Example usage for org.apache.commons.lang StringUtils substring

List of usage examples for org.apache.commons.lang StringUtils substring

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substring.

Prototype

public static String substring(String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:gemlite.core.webapp.tools.ClusterController.java

/**
 * hoemDir/*from w w w .j  av a  2  s .c  om*/
U
 * /home/gemfire/order
 * @param homeDir
 * @return
 */
private String getParentDir(String homeDir) {
    if (StringUtils.endsWith(homeDir, "/"))
        homeDir = StringUtils.substring(homeDir, 0, homeDir.length() - 1);
    int index = StringUtils.lastIndexOf(homeDir, "/");
    String left = StringUtils.substring(homeDir, 0, index);
    return left;
}

From source file:net.jadler.Request.java

private KeyValues readParametersFromString(final String parametersString) {
    KeyValues res = new KeyValues();

    if (StringUtils.isBlank(parametersString)) {
        return res;
    }// ww w .  java 2  s  . c  o m

    final String[] pairs = parametersString.split("&");

    for (final String pair : pairs) {
        final int idx = pair.indexOf('=');
        if (idx > -1) {
            final String name = StringUtils.substring(pair, 0, idx);
            final String value = StringUtils.substring(pair, idx + 1);
            res = res.add(name, value);

        } else {
            res = res.add(pair, "");
        }
    }

    return res;
}

From source file:com.google.gdt.eclipse.designer.gwtext.model.widgets.MultiFieldPanelInfo.java

private void setWidth0(WidgetInfo widget, Object _value) throws Exception {
    String value;/*from  w w  w.  j a  v  a  2s.  co m*/
    if (_value instanceof String) {
        value = (String) _value;
    } else {
        value = "100";
    }
    //
    AstEditor editor = getEditor();
    if (widget.getAssociation() instanceof InvocationChildAssociation) {
        InvocationChildAssociation association = (InvocationChildAssociation) widget.getAssociation();
        MethodInvocation invocation = association.getInvocation();
        // set percent
        if (value.endsWith("%")) {
            ColumnLayoutDataInfo columnData;
            if (association.getDescription().getSignature().endsWith(",int)")) {
                columnData = setWidth_addColumnLayoutData(widget, invocation);
            } else {
                columnData = widget.getChildren(ColumnLayoutDataInfo.class).get(0);
            }
            // set "columnWidth" property
            {
                value = StringUtils.substring(value, 0, -1);
                double weight = Integer.parseInt(value) / 100.0;
                columnData.setWidth(weight);
            }
            // done
            return;
        }
        // set absolute value
        {
            Expression expression = DomGenerics.arguments(invocation).get(1);
            editor.replaceExpression(expression, value);
            editor.replaceInvocationBinding(invocation);
            for (JavaInfo columnData : widget.getChildren(ColumnLayoutDataInfo.class)) {
                columnData.delete();
            }
        }
    }
}

From source file:ext.services.xml.XMLUtils.java

/**
 * Return a DOM document for a given string <br>
 * In case of parsing error, this method handles the exception and null is
 * returned./*from  w  ww  .  j a va2 s . co m*/
 * 
 * @param xml the string to parse
 * 
 * @return a DOM document for a given string
 */
public static Document getDocument(String xml) {
    Document out = null;
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Reader reader = new CharArrayReader(xml.toCharArray());
        out = builder.parse(new InputSource(reader));
    } catch (Exception e) {
        // print first 500 characters of string that cannot be parsed...
        Log.debug("First 500 characters of XML: " + StringUtils.substring(xml, 0, 500));
        Log.error(e);
    }
    return out;
}

From source file:com.tesora.dve.dbc.ServerDBConnection.java

public int executeUpdate(byte[] sql) throws SQLException {
    initialize();/*from   www  .j  a  v  a2 s.c  o  m*/

    final MysqlTextResultCollector resultConsumer = new MysqlTextResultCollector();
    try {
        executeInContext(resultConsumer, sql);

        // Not the most optimal but it's the quickest way to use rows affected vs rows changed settings
        int ret = (int) resultConsumer.getNumRowsAffected();
        if (ret == 0 && resultConsumer.getInfoString() != null
                && !StringUtils.startsWithIgnoreCase(resultConsumer.getInfoString(), "Rows matched: 0")) {
            int start = StringUtils.indexOf(resultConsumer.getInfoString(), "Rows matched: ")
                    + "Rows matched: ".length();
            int end = StringUtils.indexOf(resultConsumer.getInfoString(), "Changed:");
            try {
                ret = Integer.valueOf(StringUtils.substring(resultConsumer.getInfoString(), start, end).trim());
            } catch (Exception e) {
                // do nothing take original value
            }
        }

        return ret;
    } catch (SchemaException se) {
        throw ErrorMapper.makeException(se);
    } catch (Throwable t) {
        throw new SQLException(t);
    } finally {
        ssCon.releaseNonTxnLocks();
    }
}

From source file:net.jadler.stubbing.Request.java

private MultiMap readParametersFromString(final String parametersString) {
    final MultiMap res = new MultiValueMap();

    if (StringUtils.isBlank(parametersString)) {
        return res;
    }/*from   w  w w.j ava 2s . c  om*/

    final String enc = this.getEncodingInternal();
    final String[] pairs = parametersString.split("&");

    for (final String pair : pairs) {
        final int idx = pair.indexOf('=');
        if (idx > -1) {

            try {
                final String name = URLDecoder.decode(StringUtils.substring(pair, 0, idx), enc);
                final String value = URLDecoder.decode(StringUtils.substring(pair, idx + 1), enc);
                res.put(name, value);
            } catch (final UnsupportedEncodingException ex) {
                //indeed
            }
        } else {
            try {
                res.put(URLDecoder.decode(pair, enc), "");
            } catch (final UnsupportedEncodingException ex) {
                //no way
            }
        }
    }

    return res;
}

From source file:de.tudarmstadt.ukp.dkpro.core.lingpipe.LingPipeNamedEntityRecognizer.java

@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
    super.initialize(aContext);

    modelProvider = new ModelProviderBase<Chunker>(this, "lingpipe", "ner") {
        @Override/* w  w w  . java2  s.  c  o m*/
        protected Chunker produceResource(InputStream aStream) throws Exception {
            ObjectInputStream ois = new ObjectInputStream(aStream);
            Chunker chunker = (Chunker) ois.readObject();

            System.out.println(chunker.getClass());

            SingletonTagset tags = new SingletonTagset(NamedEntity.class, null);
            if (chunker instanceof HmmChunker) {
                HiddenMarkovModel hmm = ((HmmChunker) chunker).getDecoder().getHmm();

                List<String> prefixes = asList("B_", "M_", "E_", "W_", "BB_O_", "EE_O_", "WW_O_");

                for (int n = 0; n < hmm.stateSymbolTable().numSymbols(); n++) {
                    String tag = hmm.stateSymbolTable().idToSymbol(n);

                    if (prefixes.contains(StringUtils.substring(tag, 0, 5))) {
                        tag = tag.substring(5);
                    } else if (prefixes.contains(StringUtils.substring(tag, 0, 2))) {
                        tag = tag.substring(2);
                    }
                    if ("BOS".equals(tag) || "MM_O".equals(tag)) {
                        // BOS is reserved by the system
                        continue;
                    }

                    tags.add(tag);
                }
            } else if (chunker instanceof TokenShapeChunker) {
                Object decoder = FieldUtils.readField(chunker, "mDecoder", true);
                Object estimator = FieldUtils.readField(decoder, "mEstimator", true);
                SymbolTable tagTable = (SymbolTable) FieldUtils.readField(estimator, "mTagSymbolTable", true);
                for (int n = 0; n < tagTable.numSymbols(); n++) {
                    String tag = tagTable.idToSymbol(n);
                    // Handle BIO encoding
                    if (tag.startsWith("B-") || tag.startsWith("I-")) {
                        tag = tag.substring(2);
                    }
                    if ("O".equals(tag)) {
                        continue;
                    }
                    tags.add(tag);
                }
            } else if (chunker instanceof AbstractCharLmRescoringChunker) {
                @SuppressWarnings("unchecked")
                Map<String, Character> typeToChar = (Map<String, Character>) FieldUtils.readField(chunker,
                        "mTypeToChar", true);
                for (String tag : typeToChar.keySet()) {
                    tags.add(tag);
                }
            }
            addTagset(tags);

            if (printTagSet) {
                getContext().getLogger().log(INFO, tags.toString());
            }

            return chunker;
        }
    };

    mappingProvider = new MappingProvider();
    mappingProvider
            .setDefaultVariantsLocation("de/tudarmstadt/ukp/dkpro/core/lingpipe/lib/ner-default-variants.map");
    mappingProvider.setDefault(MappingProvider.LOCATION,
            "classpath:/de/tudarmstadt/ukp/dkpro/" + "core/lingpipe/lib/ner-${language}-${variant}.map");
    mappingProvider.setDefault(MappingProvider.BASE_TYPE, NamedEntity.class.getName());
    mappingProvider.setOverride(MappingProvider.LOCATION, mappingLocation);
    mappingProvider.setOverride(MappingProvider.LANGUAGE, language);
    mappingProvider.setOverride(MappingProvider.VARIANT, variant);
}

From source file:gov.nih.nci.cabig.caaers.utils.pdf.MedwatchUtils.java

public static String after(String sentence, int n) {

    int l = sentence.length();
    if (n >= l)
        return "";

    char c = sentence.charAt(n);
    if (c == ' ' || c == '\n')
        return sentence.substring(n + 1);

    int lastIndex = n;
    String s1 = StringUtils.substring(sentence, 0, n);
    int a = s1.lastIndexOf('\n');
    int b = s1.lastIndexOf(' ');
    lastIndex = (a > b) ? a : b;/*  w  ww. j a v a 2s  .  co  m*/

    return sentence.substring(lastIndex + 1);

}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

protected void initAppProperties(ServletContext sc) {
    // get properties from web.xml
    String appProperties = sc.getInitParameter(APP_PROPS_PARAM);
    if (appProperties != null) {
        StrTokenizer tokenizer = new StrTokenizer(appProperties);
        for (String str : tokenizer.getTokenArray()) {
            int i = str.indexOf("=");
            if (i < 0)
                continue;
            String name = StringUtils.substring(str, 0, i);
            String value = StringUtils.substring(str, i + 1);
            if (!StringUtils.isBlank(name)) {
                AppContext.setProperty(name, value);
            }/*from w w w . ja  v  a 2  s.c  o m*/
        }
    }

    // get properties from a set of app.properties files defined in web.xml
    String propsConfigName = getAppPropertiesConfig(sc);
    if (propsConfigName == null)
        throw new IllegalStateException(APP_PROPS_CONFIG_PARAM + " servlet context parameter not defined");

    final Properties properties = new Properties();

    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    StrTokenizer tokenizer = new StrTokenizer(propsConfigName);
    tokenizer.setQuoteChar('"');
    for (String str : tokenizer.getTokenArray()) {
        log.trace("Processing properties location: {}", str);
        str = StrSubstitutor.replaceSystemProperties(str);
        InputStream stream = null;
        try {
            if (ResourceUtils.isUrl(str) || str.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
                Resource resource = resourceLoader.getResource(str);
                if (resource.exists())
                    stream = resource.getInputStream();
            } else {
                stream = sc.getResourceAsStream(str);
            }

            if (stream != null) {
                log.info("Loading app properties from {}", str);
                try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                    properties.load(reader);
                }
            } else {
                log.trace("Resource {} not found, ignore it", str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    for (Object key : properties.keySet()) {
        AppContext.setProperty((String) key, properties.getProperty((String) key).trim());
    }
}

From source file:com.thoughtworks.gauge.autocomplete.StepCompletionProvider.java

private void replaceElement(TemplateBuilder templateBuilder, PsiElement stepParam, String replacementText) {
    String substring = StringUtils.substring(replacementText, 1, replacementText.length() - 1);
    templateBuilder.replaceElement(stepParam, new TextRange(1, replacementText.length() - 1), substring);
}