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:org.beanfuse.transfer.importer.listener.ImporterForeignerListener.java

public void endTransferItem(TransferResult tr) {
    // //from   ww w .j  a  v  a  2  s. c o  m
    for (int i = 0; i < importer.getAttrs().length; i++) { // getAttrs(),?
        String attr = importer.getAttrs()[i];

        String processed = importer.processAttr(attr);
        int foreigerKeyIndex = 0;
        boolean isforeiger = false;
        for (; foreigerKeyIndex < foreigerKeys.length; foreigerKeyIndex++) {
            if (processed.endsWith("." + foreigerKeys[foreigerKeyIndex])) {// ?
                isforeiger = true;
                break;
            }
        }
        if (!isforeiger)
            continue;

        String codeValue = (String) importer.getCurData().get(attr);
        try {
            Object foreiger = null;
            // ?
            if (StringUtils.isEmpty(codeValue))
                continue;
            Object entity = null;
            if (multiEntity) {
                entity = ((MultiEntityImporter) importer).getCurrent(attr);
            } else {
                entity = importer.getCurrent();
            }

            attr = importer.processAttr(attr);
            Object nestedForeigner = PropertyUtils.getProperty(entity,
                    StringUtils.substring(attr, 0, attr.lastIndexOf(".")));

            if (nestedForeigner instanceof Entity) {
                String className = EntityUtils.getEntityClassName(nestedForeigner.getClass());
                Map foreignerMap = (Map) foreigersMap.get(className);
                if (null == foreignerMap) {
                    foreignerMap = new HashMap();
                    foreigersMap.put(className, foreignerMap);
                }
                if (foreignerMap.size() > CACHE_SIZE)
                    foreignerMap.clear();
                foreiger = foreignerMap.get(codeValue);
                if (foreiger == null) {
                    List foreigners = entityDao.load(Class.forName(className), foreigerKeys[foreigerKeyIndex],
                            new Object[] { codeValue });
                    if (!foreigners.isEmpty()) {
                        foreiger = foreigners.iterator().next();
                        foreignerMap.put(codeValue, foreiger);
                    } else {
                        tr.addFailure("error.model.notExist", codeValue);
                    }
                }
            }
            String parentAttr = StringUtils.substring(attr, 0, attr.lastIndexOf("."));
            Model.getPopulator().populateValue(parentAttr, foreiger, entity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.beangle.commons.converters.DateConverter.java

/**
 * ?<br>/*from  w ww. ja  va2 s . com*/
 * format 1: yyyy-MM-dd hh:mm:ss<br>
 * format 2: yyyyMMdd
 */
@SuppressWarnings("rawtypes")
protected Object convertToDate(final Class type, final Object value) {
    if (StringUtils.isEmpty((String) value)) {
        return null;
    } else {
        String dateStr = (String) value;
        String[] times = StringUtils.split(dateStr, " ");
        String[] dateElems = null;
        if (StringUtils.contains(times[0], "-")) {
            dateElems = StringUtils.split(times[0], "-");
        } else {
            dateElems = new String[3];
            int yearIndex = "yyyy".length();
            dateElems[0] = StringUtils.substring(times[0], 0, yearIndex);
            dateElems[1] = StringUtils.substring(times[0], yearIndex, yearIndex + 2);
            dateElems[2] = StringUtils.substring(times[0], yearIndex + 2, yearIndex + 4);
        }
        Calendar gc = GregorianCalendar.getInstance();
        gc.set(Calendar.YEAR, NumberUtils.toInt(dateElems[0]));
        gc.set(Calendar.MONTH, NumberUtils.toInt(dateElems[1]) - 1);
        gc.set(Calendar.DAY_OF_MONTH, NumberUtils.toInt(dateElems[2]));
        if (times.length > 1 && StringUtils.isNotBlank(times[1])) {
            String[] timeElems = StringUtils.split(times[1], ":");
            if (timeElems.length > 0) {
                gc.set(Calendar.HOUR_OF_DAY, NumberUtils.toInt(timeElems[0]));
            }
            if (timeElems.length > 1) {
                gc.set(Calendar.MINUTE, NumberUtils.toInt(timeElems[1]));
            }
            if (timeElems.length > 2) {
                gc.set(Calendar.SECOND, NumberUtils.toInt(timeElems[2]));
            }
        }
        return gc.getTime();
    }
}

From source file:org.beangle.model.entity.populator.ConvertPopulatorBean.java

/**
 * params([attr(string)->value(object)]<br>
 * <br>//from w  w w .ja  v a2s. c om
 * paramsidnullnull.<br>
 * ??idparams null?
 * 
 * @param params
 * @param entity
 */
public Object populate(Object entity, String entityName, Map<String, Object> params) {
    Type type = Model.getType(entityName);
    for (final Map.Entry<String, Object> paramEntry : params.entrySet()) {
        String attr = paramEntry.getKey();
        Object value = paramEntry.getValue();
        if (value instanceof String) {
            if (StringUtils.isEmpty((String) value)) {
                value = null;
            } else if (TRIM_STR) {
                value = ((String) value).trim();
            }
        }
        // 
        if (null != type && type.isEntityType() && attr.equals(((EntityType) type).getIdPropertyName())) {
            if (ValidEntityKeyPredicate.INSTANCE.evaluate(value)) {
                setValue(attr, value, entity);
            } else {
                try {
                    PropertyUtils.setProperty(entity, attr, null);
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
            continue;
        }
        // 
        if (-1 == attr.indexOf('.')) {
            setValue(attr, value, entity);
        } else {
            String parentAttr = StringUtils.substring(attr, 0, attr.lastIndexOf('.'));
            try {
                ObjectAndType ot = initProperty(entity, entityName, parentAttr);
                if (null == ot) {
                    logger.error("error attr:[" + attr + "] value:[" + value + "]");
                    continue;
                }
                // 
                if (ot.getType().isEntityType()) {
                    String foreignKey = ((EntityType) ot.getType()).getIdPropertyName();
                    if (attr.endsWith("." + foreignKey)) {
                        if (null == value) {
                            setValue(parentAttr, null, entity);
                        } else {
                            Object foreignValue = PropertyUtils.getProperty(entity, attr);
                            // ?
                            if (null != foreignValue) {
                                if (!foreignValue.toString().equals(value.toString())) {
                                    setValue(parentAttr, null, entity);
                                    initProperty(entity, entityName, parentAttr);
                                    setValue(attr, value, entity);
                                }
                            } else {
                                setValue(attr, value, entity);
                            }
                        }
                    } else {
                        setValue(attr, value, entity);
                    }
                } else {
                    setValue(attr, value, entity);
                }
            } catch (Exception e) {
                logger.error("error attr:[" + attr + "] value:[" + value + "]", e);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("populate attr:[" + attr + "] value:[" + value + "]");
        }
    }
    return entity;
}

From source file:org.beangle.model.transfer.importer.listener.ImporterForeignerListener.java

public void onItemFinish(TransferResult tr) {
    // // w  w w  .  j  ava 2 s .  c  o m
    for (int i = 0; i < importer.getAttrs().length; i++) { // getAttrs(),?
        String attr = importer.getAttrs()[i];

        String processed = importer.processAttr(attr);
        int foreigerKeyIndex = 0;
        boolean isforeiger = false;
        for (; foreigerKeyIndex < foreigerKeys.length; foreigerKeyIndex++) {
            if (processed.endsWith("." + foreigerKeys[foreigerKeyIndex])) {// ?
                isforeiger = true;
                break;
            }
        }
        if (!isforeiger)
            continue;

        String codeValue = (String) importer.getCurData().get(attr);
        try {
            Object foreiger = null;
            // ?
            if (StringUtils.isEmpty(codeValue))
                continue;
            Object entity = null;
            if (multiEntity) {
                entity = ((MultiEntityImporter) importer).getCurrent(attr);
            } else {
                entity = importer.getCurrent();
            }

            attr = importer.processAttr(attr);
            Object nestedForeigner = PropertyUtils.getProperty(entity,
                    StringUtils.substring(attr, 0, attr.lastIndexOf(".")));

            if (nestedForeigner instanceof Entity<?>) {
                String className = EntityUtils.getEntityClassName(nestedForeigner.getClass());
                Map<String, Object> foreignerMap = foreigersMap.get(className);
                if (null == foreignerMap) {
                    foreignerMap = CollectUtils.newHashMap();
                    foreigersMap.put(className, foreignerMap);
                }
                if (foreignerMap.size() > CACHE_SIZE)
                    foreignerMap.clear();
                foreiger = foreignerMap.get(codeValue);
                if (foreiger == null) {
                    List<?> foreigners = entityDao.get(Class.forName(className), foreigerKeys[foreigerKeyIndex],
                            new Object[] { codeValue });
                    if (!foreigners.isEmpty()) {
                        foreiger = foreigners.iterator().next();
                        foreignerMap.put(codeValue, foreiger);
                    } else {
                        tr.addFailure("error.model.notExist", codeValue);
                    }
                }
            }
            String parentAttr = StringUtils.substring(attr, 0, attr.lastIndexOf("."));
            Model.getPopulator().populateValue(entity, parentAttr, foreiger);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.beer30.jdefault.JDefaultBase.java

/**
 * resolves an embedded key/*from  w ww. ja  v a  2  s. c  o m*/
 *
 * @param value embedded key that has been already fetched
 * @return fully resolved string
 */
protected static String parseFoundKey(String value) {
    //   System.out.println("Start Value: " + value);

    String regex = "#\\{([A-Za-z]+\\.)?([^\\}]+)\\}";
    Pattern p = Pattern.compile(regex);
    Matcher matcher = p.matcher(value);
    while (matcher.find()) {
        //         System.out.print("Start index: " + matcher.start());
        //         System.out.print(" End index: " + matcher.end() + " \n");
        String keyMatched = matcher.group().trim();
        //         System.out.println("Key: " + keyMatched);
        String trimmedKey = StringUtils.substring(keyMatched, 2, keyMatched.length() - 1);
        //         System.out.println("Trimmed Key: " + trimmedKey);
        String replacedValue = fetchString(trimmedKey);
        //         System.out.println("Replaced Value: " + replacedValue);
        if (StringUtils.contains(replacedValue, "#{")) {
            replacedValue = parseFoundKey(replacedValue);
        }
        value = StringUtils.replace(value, keyMatched, replacedValue);
        //         System.out.println("New Value: " + value);

    }
    return value;
}

From source file:org.betaconceptframework.astroboa.console.jsf.edit.SimpleCmsPropertyValueWrapper.java

public String getFirstSentenceOfRichTextValue() {
    if (!isRichTextCmsProperty())
        return "";

    String richText = (String) getValue();
    if (StringUtils.isBlank(richText))
        return null;

    //Get first 200 characters and strip html tags
    String firstSentence = StringUtils.substring(richText.replaceAll("<(.|\n)+?>", ""), 0, 200);

    if (firstSentence != null) {
        return firstSentence + "...";
    }/*from  w w  w .  ja v a 2 s  . c om*/

    return firstSentence;
}

From source file:org.bigmouth.nvwa.zookeeper.config.ZkPropertyPlaceholderConfigurer.java

private Properties convert(byte[] data) {
    Properties properties = new Properties();
    String string = null;/* w ww . ja  v a 2  s .  c  om*/
    try {
        string = new String(data, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        string = new String(data);
    }

    if (StringUtils.isNotBlank(string)) {
        String[] items = StringUtils.split(string, ITEM_SPLIT);
        for (String item : items) {
            if (StringUtils.isBlank(item)) {
                continue;
            }
            if (StringUtils.startsWith(item, "#")) {
                continue;
            }
            int index = StringUtils.indexOf(item, PROPERTY_SPLIT);
            String key = StringUtils.substring(item, 0, index);
            String value = StringUtils.substring(item, index + 1);
            properties.put(StringUtils.trim(key), StringUtils.trim(value));
        }
    }
    return properties;
}

From source file:org.braiden.fpm2.crypto.PBKDF2FpmKeyGenerator.java

@Override
public byte[] generateKey(String secret, String salt) throws GeneralSecurityException {
    byte[] saltBytes = StringUtils.substring(salt, 0, keyGenerator.getKeyLengthBytes() / 2).getBytes();
    return keyGenerator.generateKey(secret, saltBytes);
}

From source file:org.carewebframework.ui.zk.ZKUtil.java

/**
 * Returns a component of a type suitable for displaying the specified text. For text that is a
 * URL, returns an anchor. For text that begins with &lt;html&gt;, returns an HTML component.
 * All other text returns a label./* w w w  .  ja v  a2  s. co  m*/
 * 
 * @param text Text to be displayed.
 * @return Component of the appropriate type.
 */
public static XulElement getTextComponent(String text) {
    String frag = text == null ? "" : StringUtils.substring(text, 0, 20).toLowerCase();

    if (frag.contains("<html>")) {
        return new Html(text);
    }

    if (frag.matches("^https?:\\/\\/.+$")) {
        A anchor = new A(text);
        anchor.setHref(text);
        anchor.setTarget("_blank");
        return anchor;
    }

    return new Label(text);
}

From source file:org.carewebframework.vista.mbroker.BrokerSession.java

public void fireRemoteEvent(String eventName, Serializable eventData, String[] recipients) {
    RPCParameters params = new RPCParameters();
    params.get(0).setValue(eventName);/*from  w  w w  .  j a v a2  s .  c o m*/

    RPCParameter param = params.get(1);
    String data = eventData == null ? ""
            : eventData instanceof String ? eventData.toString()
                    : Constants.JSON_PREFIX + JSONUtil.serialize(eventData);
    int index = 0;

    for (int i = 0; i < data.length(); i += 255) {
        param.put(Integer.toString(++index), StringUtils.substring(data, i, i + 255));
    }

    param = params.get(2);

    for (String recip : recipients) {
        if (!recip.isEmpty()) {
            if (processRecipient(param, "#", "UID", recip) || processRecipient(param, "", "DUZ", recip)) {
            }
        }
    }

    callRPC("RGNETBEV BCAST", params);
}