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

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

Introduction

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

Prototype

public static boolean endsWith(final CharSequence str, final CharSequence suffix) 

Source Link

Document

Check if a CharSequence ends with a specified suffix.

null s are handled without exceptions.

Usage

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

protected LookupResult lookupNoCache(HttpServletRequest req, String reqPath) {
    String subject = null, subjectPath = null, jsPath = null, path = null, targetPath = null;
    boolean isVirtualUrl = false, jsPathFound = false;
    URL targetUrl = null;//from   www. j a  v a  2  s  . c o  m

    try {
        WebTopApp wta = WebTopApp.get(req);

        // Builds a convenient URL for the servlet relative URL
        try {
            //String reqPath = req.getPathInfo();
            //logger.trace("Requested path [{}]", reqPath);

            Matcher matcher = PATTERN_VIRTUAL_URL.matcher(reqPath);
            if (matcher.matches()) {
                // Matches URLs like: /{service.id}/{service.version}/{remaining.url.part}
                // Eg. /com.sonicle.webtop.core/5.1.1/laf/default/service.css
                //   {service.id} -> com.sonicle.webtop.core
                //   {service.version} -> 5.1.1
                //   {remaining.url.part} -> laf/default/service.css
                isVirtualUrl = true;
                subject = matcher.group(1);
                path = matcher.group(3);

                if (!wta.getServiceManager().hasService(subject)) {
                    return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
                }
                targetUrl = new URL("http://fake/client/" + subject + "/" + path);

            } else {
                isVirtualUrl = false;
                String[] urlParts = splitPath(reqPath);
                subject = urlParts[0];
                jsPath = wta.getServiceManager().getServiceJsPath(subject);
                jsPathFound = (jsPath != null);
                subjectPath = (jsPathFound) ? jsPath : urlParts[0];
                path = urlParts[1];

                targetUrl = new URL("http://fake/" + subjectPath + "/" + path);
            }
            targetPath = targetUrl.getPath();

            //logger.trace("Translated path [{}]", translPath);
            if (isForbidden(targetPath))
                return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");

        } catch (MalformedURLException ex1) {
            return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
        }

        if (!isVirtualUrl && path.startsWith("images")) {
            // Addresses domain public images
            // URLs like "/{domainPublicName}/images/{relativePathToFile}"
            // Eg.   "/1bbc048f/images/login.png"
            //      "/1bbc048f/images/sub/login.png"
            WebTopManager wtMgr = wta.getWebTopManager();

            String domainId = wtMgr.publicNameToDomainId(subject);
            if (StringUtils.isBlank(domainId)) {
                // We must support old-style URL using {domainInternetName}
                // instead of {domainPublicName}
                // Eg.   "/sonicle.com/images/login.png"
                domainId = wtMgr.internetNameToDomain(subject);
            }
            if (StringUtils.isBlank(domainId)) {
                return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
            }

            return lookupDomainImage(req, targetUrl, domainId);

        } else if (isVirtualUrl && subject.equals(CoreManifest.ID)
                && path.equals("resources/images/login.png")) {
            // Addresses login image
            // URLs like "/{serviceId}/{serviceVersion}/resources/images/login.png"
            // Eg.   "/com.sonicle.webtop.core/5.0.0/images/login.png"
            return lookupLoginImage(req, targetUrl);

        } else if (isVirtualUrl && subject.equals(CoreManifest.ID) && path.equals("resources/license.html")) {
            // Addresses licence page
            // URLs like "/{serviceId}/{serviceVersion}/resources/license.html"
            return lookupLicense(req, targetUrl);

        } else if (!isVirtualUrl && path.startsWith("whatsnew/")) {
            return lookupWhatsnew(req, targetUrl, path, subject);
        } else {
            if (StringUtils.endsWith(targetPath, ".js")) {
                String sessionId = ServletHelper.getSessionID(req);
                if (StringUtils.startsWith(path, "resources/vendor")
                        || StringUtils.startsWith(path, "resources/libs")) {
                    // If targets lib folder, simply return requested file without handling debug versions
                    return lookupJs(req, targetUrl, false);

                } else if (StringUtils.startsWith(path, "boot/")) {
                    return lookupJs(req, targetUrl, isJsDebug());

                } else if (StringUtils.startsWith(FilenameUtils.getBaseName(path), "Locale")) {
                    return lookupLocaleJs(req, targetUrl, subject);

                } else {
                    return lookupJs(req, targetUrl, isJsDebug());
                }

            } else if (StringUtils.startsWith(path, "laf")) {
                return lookupLAF(req, targetUrl, path, subject, subjectPath);

            } else {
                return lookupDefault(req, isVirtualUrl ? ClientCaching.YES : ClientCaching.AUTO, targetUrl);
            }
        }

    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:com.coul.common.excel.ImportExcel.java

/**
 * ??//from   ww w  .  j  av  a  2 s  .  com
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    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();
    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.topsem.common.io.excel.ImportExcel.java

/**
 * ??//from  ww  w  .  j av  a  2s. c  o m
 *
 * @param cls    
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field
    Field[] fs = cls.getDeclaredFields();
    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();
    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.green.common.utils.excel.ImportExcel.java

/**
 * ??// ww w .ja v  a2s  . c om
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    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();
    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.nridge.ds.solr.SolrSchemaXML.java

public void save(PrintWriter aPW, String aTagName, int anIndentAmount) throws IOException {
    DataField dataField;//from  w  w  w  .jav a  2s.c om

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<%s>%n", aTagName);
    saveComment(aPW, anIndentAmount);
    anIndentAmount++;

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<field name=\"text\" type=\"%s\" indexed=\"true\" stored=\"true\" multiValued=\"true\"/>%n",
            SOLR_TEXT_FIELD_TYPE_DEFAULT);

    DataBag dataBag = mDocument.getBag();
    int fieldCount = dataBag.count();
    for (int i = 0; i < fieldCount; i++) {
        dataField = dataBag.getByOffset(i);

        IOXML.indentLine(aPW, anIndentAmount);
        aPW.printf("<field name=\"%s\"", dataField.getName());
        if (dataField.isFeatureAssigned(Solr.FEATURE_SOLR_TYPE))
            aPW.printf(" type=\"%s\"", dataField.getFeature(Solr.FEATURE_SOLR_TYPE));
        else
            aPW.printf(" type=\"%s\"", mapFieldType(dataField));
        if (dataField.isFeatureAssigned(Solr.FEATURE_IS_INDEXED))
            aPW.printf(" indexed=\"%s\"", dataField.getFeature(Solr.FEATURE_IS_INDEXED));
        else
            aPW.printf(" indexed=\"true\"");
        if (dataField.isFeatureAssigned(Solr.FEATURE_IS_STORED))
            aPW.printf(" stored=\"%s\"", dataField.getFeature(Solr.FEATURE_IS_STORED));
        else
            aPW.printf(" stored=\"true\"");
        if (dataField.isFeatureTrue(Field.FEATURE_IS_REQUIRED))
            aPW.printf(" required=\"true\"");
        if (dataField.isMultiValue())
            aPW.printf(" multiValued=\"true\"");
        if (dataField.isFeatureTrue(Solr.FEATURE_IS_OMIT_NORMS))
            aPW.printf(" omitNorms=\"%s\"", dataField.getFeature(Solr.FEATURE_IS_OMIT_NORMS));
        if ((dataField.isFeatureTrue(Solr.FEATURE_IS_DEFAULT))
                && (StringUtils.isNotEmpty(dataField.getDefaultValue())))
            aPW.printf(" default=\"%s\"", dataField.getDefaultValue());
        aPW.printf("/>%n");
    }

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<field name=\"_version_\" type=\"long\" indexed=\"true\" stored=\"true\"/>%n");

    anIndentAmount--;
    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("</%s>%n", aTagName);

    dataField = dataBag.getPrimaryKeyField();
    if (dataField != null) {
        IOXML.indentLine(aPW, anIndentAmount);
        aPW.printf("<uniqueKey>%s</uniqueKey>%n", dataField.getName());
    }

    String fieldName;
    for (int i = 0; i < fieldCount; i++) {
        dataField = dataBag.getByOffset(i);

        fieldName = dataField.getName();
        if ((StringUtils.endsWith(fieldName, "_name")) || (StringUtils.endsWith(fieldName, "_title"))
                || (StringUtils.endsWith(fieldName, "_description"))
                || (StringUtils.endsWith(fieldName, "_content"))) {
            IOXML.indentLine(aPW, anIndentAmount);
            aPW.printf("<copyField source=\"%s\" dest=\"text\"/>%n", fieldName);
        }
    }
}

From source file:com.norconex.commons.lang.url.URLNormalizer.java

/**
 * <p>Adds a trailing slash (/) to a URL ending with a directory.  A URL is 
 * considered to end with a directory if the last path segment,
 * before fragment (#) or query string (?), does not contain a dot,
 * typically representing an extension.</p>
 *   /*from   w ww .j  a v  a  2s  .c o  m*/
 * <p><b>Please Note:</b> URLs do not always denote a directory structure 
 * and many URLs can qualify to this method without truly representing a 
 * directory. Adding a trailing slash to these URLs could potentially break
 * its semantic equivalence.</p>
 * <code>http://www.example.com/alice &rarr; 
 *       http://www.example.com/alice/</code>
 * @return this instance
 */
public URLNormalizer addTrailingSlash() {
    String name = StringUtils.substringAfterLast(url, "/");
    if (!name.contains(".") && !StringUtils.endsWith(name, "/")) {
        url = url + "/";
    }
    return this;
}

From source file:com.fengduo.spark.commons.file.excel.ImportExcel.java

/**
 * ??/*from  ww w  .  j  a  v  a  2s .  c  o m*/
 * 
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field
    Field[] fs = cls.getDeclaredFields();
    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();
    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.ottogroup.bi.asap.repository.ComponentClassloader.java

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder//from   w ww  .j  a  v  a 2 s . c o  m
 * @param componentJarIdentifier file to search for in component JAR which identifies it as component JAR 
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder, final String componentJarIdentifier)
        throws IOException, RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(componentFolder))
        throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");

    File folder = new File(componentFolder);
    if (!folder.isDirectory())
        throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");

    File[] jarFiles = folder.listFiles();
    if (jarFiles == null || jarFiles.length < 1)
        throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
    //
    ///////////////////////////////////////////////////////////////////

    logger.info("Initializing component classloader [componentJarIdentifier=" + componentJarIdentifier
            + ", folder=" + componentFolder + "]");

    // step through jar files, ensure it is a file and iterate through its contents
    for (File jarFile : jarFiles) {
        if (jarFile.isFile()) {

            JarInputStream jarInputStream = null;
            try {
                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
                JarEntry jarEntry = null;
                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                    String jarEntryName = jarEntry.getName();
                    // if the current file references a class implementation, replace slashes by dots, strip 
                    // away the class suffix and add a reference to the classes-2-jar mapping 
                    if (StringUtils.endsWith(jarEntryName, ".class")) {
                        jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                        this.classesJarMapping.put(jarEntryName, jarFile.getAbsolutePath());
                    } else {
                        // if the current file references a resource, check if it is the identifier file which
                        // marks this jar to contain component implementation                     
                        if (StringUtils.equalsIgnoreCase(jarEntryName, componentJarIdentifier))
                            this.componentJarFiles.add(jarFile.getAbsolutePath());
                        // ...and add a mapping for resource to jar file as well                     
                        this.resourcesJarMapping.put(jarEntryName, jarFile.getAbsolutePath());
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                        + e.getMessage());
            } finally {
                try {
                    jarInputStream.close();
                } catch (Exception e) {
                    logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                            + e.getMessage());
                }
            }
        }
    }

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.componentJarFiles) {
        logger.info("Attempting to load pipeline components located in '" + cjf + "'");

        // open JAR file and iterate through it's contents
        JarInputStream jarInputStream = null;
        try {
            jarInputStream = new JarInputStream(new FileInputStream(cjf));
            JarEntry jarEntry = null;
            while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {

                // fetch name of current entry and ensure it is a class file
                String jarEntryName = jarEntry.getName();
                if (jarEntryName.endsWith(".class")) {
                    // replace slashes by dots and strip away '.class' suffix
                    jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                    Class<?> c = loadClass(jarEntryName);
                    AsapComponent pc = c.getAnnotation(AsapComponent.class);
                    if (pc != null) {
                        this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()),
                                new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(),
                                        pc.description()));
                        logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name()
                                + ", version=" + pc.version() + "]");
                        ;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Failed to read from JAR file '" + cjf + "'. Error: " + e.getMessage());
        } finally {
            try {
                jarInputStream.close();
            } catch (Exception e) {
                logger.error("Failed to close open JAR file '" + cjf + "'. Error: " + e.getMessage());
            }
        }
    }
}

From source file:com.funtl.framework.smoke.core.commons.excel.ImportExcel.java

/**
 * ??/* www .  ja  va2  s. co  m*/
 *
 * @param cls    
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field
    Field[] fs = cls.getDeclaredFields();
    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();
    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:Heuristics.TermLevelHeuristics.java

public boolean isImmediatelyFollowedByVerbPastTense(String status, String termOrig) {
    String temp = status.substring(status.indexOf(termOrig)).trim();
    boolean pastTense;
    String[] nextTerms = temp.split(" ");
    if (nextTerms.length > 1) {
        temp = nextTerms[1].trim();/* w w w.  j av a 2s.com*/
        pastTense = StringUtils.endsWith(temp, "ed");
        if (pastTense) {
            return true;
        }
        pastTense = StringUtils.endsWith(temp, "ought") & !StringUtils.startsWith(temp, "ought");
        if (pastTense) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}