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

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

Introduction

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

Prototype

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

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

A negative start position can be used to start/end n characters from the end of the String.

The returned substring starts with the character in the start position and ends before the end position.

Usage

From source file:com.dgtlrepublic.anitomyj.Tokenizer.java

/**
 * Adds a token to the internal list of tokens.
 *
 * @param category the token category// w  ww  .j  a v a  2s . c  o  m
 * @param enclosed whether or not the token is enclosed in braces
 * @param range    the token range
 */
private void addToken(TokenCategory category, boolean enclosed, TokenRange range) {
    tokens.add(new Token(category,
            StringUtils.substring(filename, range.getOffset(), range.getOffset() + range.getSize()), enclosed));
}

From source file:com.quinsoft.zeidon.dbhandler.StandardJdbcTranslator.java

protected boolean appendString(SqlStatement stmt, StringBuilder buffer, Object value) {
    String str = value.toString();
    if (str.length() > MAX_INLINE_STRING_LENGTH || bindAllValues) {
        if (getTask().dblog().isTraceEnabled())
            getTask().dblog().trace("Bound string: length = %d, value = %s...", str.length(),
                    StringUtils.substring(str, 0, 50));

        stmt.addBoundAttribute(buffer, value);
    } else {//  w  w w.  ja v a 2  s. co  m
        buffer.append("'").append(StringUtils.replace(str, "'", "''")).append("'");
    }

    return true;
}

From source file:com.thinkbiganalytics.metadata.jpa.app.JpaKyloVersionProvider.java

private KyloVersion parseVersionString(String versionString) {

    if (versionString != null) {
        JpaKyloVersion kyloVersion = new JpaKyloVersion();
        //Major version ends before second period
        //i.e.  v 0.3.0    0.3
        int beforeIndex = StringUtils.ordinalIndexOf(versionString, ".", 2);
        String majorVersionString = StringUtils.substring(versionString, 0, beforeIndex);
        String minorVersion = StringUtils.substring(versionString, (beforeIndex + 1));
        kyloVersion.setMajorVersion(majorVersionString);
        kyloVersion.setMinorVersion(minorVersion);
        return kyloVersion;
    }/*from   w  ww.  jav a  2s  . c o m*/
    return null;

}

From source file:com.thruzero.common.core.utils.MapUtilsExt.java

/**
 * Takes the comma separated series of keys and returns a {@code Map} of key/value pairs (trimming each key segment
 * before lookup).//from   w  w  w  .  java2  s  .c  o m
 *
 * @param commaSeparatedKeys series of key names (e.g., "foo, bar").
 * @return key/value pair for each key in the series.
 */
public static <K, V> Map<String, String> getValueAsStringMap(final K key, final Map<K, V> map) {
    Object mapValue = map.get(key);

    if (mapValue == null) {
        return null;
    } else {
        Map<String, String> result = new LinkedHashMap<String, String>();
        String[] pairs = StringUtils.split(mapValue.toString(), ']');

        for (String string : pairs) {
            String[] values = StringUtils.split(StringUtils.substring(string, 1, string.length() - 1), ',');
            result.put(values[0], values[1].trim());
        }

        return result;
    }
}

From source file:com.mirth.connect.donkey.model.channel.MetaDataColumnType.java

/**
 * Returns an object for a metadata value that is casted to the correct type
 * /*from   w ww.ja  va  2  s. c o  m*/
 * @throws MetaDataColumnException
 *             If an error occurred while attempting to cast the value
 */
public Object castValue(Object value) throws MetaDataColumnException {
    if (value == null) {
        return null;
    }

    try {
        switch (this) {
        case BOOLEAN:
            return (Boolean) new BooleanConverter().convert(Boolean.class, value);
        case NUMBER:
            BigDecimal number = (BigDecimal) new BigDecimalConverter().convert(BigDecimal.class, value);
            if (number.compareTo(MAX_NUMBER_VALUE) >= 0) {
                throw new Exception("Number " + String.valueOf(number)
                        + " is greater than or equal to the maximum allowed value of 10^16.");
            }
            return number;
        case STRING:
            String string = (String) new StringConverter().convert(String.class, value);
            if (string.length() > 255) {
                string = StringUtils.substring(string, 0, 255);
            }
            return string;
        case TIMESTAMP:
            return new DateParser().parse(value.toString());
        }
    } catch (Exception e) {
        throw new MetaDataColumnException(e);
    }

    throw new MetaDataColumnException("Unrecognized MetaDataColumnType");
}

From source file:com.quinsoft.zeidon.standardoe.WriteOisToXmlStream.java

private void write(String string) {
    try {//from www.j av  a 2s  .  co m
        writer.write(string);
    } catch (IOException e) {
        throw ZeidonException.wrapException(e).appendMessage("Attempting to write: %s",
                StringUtils.substring(string, 0, 100));
    }
}

From source file:com.thoughtworks.go.server.service.AccessTokenService.java

public AccessToken findByAccessToken(String actualToken) {
    if (actualToken.length() != 40) {
        throw new InvalidAccessTokenException();
    }/*from  w w w.j av a2  s .  c o m*/

    String saltId = StringUtils.substring(actualToken, 0, 8);

    AccessToken token = accessTokenDao.findAccessTokenBySaltId(saltId);
    if (token == null) {
        throw new InvalidAccessTokenException();
    }

    boolean isValid = token.isValidToken(actualToken);

    if (!isValid) {
        throw new InvalidAccessTokenException();
    }

    if (token.isRevoked()) {
        throw new RevokedAccessTokenException(token.getRevokedAt());
    }

    return token;
}

From source file:com.dominion.salud.nomenclator.negocio.service.impl.farmatools.InteracGgServiceImpl.java

@Override
public void autoload() {
    logger.info("INICIANDO la carga de INTERACCIONES_GG automatizadas");

    Set<String> mensajes = new HashSet<>();
    List<AtcInteracciones> listaAtcInteracciones = atcInteraccionesService.findAll();

    if (listaAtcInteracciones != null && !listaAtcInteracciones.isEmpty()) {
        logger.debug("     Se han obtenido: " + listaAtcInteracciones.size() + " INTERACCIONES_GG");
        Iterator<AtcInteracciones> iteradorAtcInteracciones = listaAtcInteracciones.iterator();
        int contador = 1;

        while (iteradorAtcInteracciones.hasNext()) {
            logger.debug("          Cargando INTERACCION_GG (" + contador + " de "
                    + listaAtcInteracciones.size() + ")");
            AtcInteracciones atcInteracciones = iteradorAtcInteracciones.next();

            try {
                InteracGg interacGg = new InteracGg();
                InteracGgPK interacGgPK = new InteracGgPK();

                interacGgPK.setGrupo1(atcInteracciones.getAtc().getCodAtc());
                interacGgPK.setGrupo2(atcInteracciones.getInteraccion().getCodAtc());
                interacGg.setInteracGgPK(interacGgPK);
                interacGg.setDesInterac(atcInteracciones.getEfecto());
                interacGg.setDesNaturaleza(StringUtils.substring(atcInteracciones.getOrientacion(), 0, 200));
                interacGg.setObservacion(StringUtils.substring(atcInteracciones.getDescripcion(), 0, 60));

                try {
                    interacGg = interacGgRepository.findOne(interacGg);
                    logger.debug("               INTERACCION_GG ya existe: " + interacGg);
                } catch (NoResultException nre) {
                    logger.debug("               INTERACCION_GG NO existe. Almacenando: " + interacGg);
                    interacGgRepository.save(interacGg);
                }/*from   w  ww  .j  a  v  a  2s.com*/

                logger.debug("                    " + interacGg.toString());
                logger.debug("               INTERACCION_GG creada correctamente");

                contador++;
            } catch (Exception e) {
                logger.error("               No se ha podido generar la INTERACCION_GG: " + e.toString());
                mensajes.add("No se ha podido generar la INTERACCION_GG: " + e.toString());
            }
        }
    }

    if (!mensajes.isEmpty()) {
        logger.warn("     Se han producido los siguientes errores en la carga de registros: ");
        Iterator<String> iteradorMensajes = mensajes.iterator();
        while (iteradorMensajes.hasNext()) {
            logger.warn("          - " + iteradorMensajes.next());
        }
    }

    logger.info("FINALIZANDO la carga de INTERACCIONES_GG automatizadas");
}

From source file:annis.gui.docbrowser.DocBrowserController.java

public void openDocVis(String corpus, String doc, Visualizer visConfig, Button btn) {

    final String canonicalTitle = corpus + " > " + doc + " - " + "Visualizer: " + visConfig.getDisplayName();
    final String tabCaption = StringUtils.substring(canonicalTitle, 0, 15) + "...";

    if (visibleVisHolder.containsKey(canonicalTitle)) {
        Panel visHolder = visibleVisHolder.get(canonicalTitle);
        ui.getTabSheet().setSelectedTab(visHolder);
        return;// w  w w.j  ava 2 s  .  c o m
    }

    Panel visHolder = new Panel();
    visHolder.setSizeFull();
    visHolder.addDetachListener(new ClientConnector.DetachListener() {
        @Override
        public void detach(ClientConnector.DetachEvent event) {
            visibleVisHolder.remove(canonicalTitle);
        }
    });

    // first set loading indicator
    ProgressBar progressBar = new ProgressBar(1.0f);
    progressBar.setIndeterminate(true);
    progressBar.setSizeFull();
    VerticalLayout layoutProgress = new VerticalLayout(progressBar);
    layoutProgress.setSizeFull();
    layoutProgress.setComponentAlignment(progressBar, Alignment.MIDDLE_CENTER);

    visHolder.setContent(layoutProgress);

    Tab visTab = ui.getTabSheet().addTab(visHolder, tabCaption);
    visTab.setDescription(canonicalTitle);
    visTab.setIcon(EYE_ICON);
    visTab.setClosable(true);
    ui.getTabSheet().setSelectedTab(visTab);

    // register visible visHolder
    this.visibleVisHolder.put(canonicalTitle, visHolder);

    PollControl.runInBackground(100, ui, new DocVisualizerFetcher(corpus, doc, canonicalTitle,
            visConfig.getType(), visHolder, visConfig, btn, UI.getCurrent()));
}

From source file:com.adguard.filter.rules.CssFilterRule.java

/**
 * Creates CSS filter rule//from  w  w w . j  a v a 2 s.  c om
 *
 * @param ruleText Rule text
 */
public CssFilterRule(String ruleText) {
    super(ruleText);

    String mask;
    boolean styleInject = false;
    boolean whiteListRule = false;
    if (StringUtils.contains(ruleText, MASK_CSS_INJECT_EXCEPTION_RULE)) {
        mask = MASK_CSS_INJECT_EXCEPTION_RULE;
        whiteListRule = true;
        styleInject = true;
    } else if (StringUtils.contains(ruleText, MASK_CSS_INJECT_RULE)) {
        mask = MASK_CSS_INJECT_RULE;
        styleInject = true;
    } else if (StringUtils.contains(ruleText, MASK_CSS_EXCEPTION_RULE)) {
        mask = MASK_CSS_EXCEPTION_RULE;
        whiteListRule = true;
    } else if (StringUtils.contains(ruleText, MASK_CSS_RULE)) {
        mask = MASK_CSS_RULE;
    } else {
        throw new IllegalArgumentException("ruleText");
    }

    int indexOfMask = StringUtils.indexOf(ruleText, mask);
    if (indexOfMask > 0) {
        // domains are specified, parsing
        String domains = StringUtils.substring(ruleText, 0, indexOfMask);
        loadDomains(domains);
    }

    this.styleInject = styleInject;
    this.whiteListRule = whiteListRule;
    cssContent = ruleText.substring(indexOfMask + mask.length());
}