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

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

Introduction

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

Prototype

public static String substringAfter(String str, String separator) 

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:net.sourceforge.fenixedu.presentationTier.Action.academicAdministration.executionCourseManagement.EditExecutionCourseDispatchAction.java

protected String separateLabel(ActionForm form, HttpServletRequest request, String property, String id,
        String name) {//from  ww w  . j  a v a 2  s  . c o m

    DynaActionForm executionCourseForm = (DynaActionForm) form;

    // the value returned to action is a string name~externalId
    String object = (String) executionCourseForm.get(property);
    if (object == null || object.length() <= 0) {
        object = (String) request.getAttribute(property);
        if (object == null) {
            object = request.getParameter(property);
        }
    }

    String objectId = null;
    String objectName = null;
    if (object != null && object.length() > 0 && object.indexOf("~") > 0) {
        executionCourseForm.set(property, object);
        request.setAttribute(property, object);

        objectId = StringUtils.substringAfter(object, "~");
        objectName = object.substring(0, object.indexOf("~"));

        request.setAttribute(name, objectName);
        request.setAttribute(id, objectId);
    }

    return objectId;
}

From source file:com.amalto.core.storage.StorageWrapper.java

protected String[] getAllDocumentsUniqueID(String clusterName, boolean includeClusterAndTypeName)
        throws XmlServerException {
    String pureClusterName = getPureClusterName(clusterName);
    Storage storage = getStorage(pureClusterName);
    MetadataRepository repository = storage.getMetadataRepository();
    Collection<ComplexTypeMetadata> typeToQuery;
    if (clusterName.contains("/")) { //$NON-NLS-1$
        String typeName = StringUtils.substringAfter(clusterName, "/"); //$NON-NLS-1$
        ComplexTypeMetadata complexType = repository.getComplexType(typeName);
        if (complexType == null) {
            throw new IllegalArgumentException(
                    "Type '" + typeName + "' does not exist in container '" + pureClusterName + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }//from  w  ww. j a v  a2s  .  c  om
        typeToQuery = Collections.singletonList(complexType);
    } else {
        typeToQuery = getClusterTypes(clusterName);
    }
    try {
        List<String> uniqueIDs = new LinkedList<String>();
        storage.begin();
        for (ComplexTypeMetadata currentType : typeToQuery) {
            UserQueryBuilder qb = from(currentType).selectId(currentType);
            StorageResults results = storage.fetch(qb.getSelect());
            try {
                for (DataRecord result : results) {
                    uniqueIDs.add(getUniqueID(pureClusterName, currentType, result, includeClusterAndTypeName));
                }
            } finally {
                results.close();
            }
        }
        storage.commit();
        return uniqueIDs.toArray(new String[uniqueIDs.size()]);
    } catch (Exception e) {
        storage.rollback();
        throw new XmlServerException(e);
    }
}

From source file:com.hangum.tadpole.rdb.core.viewers.object.sub.rdb.table.index.TadpoleIndexesComposite.java

/**
 * index    .//from   w w  w  .  j av a  2 s.c  om
 * @param strObjectName 
 */
public void refreshIndexes(final UserDBDAO userDB, boolean boolRefresh, String strObjectName) {
    if (!boolRefresh)
        if (listIndexes != null)
            return;

    this.userDB = userDB;
    try {
        SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
        HashMap<String, String> map = new HashMap<String, String>();
        if (userDB.getDBDefine() == DBDefine.ALTIBASE_DEFAULT) {
            map.put("user_name", StringUtils.substringBefore(tableDao.getName(), ".")); //$NON-NLS-1$
            map.put("table_name", StringUtils.substringAfter(tableDao.getName(), ".")); //$NON-NLS-1$
        } else {
            map.put("table_schema", userDB.getDb());
            map.put("table_name", tableDao.getName());
        }
        listIndexes = sqlClient.queryForList("indexList", map); //$NON-NLS-1$

        indexTableViewer.setInput(listIndexes);
        indexTableViewer.refresh();

        TableUtil.packTable(indexTableViewer.getTable());

        // select tabitem
        getTabFolderObject().setSelection(tbtmIndex);

        selectDataOfTable(strObjectName);
    } catch (Exception e) {
        logger.error("index refresh", e); //$NON-NLS-1$
        Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
        ExceptionDetailsErrorDialog.openError(getSite().getShell(), Messages.get().Error,
                Messages.get().ExplorerViewer_1, errStatus); //$NON-NLS-1$
    }
}

From source file:cn.orignzmn.shopkepper.common.utils.excel.ImportExcel.java

/**
 * ??/*  w ww . j ava2  s . co  m*/
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, Map<String, Object> inportInfo, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    ExcelSheet esarr = cls.getAnnotation(ExcelSheet.class);
    String annTitle = "";
    if (esarr == null)
        return Lists.newArrayList();
    annTitle = esarr.value();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    //???
    if (!"".equals(annTitle)) {
        String title = StringUtils.trim(this.getCellValue(this.getRow(0), 0).toString());
        if (!annTitle.equals(title)) {
            inportInfo.put("success", false);
            inportInfo.put("message", "??");
            return Lists.newArrayList();
        }
    }
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);

        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // If is dict type, get dict value
                //               if (StringUtils.isNotBlank(ef.dictType())){
                //                  val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                //                  //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                //               }
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        String s = String.valueOf(val.toString());
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = String.valueOf(val.toString());
                        }
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.composite.MSSQLLoginComposite.java

@Override
public boolean makeUserDBDao(boolean isTest) {
    if (!isValidateInput(isTest))
        return false;

    String dbUrl = "";
    String strHost = StringUtils.trimToEmpty(textHost.getText());
    String strPort = StringUtils.trimToEmpty(textPort.getText());
    String strDB = StringUtils.trimToEmpty(textDatabase.getText());

    if (StringUtils.contains(strHost, "\\")) {

        String strIp = StringUtils.substringBefore(strHost, "\\");
        String strInstance = StringUtils.substringAfter(strHost, "\\");

        dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strIp, strPort, strDB) + ";instance="
                + strInstance;/*from w ww.  ja  v a 2  s  .  c  om*/
    } else if (StringUtils.contains(strHost, "/")) {

        String strIp = StringUtils.substringBefore(strHost, "/");
        String strInstance = StringUtils.substringAfter(strHost, "/");

        dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strIp, strPort, strDB) + ";instance="
                + strInstance;

    } else {
        dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strHost, strPort, strDB);
    }
    if (!"".equals(textJDBCOptions.getText())) {
        if (StringUtils.endsWith(dbUrl, ";")) {
            dbUrl += textJDBCOptions.getText();
        } else {
            dbUrl += ";" + textJDBCOptions.getText();
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("[db url]" + dbUrl);

    userDB = new UserDBDAO();
    userDB.setDbms_type(getSelectDB().getDBToString());
    userDB.setUrl(dbUrl);
    userDB.setUrl_user_parameter(textJDBCOptions.getText());
    userDB.setDb(StringUtils.trimToEmpty(textDatabase.getText()));
    userDB.setGroup_name(StringUtils.trimToEmpty(preDBInfo.getComboGroup().getText()));
    userDB.setDisplay_name(StringUtils.trimToEmpty(preDBInfo.getTextDisplayName().getText()));

    String dbOpType = PublicTadpoleDefine.DBOperationType
            .getNameToType(preDBInfo.getComboOperationType().getText()).name();
    userDB.setOperation_type(dbOpType);
    if (dbOpType.equals(PublicTadpoleDefine.DBOperationType.PRODUCTION.name())
            || dbOpType.equals(PublicTadpoleDefine.DBOperationType.BACKUP.name())) {
        userDB.setIs_lock(PublicTadpoleDefine.YES_NO.YES.name());
    }

    userDB.setHost(StringUtils.trimToEmpty(textHost.getText()));
    userDB.setPort(StringUtils.trimToEmpty(textPort.getText()));
    userDB.setUsers(StringUtils.trimToEmpty(textUser.getText()));
    userDB.setPasswd(StringUtils.trimToEmpty(textPassword.getText()));

    // ? ?? ? .
    userDB.setRole_id(PublicTadpoleDefine.USER_ROLE_TYPE.ADMIN.toString());

    // others connection  .
    setOtherConnectionInfo();

    return true;
}

From source file:com.sfs.whichdoctor.dao.onlineapplication.BasicTrainingOnlineApplicationHandler.java

/**
 * Load person details from the XML application.
 *
 * @param root the root of the XML application
 * @return the person bean/*from www  . j  a  va2s  . co  m*/
 */
private PersonBean loadPersonDetails(final Element root) {
    PersonBean person = new PersonBean();

    Element pd = root.getChild("personaldetails");
    try {
        String name = pd.getChildText("firstname").trim();
        person.setFirstName(name);
        if (StringUtils.contains(name, " ")) {
            // Split the first and middle names
            person.setFirstName(StringUtils.substringBefore(name, " "));
            person.setMiddleName(StringUtils.substringAfter(name, " "));
        }
    } catch (Exception e) {
        dataLogger.error("Error parsing firstname: " + e.getMessage());
    }
    try {
        person.setPreferredName(pd.getChildText("prefname").trim());
    } catch (Exception e) {
        dataLogger.error("Error parsing prefname: " + e.getMessage());
    }
    try {
        person.setLastName(pd.getChildText("lastname").trim());
    } catch (Exception e) {
        dataLogger.error("Error parsing lastname: " + e.getMessage());
    }
    try {
        String birthDate = pd.getChildText("dob").trim();
        person.setBirthDate(parseDate(birthDate));
    } catch (Exception e) {
        dataLogger.error("Error parsing dob: " + e.getMessage());
    }
    try {
        String gender = pd.getChildText("gender").trim();
        person.setGender(WordUtils.capitalizeFully(gender));
    } catch (Exception e) {
        dataLogger.error("Error parsing lastname: " + e.getMessage());
    }
    person.setTitle("Dr");

    return person;
}

From source file:info.magnolia.cms.gui.dialog.DialogFckEdit.java

/**
 * @param value//from   w  w w .ja  va 2s . c  o  m
 * @return
 */
private String convertToView(String value) {
    String tmp = value;
    if (tmp != null) {
        tmp = tmp.replaceAll("\r\n", "<br />"); //$NON-NLS-1$ //$NON-NLS-2$
        tmp = tmp.replaceAll("\n", "<br />"); //$NON-NLS-1$ //$NON-NLS-2$

        value = LinkUtil.convertUUIDsToAbsoluteLinks(value);

        Pattern imagePattern = Pattern.compile("(<(a|img)[^>]+(src|href)[ ]*=[ ]*\")([^\"]*)(\"[^>]*>)"); //$NON-NLS-1$

        Matcher matcher = imagePattern.matcher(value);
        StringBuffer res = new StringBuffer();
        while (matcher.find()) {
            String src = matcher.group(4);

            // process only internal and relative links
            if (!Pattern.matches("^\\w*://.*", src) && !src.startsWith("/")) {
                String link = this.getRequest().getContextPath() + this.getTopParent().getConfigValue("path")
                        + "/" + StringUtils.substringAfter(src, "/");

                matcher.appendReplacement(res, "$1" + link + "$5"); //$NON-NLS-1$
            }
        }
        matcher.appendTail(res);
        return res.toString();
    }

    return StringUtils.EMPTY;
}

From source file:com.sfs.whichdoctor.dao.OnlineApplicationDAOImpl.java

/**
 * Gets the next step for the application.
 *
 * @param onlineApplication the online application
 * @return the next step/* w w w.  j a  v  a2s .  c om*/
 */
public final String[] getNextStep(final OnlineApplicationBean onlineApplication) {

    String step = "";
    String recordNumber = "";

    Collection<ObjectTypeBean> objectTypes = new ArrayList<ObjectTypeBean>();
    Map<Integer, String> statuses = new TreeMap<Integer, String>();

    try {
        objectTypes = this.getObjectTypeDAO().load("Application Status");
    } catch (SFSDaoException sfe) {
        dataLogger.error("Error loading list of application statuses: " + sfe.getMessage());
    }

    String type = onlineApplication.getType();
    String currentStatus = onlineApplication.getStatus();
    String currentRecordId = onlineApplication.getRecordNumber();

    if (objectTypes != null) {
        for (ObjectTypeBean objectType : objectTypes) {
            if (StringUtils.equalsIgnoreCase(type, objectType.getClassName())) {
                // This is of the type we are interested in
                String recordId = "";
                if (StringUtils.isNotBlank(objectType.getAbbreviation())) {
                    recordId = objectType.getAbbreviation().trim();
                }
                int orderId = (int) objectType.getValue();

                String key = objectType.getName() + "_" + recordId;
                statuses.put(orderId, key);

                if (dataLogger.isDebugEnabled()) {
                    dataLogger.debug("Status id: " + orderId);
                    dataLogger.debug("Status key: " + key);
                }
            }
        }
    }

    Document xml = null;
    try {
        xml = parseXmlApplication(onlineApplication.getApplicationXml());
    } catch (WhichDoctorDaoException wde) {
        dataLogger.error("Error parsing application XML: " + wde.getMessage());
    }

    boolean setNextValue = false;

    for (Integer orderId : statuses.keySet()) {
        String value = statuses.get(orderId);

        String nextStep = StringUtils.substringBefore(value, "_");
        String recordId = StringUtils.substringAfter(value, "_");

        if (dataLogger.isDebugEnabled()) {
            dataLogger.debug("Status id: " + orderId);
            dataLogger.debug("Status raw value: " + value);
            dataLogger.debug("Next status step: " + nextStep);
            dataLogger.debug("Record id: '" + recordId + "'");
            dataLogger.debug("Current record id: '" + currentRecordId + "'");
        }

        // If the currentStatus == value then the next value is the step
        if (StringUtils.equalsIgnoreCase(currentStatus, nextStep)
                && StringUtils.equalsIgnoreCase(currentRecordId, recordId)) {
            setNextValue = true;
            dataLogger.debug(nextStep + " is the current status value");
        } else {
            dataLogger.debug("Validating: '" + nextStep + "' - '" + recordId + "'");

            // If nextValue is set the next step to the value
            if (setNextValue && validateNextStep(xml, nextStep, onlineApplication.getType(), recordId)) {
                step = nextStep;
                recordNumber = recordId;

                // Reset to false
                setNextValue = false;
            }
        }
        if (dataLogger.isDebugEnabled()) {
            dataLogger.debug("Loop next step value: " + step);
            dataLogger.debug("Loop record id value: " + recordNumber);
        }
    }
    String[] statusDetails = { step, recordNumber };

    return statusDetails;
}

From source file:it.openutils.mgnlaws.magnolia.datastore.S3DataStore.java

/**
 * {@inheritDoc}/*  ww w  .j a v  a  2  s .com*/
 */
public void init(String homeDir) throws RepositoryException {
    // init S3 client
    amazonS3 = new AmazonS3Client(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
    // set endpoint
    if (StringUtils.isNotBlank(endpoint)) {
        amazonS3.setEndpoint(endpoint);
    }
    // init transfer manager
    transferManager = new TransferManager(amazonS3);

    // initialize tmp directory
    if (StringUtils.isNotBlank(tmpPath)) {
        tmpDirectory = new File(tmpPath);
        if (!tmpDirectory.exists()) {
            tmpDirectory.mkdirs();
        }
    }
    if (tmpDirectory == null || !tmpDirectory.isDirectory()) {
        tmpDirectory = new File(System.getProperty("java.io.tmpdir"));
    }

    if (useCache) {
        // initialize cache directory
        if (StringUtils.isNotBlank(cacheDirectoryPath)) {
            cacheDirectory = new File(cacheDirectoryPath);
            if (!cacheDirectory.exists()) {
                cacheDirectory.mkdirs();
            }
        }
        if (cacheDirectory == null || !cacheDirectory.isDirectory()) {
            cacheDirectory = new File(System.getProperty("java.io.tmpdir"), cacheName);
            if (!cacheDirectory.exists()) {
                cacheDirectory.mkdirs();
            }
        }

        // create cache manager
        CacheManager cacheManager;
        if (StringUtils.startsWith(cacheConfigFile, "classpath:")) {
            URL configurationFileURL = getClass()
                    .getResource(StringUtils.substringAfter(cacheConfigFile, "classpath:"));
            cacheManager = CacheManager.newInstance(configurationFileURL);
        } else {
            cacheManager = CacheManager.newInstance(cacheConfigFile);
        }
        // get cache
        cache = cacheManager.getCache(cacheName);
        // register cache listener
        cache.getCacheEventNotificationService().registerListener(new S3CacheListener(cacheDirectory));
    }
}

From source file:com.steeleforge.aem.ironsites.wcm.WCMUtil.java

/**
 * For non HTTPS fully qualified URLs, ensure HTTPS
 * /*from ww w .  ja  v a  2s . c o  m*/
 * @param fullyQualifiedURL
 * @return
 */
public static String getSecureURL(String fullyQualifiedURL) {
    if (!StringUtils.startsWith(fullyQualifiedURL, WCMConstants.HTTPS)) {
        return WCMConstants.HTTPS + WCMConstants.DELIMITER_PORT
                + StringUtils.substringAfter(fullyQualifiedURL, WCMConstants.PROTOCOL_RELATIVE);
    }
    return fullyQualifiedURL;
}