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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:net.ymate.platform.webmvc.support.RequestMappingParser.java

/**
 * @param context /* w ww  .  ja v  a  2 s.  c  o m*/
 * @return ?????????WebContextPathVariable?
 */
public RequestMeta doParse(IRequestContext context) {
    RequestMeta _meta = null;
    Map<String, RequestMeta> _mappingMap = null;
    switch (context.getHttpMethod()) {
    case POST:
        _mappingMap = __MAPPING_META_FOR_POST;
        break;
    case DELETE:
        _mappingMap = __MAPPING_META_FOR_DELETE;
        break;
    case PUT:
        _mappingMap = __MAPPING_META_FOR_PUT;
        break;
    case OPTIONS:
        _mappingMap = __MAPPING_META_FOR_OPTIONS;
        break;
    case HEAD:
        _mappingMap = __MAPPING_META_FOR_HEAD;
        break;
    case TRACE:
        _mappingMap = __MAPPING_META_FOR_TRACE;
        break;
    default:
        _mappingMap = __MAPPING_META_FOR_GET;
    }
    _meta = _mappingMap.get(context.getRequestMapping());
    if (_meta == null) {
        String _requestMapping = this.__doFixMappingPart(context.getRequestMapping());
        // ??PairObject<Mapping[??], ??>
        Set<PairObject<String[], Integer>> _filteredMapping = new HashSet<PairObject<String[], Integer>>();
        for (String _key : _mappingMap.keySet()) {
            if (_key.contains("{")) {
                String _mappingKey = StringUtils.substringBefore(_key, "{");
                String _fixedMappingKey = this.__doFixMappingPart(_mappingKey);
                if (StringUtils.startsWithIgnoreCase(_requestMapping, _fixedMappingKey)) {
                    // ?????
                    String _paramKey = _key.substring(_key.indexOf('{'));
                    _filteredMapping.add(new PairObject<String[], Integer>(
                            new String[] { _key, _mappingKey, _fixedMappingKey, _paramKey },
                            StringUtils.split(_paramKey, "/").length));
                }
            }
        }
        // ?????
        PairObject<String[], Integer> _result = null;
        String _mappingParamPart = null;
        for (PairObject<String[], Integer> _item : _filteredMapping) {
            // ?????
            _mappingParamPart = StringUtils.substringAfter(_requestMapping, _item.getKey()[2]);
            // ???
            int _paramPartCount = StringUtils.split(_mappingParamPart, "/").length;
            // ?????
            if (_paramPartCount == _item.getValue()) {
                _result = _item;
                break;
            }
        }
        if (_result != null) {
            Map<String, String> _params = this.__doParserMappingParams(_mappingParamPart, _result.getKey()[3]);
            // ???WebContextPathVariable?
            for (Map.Entry<String, String> _entry : _params.entrySet()) {
                context.addAttribute(_entry.getKey(), _entry.getValue());
            }
            _meta = _mappingMap.get(_result.getKey()[0]);
        }
    }
    return _meta;
}

From source file:net.ymate.platform.webmvc.view.impl.BinaryView.java

/**
 * ?Range????/*from ww  w  . ja va 2s  . c  o m*/
 *
 * @param length ??
 * @return ?null
 */
private PairObject<Long, Long> __doParseRange(long length) {
    PairObject<Long, Long> _returnValue = null;
    // Range??
    String _rangeStr = WebContext.getRequest().getHeader("Range");
    if (_rangeStr != null && _rangeStr.startsWith("bytes=") && _rangeStr.length() >= 7) {
        _rangeStr = StringUtils.substringAfter(_rangeStr, "bytes=");
        String[] _ranges = StringUtils.split(_rangeStr, ",");
        // ?Range??...
        for (String _range : _ranges) {
            if (StringUtils.isBlank(_range)) {
                return null;
            }
            // bytes=-100
            if (_range.startsWith("-")) {
                long _end = Long.parseLong(_range);
                long _start = length + _end;
                if (_start < 0) {
                    return null;
                }
                _returnValue = new PairObject<Long, Long>(_start, length);
                break;
            }
            // bytes=1024-
            if (_range.endsWith("-")) {
                long _start = Long.parseLong(StringUtils.substringBefore(_range, "-"));
                if (_start < 0) {
                    return null;
                }
                _returnValue = new PairObject<Long, Long>(_start, length);
                break;
            }
            // bytes=10-1024
            if (_range.contains("-")) {
                String[] _tmp = _range.split("-");
                long _start = Long.parseLong(_tmp[0]);
                long _end = Long.parseLong(_tmp[1]);
                if (_start > _end) {
                    return null;
                }
                _returnValue = new PairObject<Long, Long>(_start, _end + 1);
            }
        }
    }
    return _returnValue;
}

From source file:nl.nn.adapterframework.extensions.svn.SvnUtils.java

public static String getLogReport(String urlString) throws DomBuilderException, XPathExpressionException,
        ConfigurationException, SenderException, TimeOutException {
    String head = getHeadHtml(urlString);
    String etag = XmlUtils.evaluateXPathNodeSetFirstElement(head, "headers/header[lower-case(@name)='etag']");
    if (etag != null) {
        if (StringUtils.countMatches(etag, "\"") >= 2) {
            String s = StringUtils.substringAfter(etag, "\"");
            String s2 = StringUtils.substringBefore(s, "\"");
            String s3 = StringUtils.substringBefore(s2, "/");
            String s4 = StringUtils.substringAfter(s2, "/");
            return getReportHtml(urlString, s3, s4);
        }/*w  w w . j  av  a2s .  c om*/
    }
    return null;
}

From source file:nl.openweb.hippo.umd.ui.ResourceServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String resourcePath = StringUtils.substringBefore(request.getPathInfo(), ";");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Processing request for resource {}.", resourcePath);
    }/*from  w w  w. j  a v  a 2 s  .  c  o  m*/

    URL resource = getResourceURL(resourcePath);

    if (resource == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resource not found: {}", resourcePath);
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");

    URLConnection conn = resource.openConnection();
    long lastModified = conn.getLastModified();

    if (ifModifiedSince >= lastModified) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resource: {} Not Modified.", resourcePath);
        }
        response.setStatus(304);
        return;
    }

    int contentLength = conn.getContentLength();

    prepareResponse(response, resource, lastModified, contentLength);

    OutputStream out = selectOutputStream(request, response);

    try {
        InputStream is = conn.getInputStream();
        try {
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = is.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } finally {
            is.close();
        }
    } finally {
        out.close();
    }

}

From source file:nl.ucan.navigate.NestedPath.java

private NestedPath() {
    this.propertyInstance = new PropertyInstance() {
        public Object indexed(Object bean, String property, int index, Object value) {
            log.info("created indexed property " + property + " at " + index + " of bean " + bean
                    + " and will be set to " + value);
            return value;
        }//from  w  w w  .j a v a2  s  .  com

        public Object simple(Object bean, String property, Object value) {
            log.info("created simple property " + property + " of bean " + bean + " and will be set to "
                    + value);
            return value;
        }
    };
    this.propertyValue = new PropertyValue() {
        public Object indexed(Object bean, String property, int index, Object value) {
            log.info("value of indexed property " + property + " at " + index + " of bean " + bean
                    + " will be set to " + value);
            return value;
        }

        public Object mapped(Object bean, String property, Object key, Object value) {
            log.info("value of mapped property " + property + " at " + key + " of bean " + bean
                    + " will be set to " + value);
            return value;
        }

        public Object simple(Object bean, String property, Object value) {
            log.info("value of simple property " + property + " of bean " + bean + " will be set to " + value);
            return value;
        }

        public Object valueOf(Class clasz, String property, String value) {
            log.info("value of valueOf " + property + " will be set to " + value);
            return value;
        }
    };
    this.indexPointer = new IndexPointer() {
        public int size(Object bean) {
            return CollectionUtils.size(bean);
        }

        public Object get(Object bean, int idx) {
            return CollectionUtils.get(bean, idx);
        }

        public int firstIndexOf(Object bean, String undeterminedIndex)
                throws IllegalAccessException, InvocationTargetException, NoSuchMethodException,
                InstantiationException, IntrospectionException {
            this.setUndeterminedIndex(undeterminedIndex);
            for (int idx = 0; idx < size(bean); idx++) {
                Object object = get(bean, idx);
                if (object != null) {
                    if (evaluate(object, this.getUndeterminedIndex()))
                        return idx;
                }
            }
            return -1;
        }

        public void setIndexAsProperty(Object bean, String undeterminedIndex)
                throws IllegalAccessException, InvocationTargetException, NoSuchMethodException,
                InstantiationException, IntrospectionException {
            this.setUndeterminedIndex(undeterminedIndex);
            Object value = propertyValue.simple(bean, this.getProperty(), this.getValue());
            pub.setProperty(bean, this.getProperty(), value);
        }

        private String undeterminedIndex;

        private void setUndeterminedIndex(String undeterminedIndex) {
            this.undeterminedIndex = undeterminedIndex;
        }

        private String getUndeterminedIndex() {
            return this.undeterminedIndex;
        }

        private boolean evaluate(Object bean, String undeterminedIndex)
                throws IllegalAccessException, InvocationTargetException, NoSuchMethodException,
                InstantiationException, IntrospectionException {
            this.setUndeterminedIndex(undeterminedIndex);
            String property = getProperty();
            String valueOfIndex = getValue();
            Object valueOfBean = pub.getProperty(bean, property);
            return ObjectUtils.equals(valueOfIndex, valueOfBean);
        }

        private String getProperty() {
            Map.Entry<String, String> entry = getNamedIndex(this.getUndeterminedIndex());
            return entry.getKey();
        }

        private String getValue() {
            Map.Entry<String, String> entry = getNamedIndex(this.getUndeterminedIndex());
            return entry.getValue();
        }

        private Map.Entry<String, String> getNamedIndex(String value) {
            final String SEP = "=";
            Map<String, String> keyValuePair = new HashMap<String, String>();
            if (StringUtils.indexOf(value, SEP) == -1)
                return null;
            keyValuePair.put(StringUtils.substringBefore(value, SEP), StringUtils.substringAfter(value, SEP));
            return keyValuePair.entrySet().iterator().next();
        }
    };
    this.pub = BeanUtilsBean.getInstance().getPropertyUtils();
    this.pub.setResolver(new ResolverImpl());
}

From source file:opennlp.tools.doc_classifier.DocClassifierTrainingSetMultilingualExtender.java

public void processDirectory(String fileName) throws IOException {
    List<String[]> report = new ArrayList<String[]>();
    report.add(new String[] { "filename", "category", "confirmed?", });

    addFiles(new File(fileName));
    //   FileUtils.deleteDirectory(new File(destinationDir));
    //   FileUtils.forceMkdir(new File(destinationDir));

    for (File f : queue) {
        String content = null;/*from   w  ww  .j ava 2  s  . com*/
        try {// should be wiki page
             //if (f.getName().toString().toLowerCase().indexOf(" wiki")<0 && 

            //   if (      f.getAbsolutePath().indexOf("wiki-new")<0)
            //      continue;
            // should not be a page already derived by a link
            if (f.getName().toString().toLowerCase().indexOf(".html_") > -1)
                continue;

            System.out.println("processing " + f.getName());
            content = FileUtils.readFileToString(f, "utf-8");
            int langIndex = 0;
            for (String[] begEnd : multilingualTokens) {
                String urlDirty = StringUtils.substringBetween(content, begEnd[0], begEnd[1]);
                String url = StringUtils.substringBefore(urlDirty, "\"");

                if (url != null) {
                    if (!url.startsWith("http:"))
                        url = "https:" + url;

                    String[] parts = url.split("/");
                    String multilingualName = parts[parts.length - 1];
                    String destFileName = f.getAbsolutePath().replace(sourceDir, destinationDir)
                            .replace(" - Wikipedia, the free encyclopedia.html", "-wiki") + "."
                            + langs[langIndex] + "." + "_" + multilingualName + ".html";
                    if (!new File(destFileName).exists()) {
                        saveDocFromTheWeb(url, destFileName);
                        System.out.println(f.getName() + " => " + destFileName);
                    }
                } else {
                    System.out.println("Unable to extract multilingual urls for'" + langs[langIndex]
                            + "' from file " + f.getCanonicalPath());
                }
                langIndex++;
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    queue.clear();
}

From source file:org.agric.oxm.utils.JpaUtils.java

/**
 * Gets a Path from Path using property path
 * //from w  ww.  j a  va 2  s .  c om
 * @param path
 *            the base path
 * @param propertyPath
 *            property path String like "customer.order.price"
 * @return a new Path for property
 */
public static Path<?> getPath(Path<?> path, String propertyPath) {
    if (StringUtils.isEmpty(propertyPath))
        return path;

    String name = StringUtils.substringBefore(propertyPath, PropertyUtils.PROPERTY_SEPARATOR);
    Path<?> p = path.get(name);

    return getPath(p, StringUtils.substringAfter(propertyPath, PropertyUtils.PROPERTY_SEPARATOR));

}

From source file:org.apache.archiva.metadata.repository.cassandra.CassandraMetadataRepository.java

@Override
public Collection<String> getRootNamespaces(final String repoId) throws MetadataResolutionException {

    QueryResult<OrderedRows<String, String, String>> result = HFactory //
            .createRangeSlicesQuery(keyspace, ss, ss, ss) //
            .setColumnFamily(cassandraArchivaManager.getNamespaceFamilyName()) //
            .setColumnNames(NAME.toString()) //
            .addEqualsExpression(REPOSITORY_NAME.toString(), repoId) //
            .execute();//from w  ww  . j a  v a 2s.c o m

    Set<String> namespaces = new HashSet<String>(result.get().getCount());

    for (Row<String, String, String> row : result.get()) {
        namespaces.add(StringUtils.substringBefore(getStringValue(row.getColumnSlice(), NAME.toString()), "."));
    }

    return namespaces;
}

From source file:org.apache.archiva.metadata.repository.cassandra.CassandraMetadataRepository.java

@Override
public Collection<String> getNamespaces(final String repoId, final String namespaceId)
        throws MetadataResolutionException {

    QueryResult<OrderedRows<String, String, String>> result = HFactory //
            .createRangeSlicesQuery(keyspace, ss, ss, ss) //
            .setColumnFamily(cassandraArchivaManager.getNamespaceFamilyName()) //
            .setColumnNames(NAME.toString()) //
            .addEqualsExpression(REPOSITORY_NAME.toString(), repoId) //
            .execute();//from w w w . j a va  2s  .c o  m

    List<String> namespaces = new ArrayList<>(result.get().getCount());

    for (Row<String, String, String> row : result.get()) {
        String currentNamespace = getStringValue(row.getColumnSlice(), NAME.toString());
        if (StringUtils.startsWith(currentNamespace, namespaceId) //
                && (StringUtils.length(currentNamespace) > StringUtils.length(namespaceId))) {
            // store after namespaceId '.' but before next '.'
            // call org namespace org.apache.maven.shared -> stored apache

            String calledNamespace = StringUtils.endsWith(namespaceId, ".") ? namespaceId : namespaceId + ".";
            String storedNamespace = StringUtils.substringAfter(currentNamespace, calledNamespace);

            storedNamespace = StringUtils.substringBefore(storedNamespace, ".");

            namespaces.add(storedNamespace);
        }
    }

    return namespaces;

}

From source file:org.apache.archiva.metadata.repository.storage.maven2.RepositoryModelResolver.java

private String getProtocol(String url) {
    String protocol = StringUtils.substringBefore(url, ":");

    return protocol;
}