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:org.openconcerto.sql.model.SQLBase.java

private final static String quote(final SQLBase b, final String pattern, Object... params) {
    final Matcher m = percent.matcher(pattern);
    final StringBuffer sb = new StringBuffer();
    int i = 0;/*from   w  ww. j ava2  s.  co m*/
    int lastAppendPosition = 0;
    while (m.find()) {
        final String replacement;
        final char modifier = m.group().charAt(m.group().length() - 1);
        if (modifier == '%') {
            replacement = "%";
        } else {
            final Object param = params[i++];
            if (modifier == 's') {
                replacement = quoteString(b, param.toString());
            } else if (modifier == 'i') {
                if (param instanceof SQLName)
                    replacement = ((SQLName) param).quote();
                else
                    replacement = quoteIdentifier(param.toString());
            } else {
                final SQLIdentifier ident = (SQLIdentifier) ((DBStructureItem<?>) param).getJDBC();
                if (modifier == 'f') {
                    replacement = ident.getSQLName().quote();
                } else if (modifier == 'n')
                    replacement = quoteIdentifier(ident.getName());
                else
                    throw new IllegalArgumentException("unknown modifier: " + modifier);
            }
        }

        // do NOT use appendReplacement() (and appendTail()) since it parses \ and $
        // Append the intervening text
        sb.append(pattern.subSequence(lastAppendPosition, m.start()));
        // Append the match substitution
        sb.append(replacement);
        lastAppendPosition = m.end();
    }
    sb.append(pattern.substring(lastAppendPosition));
    return sb.toString();
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageParser.java

private void pageImport(String value) {
    // LOG.debug("pageImport(" + value + ')');
    String[] imports = Pattern.compile(";").split(value.subSequence(0, value.length()));
    for (int ix = 0; ix < imports.length; ix++) {
        out.print("import ");
        out.print(imports[ix]);/*  ww  w  . j  a  va2  s  . com*/
        out.println();
    }
}

From source file:org.eclipse.mylyn.github.internal.GitHubService.java

/**
 * Remove an existing label from an existing GitHub issue.
 * //from ww  w .j a  v  a 2  s .c om
 * @param user
 *            - The user the repository is owned by
 * @param repo
 *            - The git repository where the issue tracker is hosted
 * @param label
 * @param issueNumber
 * @param api
 * 
 * @return A list of GitHub issues in the response text.
 * 
 * @throws GitHubServiceException
 * 
 *             API Doc: issues/label/remove/:user/:repo/:label/:number API
 *             POST Variables: login, api-token
 */
public boolean removeLabel(final String user, final String repo, final String label, final int issueNumber,
        final GitHubCredentials credentials) throws GitHubServiceException {
    PostMethod method = null;
    boolean success = false;
    try {
        // build HTTP GET method
        method = new PostMethod(gitURLBase + gitIssueRoot + REMOVE_LABEL + user + "/" + repo + "/" + label + "/"
                + Integer.toString(issueNumber));

        // Set the users login and API token
        final NameValuePair login = new NameValuePair("login", credentials.getUsername());
        final NameValuePair token = new NameValuePair("token", credentials.getUsername());
        method.setRequestBody(new NameValuePair[] { login, token });

        // execute HTTP GET method
        executeMethod(method);
        // Check the response, make sure the action was successful
        final String response = method.getResponseBodyAsString();
        if (!response.contains(label.subSequence(0, label.length()))) {
            success = true;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Response: " + method.getResponseBodyAsString());
            LOG.debug("URL: " + method.getURI());
        }
    } catch (GitHubServiceException e) {
        throw e;
    } catch (final RuntimeException runtimeException) {
        throw runtimeException;
    } catch (final Exception exception) {
        throw new GitHubServiceException(exception);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return success;
}

From source file:org.eclipse.mylyn.github.internal.GitHubService.java

/**
 * Add a label to an existing GitHub issue.
 * //from  ww  w  .j av  a 2  s.  c o m
 * @param user
 *            - The user the repository is owned by
 * @param repo
 *            - The git repository where the issue tracker is hosted
 * @param label
 *            - The text label to add to the existing issue
 * @param issueNumber
 *            - The issue number to add a label to
 * @param api
 *            - The users GitHub
 * 
 * @return A boolean representing the success of the function call
 * 
 * @throws GitHubServiceException
 * 
 * @note API Doc: issues/label/add/:user/:repo/:label/:number API POST
 *       Variables: login, api-token
 */
public boolean addLabel(final String user, final String repo, final String label, final int issueNumber,
        final GitHubCredentials credentials) throws GitHubServiceException {
    PostMethod method = null;

    boolean success = false;

    try {
        // build HTTP GET method
        method = new PostMethod(gitURLBase + gitIssueRoot + ADD_LABEL + user + "/" + repo + "/" + label + "/"
                + Integer.toString(issueNumber));

        // Set the users login and API token
        final NameValuePair login = new NameValuePair("login", credentials.getUsername());
        final NameValuePair token = new NameValuePair("token", credentials.getApiToken());
        method.setRequestBody(new NameValuePair[] { login, token });

        // execute HTTP GET method
        executeMethod(method);
        // Check the response, make sure the action was successful
        final String response = method.getResponseBodyAsString();
        if (response.contains(label.subSequence(0, label.length()))) {
            success = true;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response: " + method.getResponseBodyAsString());
            LOG.debug("URL: " + method.getURI());
        }
    } catch (GitHubServiceException e) {
        throw e;
    } catch (final RuntimeException runtimeException) {
        throw runtimeException;
    } catch (final Exception exception) {
        throw new GitHubServiceException(exception);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return success;
}

From source file:net.momodalo.app.vimtouch.VimTouch.java

public void showCmdHistory() {

    final Dialog dialog = new Dialog(this, R.style.DialogSlideAnim);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.BOTTOM);// w  w w .  ja  va2 s . c  o  m

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.hist_list);
    dialog.setCancelable(true);

    LinearLayout layout = (LinearLayout) dialog.findViewById(R.id.hist_layout);
    if (AndroidCompat.SDK >= 11) {
        layout.setShowDividers(LinearLayout.SHOW_DIVIDER_BEGINNING | LinearLayout.SHOW_DIVIDER_MIDDLE
                | LinearLayout.SHOW_DIVIDER_END);
    }
    LayoutParams params = layout.getLayoutParams();
    params.width = mScreenWidth;
    layout.setLayoutParams(params);

    LayoutInflater inflater = LayoutInflater.from(this);
    boolean exists = false;

    for (int i = 1; i <= 10; i++) {
        TextView button = (TextView) inflater.inflate(R.layout.histbutton, layout, false);
        String cmd = Exec.getCmdHistory(i);
        if (cmd.length() == 0)
            break;
        exists = true;
        button.setText(":" + cmd);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                TextView text = (TextView) v;
                CharSequence cmd = text.getText();
                Exec.doCommand(cmd.subSequence(1, cmd.length()).toString());
                dialog.dismiss();
            }
        });
        layout.addView((View) button);
    }

    if (exists)
        dialog.show();
}

From source file:org.openmrs.hl7.HL7Util.java

/**
 * Converts an HL7 timestamp into a java.util.Date object. HL7 timestamps can be created with
 * varying levels of precision &mdash; e.g., just the year or just the year and month, etc.
 * Since java.util.Date cannot store a partial value, we fill in defaults like January, 01 at
 * midnight within the current timezone.
 *
 * @param s HL7 timestamp to be parsed// w  w w  .  j  ava 2s . c  o  m
 * @return Date object
 * @throws HL7Exception
 * @should fail on 78
 * @should handle 1978
 * @should fail on 19784
 * @should handle 197804
 * @should fail on 197841
 * @should handle 19780411
 * @should fail on 197804116
 * @should handle 1978041106
 * @should fail on 19780411065
 * @should handle 197804110615
 * @should fail on 1978041106153
 * @should handle 19780411061538
 * @should handle 19780411061538.1
 * @should handle 19780411061538.12
 * @should handle 19780411061538.123
 * @should handle 19780411061538.1234
 * @should fail on 197804110615-5
 * @should handle 197804110615-05
 * @should handle 197804110615-0200
 * @should not flub dst with 20091225123000
 */
public static Date parseHL7Timestamp(String s) throws HL7Exception {

    // HL7 dates must at least contain year and cannot exceed 24 bytes
    if (s == null || s.length() < 4 || s.length() > 24) {
        throw new HL7Exception("Invalid date '" + s + "'");
    }

    StringBuffer dateString = new StringBuffer();
    dateString.append(s.substring(0, 4)); // year
    if (s.length() >= 6) {
        dateString.append(s.substring(4, 6)); // month
    } else {
        dateString.append("01");
    }
    if (s.length() >= 8) {
        dateString.append(s.substring(6, 8)); //day
    } else {
        dateString.append("01");
    }

    // Parse timezone (optional in HL7 format)
    String timeZoneOffset;
    try {
        Date parsedDay = new SimpleDateFormat("yyyyMMdd").parse(s.substring(0, 8));
        timeZoneOffset = getTimeZoneOffset(s, parsedDay);
    } catch (ParseException e) {
        throw new HL7Exception(
                "Error parsing date: '" + s.substring(0, 8) + "' for time zone offset'" + s + "'", e);
    }
    s = s.replace(timeZoneOffset, ""); // remove the timezone from the string

    if (s.length() >= 10) {
        dateString.append(s.substring(8, 10)); // hour
    } else {
        dateString.append("00");
    }
    if (s.length() >= 12) {
        dateString.append(s.substring(10, 12)); // minute
    } else {
        dateString.append("00");
    }
    if (s.length() >= 14) {
        dateString.append(s.substring(12, 14)); // seconds
    } else {
        dateString.append("00");
    }
    if (s.length() >= 15 && s.charAt(14) != '.') {
        // decimal point
        throw new HL7Exception("Invalid date format '" + s + "'");
    } else {
        dateString.append(".");
    }
    if (s.length() >= 16) {
        dateString.append(s.substring(15, 16)); // tenths
    } else {
        dateString.append("0");
    }
    if (s.length() >= 17) {
        dateString.append(s.substring(16, 17)); // hundredths
    } else {
        dateString.append("0");
    }
    if (s.length() >= 18) {
        dateString.append(s.subSequence(17, 18)); // milliseconds
    } else {
        dateString.append("0");
    }

    dateString.append(timeZoneOffset);

    Date date;
    try {
        date = new SimpleDateFormat(TIMESTAMP_FORMAT).parse(dateString.toString());
    } catch (ParseException e) {
        throw new HL7Exception("Error parsing date '" + s + "'");
    }
    return date;
}

From source file:cn.sinobest.jzpt.framework.utils.string.StringUtils.java

/**
 * $[key}properties//from ww  w .  j  av a2  s  .  co  m
 *
 * @param s
 * @param prop
 * @return
 */
public static String convertProperty(String s, Properties prop) {
    int i = s.indexOf("${");
    if (i > -1) {
        StringBuilder sb = new StringBuilder();
        int j = -1;
        while (i > -1) {
            sb.append(s.subSequence(j + 1, i));
            j = s.indexOf('}', i + 1);
            String key = "";
            if (j > 0) {// Invalid block
                key = s.substring(i + 2, j);
            } else {
                j = s.indexOf("${", i + 2) - 1;// 
                if (j < 0) {
                    j = s.length() - 1;
                }
            }
            if (StringUtils.isEmpty(key)) {
                sb.append(s.subSequence(i, j + 1));// J
            } else {
                String value = prop.getProperty(key);
                if (value != null)
                    sb.append(value);
            }
            i = s.indexOf("${", j);
        }
        sb.append(s.substring(j + 1));
        return sb.toString();
    }
    return s;

}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public void startRoutine(Device device, String utterance) throws IOException, URISyntaxException {
    JsonAutomation found = null;/*from w  w  w . j  a  va2 s  .  c  om*/
    String deviceLocale = "";
    for (JsonAutomation routine : getRoutines()) {
        Trigger[] triggers = routine.triggers;
        if (triggers != null && routine.sequence != null) {
            for (JsonAutomation.Trigger trigger : triggers) {
                if (trigger == null) {
                    continue;
                }
                Payload payload = trigger.payload;
                if (payload == null) {
                    continue;
                }
                if (StringUtils.equalsIgnoreCase(payload.utterance, utterance)) {
                    found = routine;
                    deviceLocale = payload.locale;
                    break;
                }
            }
        }
    }
    if (found != null) {
        String sequenceJson = gson.toJson(found.sequence);

        JsonStartRoutineRequest request = new JsonStartRoutineRequest();
        request.behaviorId = found.automationId;

        // replace tokens

        // "deviceType":"ALEXA_CURRENT_DEVICE_TYPE"
        String deviceType = "\"deviceType\":\"ALEXA_CURRENT_DEVICE_TYPE\"";
        String newDeviceType = "\"deviceType\":\"" + device.deviceType + "\"";
        sequenceJson = sequenceJson.replace(deviceType.subSequence(0, deviceType.length()),
                newDeviceType.subSequence(0, newDeviceType.length()));

        // "deviceSerialNumber":"ALEXA_CURRENT_DSN"
        String deviceSerial = "\"deviceSerialNumber\":\"ALEXA_CURRENT_DSN\"";
        String newDeviceSerial = "\"deviceSerialNumber\":\"" + device.serialNumber + "\"";
        sequenceJson = sequenceJson.replace(deviceSerial.subSequence(0, deviceSerial.length()),
                newDeviceSerial.subSequence(0, newDeviceSerial.length()));

        // "customerId": "ALEXA_CUSTOMER_ID"
        String customerId = "\"customerId\":\"ALEXA_CUSTOMER_ID\"";
        String newCustomerId = "\"customerId\":\""
                + (StringUtils.isEmpty(this.accountCustomerId) ? device.deviceOwnerCustomerId
                        : this.accountCustomerId)
                + "\"";
        sequenceJson = sequenceJson.replace(customerId.subSequence(0, customerId.length()),
                newCustomerId.subSequence(0, newCustomerId.length()));

        // "locale": "ALEXA_CURRENT_LOCALE"
        String locale = "\"locale\":\"ALEXA_CURRENT_LOCALE\"";
        String newlocale = StringUtils.isNotEmpty(deviceLocale) ? "\"locale\":\"" + deviceLocale + "\""
                : "\"locale\":null";
        sequenceJson = sequenceJson.replace(locale.subSequence(0, locale.length()),
                newlocale.subSequence(0, newlocale.length()));

        request.sequenceJson = sequenceJson;

        String requestJson = gson.toJson(request);
        makeRequest("POST", alexaServer + "/api/behaviors/preview", requestJson, true, true, null);
    } else {
        logger.warn("Routine {} not found", utterance);
    }
}

From source file:de.csw.ontology.XWikiTextEnhancer.java

/**
 * The enhanced text contains links to the Lucene search page of the xWiki
 * system. The search terms are related to the annotated phrase.
 *//*from   w  w  w . ja  va2  s .c  o m*/
public String enhance(String text) {
    CSWGermanAnalyzer ga = new CSWGermanAnalyzer();
    TokenStream ts = null;
    StringBuilder result = new StringBuilder();

    initializeLinkIndex(text);

    try {
        Reader r = new BufferedReader(new StringReader(text));

        ts = ga.tokenStream("", r);

        CharTermAttribute charTermAttribute = ts.addAttribute(CharTermAttribute.class);
        OffsetAttribute offsetAttribute = ts.addAttribute(OffsetAttribute.class);
        TypeAttribute typeAttribute = ts.addAttribute(TypeAttribute.class);

        String term;
        int lastEndIndex = 0;

        while (ts.incrementToken()) {

            result.append(text.substring(lastEndIndex, offsetAttribute.startOffset()));
            term = String.copyValueOf(charTermAttribute.buffer(), 0, charTermAttribute.length());

            if (typeAttribute.type().equals(ConceptFilter.CONCEPT_TYPE) && isAnnotatable(offsetAttribute)) {
                log.debug("Annotating concept: " + term);
                annotateWithSearch(result,
                        text.substring(offsetAttribute.startOffset(), offsetAttribute.endOffset()), term);
            } else {
                result.append(text.substring(offsetAttribute.startOffset(), offsetAttribute.endOffset()));
            }

            lastEndIndex = offsetAttribute.endOffset();
        }
        result.append(text.subSequence(lastEndIndex, text.length()));
    } catch (IOException e) {
        Log.error("Error while processing the page content", e);
    }

    ga.close();
    return result.toString();
}

From source file:org.soybeanMilk.core.config.parser.ConfigurationParser.java

/**
 * ?Arg//from  w  ww.  j a v  a  2 s  .co m
 * @param strArg
 * @param strType
 * @return
 * @date 2012-5-8
 */
protected Arg stringToArg(String strArg, String strType) {
    Arg re = null;

    Type argType = null;
    if (strType != null && strType.length() > 0)
        argType = nameToType(strType);

    if (strArg == null || strArg.length() == 0)
        re = new ValueArg(strArg, argType);
    else {
        int len = strArg.length();
        char first = strArg.charAt(0);
        char end = strArg.charAt(len - 1);

        //
        if (Character.isDigit(first)) {
            Type wrappedType = (argType == null ? null : SbmUtils.wrapType(argType));

            if (Byte.class.equals(wrappedType)) {
                re = new ValueArg(new Byte(strArg), argType);
            } else if (Short.class.equals(wrappedType)) {
                re = new ValueArg(new Short(strArg), argType);
            } else if (Integer.class.equals(wrappedType)) {
                re = new ValueArg(new Integer(strArg), argType);
            } else if (Long.class.equals(wrappedType)) {
                re = new ValueArg(new Long(strArg), argType);
            } else if (Float.class.equals(wrappedType)) {
                re = new ValueArg(new Float(strArg), argType);
            } else if (Double.class.equals(wrappedType)) {
                re = new ValueArg(new Double(strArg), argType);
            } else if ('L' == end) {
                re = new ValueArg(new Long(strArg.substring(0, len - 1)), Long.class);
            } else if ('l' == end) {
                re = new ValueArg(new Long(strArg.substring(0, len - 1)), long.class);
            } else if ('F' == end) {
                re = new ValueArg(new Float(strArg.substring(0, len - 1)), Float.class);
            } else if ('f' == end) {
                re = new ValueArg(new Float(strArg.substring(0, len - 1)), float.class);
            } else if ('D' == end) {
                re = new ValueArg(new Double(strArg.substring(0, len - 1)), Double.class);
            } else if ('d' == end) {
                re = new ValueArg(new Double(strArg.substring(0, len - 1)), double.class);
            } else {
                boolean point = strArg.indexOf('.') >= 0;

                if (point)
                    re = new ValueArg(new Double(strArg), argType);
                else
                    re = new ValueArg(new Integer(strArg), argType);
            }
        } else if (first == '"') {
            String ue = SbmUtils.unEscape(strArg);
            len = ue.length();

            if (len < 2 || ue.charAt(len - 1) != '"')
                throw new ParseException("illegal String definition: " + strArg);

            if (len == 2)
                re = new ValueArg("", argType);
            else
                re = new ValueArg(ue.subSequence(1, len - 1), argType);
        } else if (first == '\'') {
            String ue = SbmUtils.unEscape(strArg);
            len = ue.length();

            if (len != 3 || end != '\'')
                throw new ParseException("illegal char definition: " + strArg);

            re = new ValueArg(ue.charAt(1), argType);
        } else if ("true".equals(strArg)) {
            re = new ValueArg(Boolean.TRUE, argType);
        } else if ("false".equals(strArg)) {
            re = new ValueArg(Boolean.FALSE, argType);
        } else if ("null".equals(strArg)) {
            re = new ValueArg(null, argType);
        } else
            re = new KeyArg(strArg, argType);
    }

    return re;
}