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:com.ultrapower.eoms.common.plugin.ecside.core.RetrievalUtils.java

static Collection retrieveNestedCollection(WebContext context, String collection, String scope)
        throws Exception {
    String split[] = StringUtils.split(collection, ".");
    Object obj = RetrievalUtils.retrieve(context, split[0], scope);
    String collectionToFind = StringUtils.substringAfter(collection, ".");
        /*from  ww w. ja  v a  2 s .c  o m*/
    Object value=null;
    try {
     // if (ExtremeUtils.isBeanPropertyReadable(bean, property)) {
     value = PropertyUtils.getProperty(obj, collectionToFind);
     obj = value;
     // }
  } catch (Exception e) {
     if (logger.isDebugEnabled()) {
        logger.debug("Could not find the property [" + collectionToFind
              + "]. Either the bean or property is null");
     }
  }
              
    if (!(obj instanceof Collection)) {
        if (logger.isDebugEnabled()) {
            logger.debug("The object is not of type Collection.");
        }

        return Collections.EMPTY_LIST;
    }

    return (Collection) obj;
}

From source file:com.googlecode.jtiger.modules.ecside.core.RetrievalUtils.java

static Collection retrieveNestedCollection(WebContext context, String collection, String scope)
        throws Exception {
    String split[] = StringUtils.split(collection, ".");
    Object obj = RetrievalUtils.retrieve(context, split[0], scope);
    String collectionToFind = StringUtils.substringAfter(collection, ".");

    Object value = null;/*from w ww . j a  va 2 s  . c  o m*/
    try {
        // if (ExtremeUtils.isBeanPropertyReadable(bean, property)) {
        value = PropertyUtils.getProperty(obj, collectionToFind);
        obj = value;
        // }
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find the property [" + collectionToFind
                    + "]. Either the bean or property is null");
        }
    }

    if (!(obj instanceof Collection)) {
        if (logger.isDebugEnabled()) {
            logger.debug("The object is not of type Collection.");
        }

        return Collections.EMPTY_LIST;
    }

    return (Collection) obj;
}

From source file:eionet.eunis.servlets.DownloadServlet.java

/**
 * Process the actual request.//  w w  w .  jav a2  s  .c  o  m
 *
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not (HEAD).
 * @throws IOException If something fails at I/O level.
 * @throws ServletException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException, ServletException {

    String requestURI = request.getRequestURI();
    String contextPath = request.getContextPath();
    String pathInfo = request.getPathInfo();
    String servletPath = request.getServletPath();

    // Create the abstract file reference to the requested file.
    File file = null;
    String fileRelativePath = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath());
    fileRelativePath = StringUtils.replace(fileRelativePath, "%20", " ");
    if (StringUtils.isNotEmpty(fileRelativePath) && StringUtils.isNotEmpty(appHome)) {
        file = new File(appHome, fileRelativePath);
    }

    // If file was not found, send 404.
    if (file == null || !file.exists() || file.isDirectory()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;

    // Validate request headers for caching ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding is supported by
    // the browser and expand content type with the one and right character encoding.
    // Else, expect for images, determine content disposition. If content type is supported by
    // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    } else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (content) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of GZIP.
                    // So only add it if there is no means of GZIP, else browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Cast back to ServletOutputStream to get the easy println methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:cool.pandora.modeller.ui.handlers.common.NodeMap.java

/**
 * getAreaIdMap./* w ww.j a v  a 2  s  .  com*/
 *
 * @param hocr       hOCRData
 * @param pageIdList List
 * @return Map
 */
public static Map<String, List<String>> getAreaIdMap(final hOCRData hocr, final List<String> pageIdList) {
    final Map<String, List<String>> nodemap = new HashMap<>();
    List<String> areaIdList;
    for (String pageId : pageIdList) {
        areaIdList = getAreaIdListforPage(hocr, pageId);
        for (int i = 0; i < areaIdList.size(); i++) {
            final String areaId = StringUtils.substringAfter(areaIdList.get(i), "_");
            areaIdList.set(i, areaId);
        }
        pageId = StringUtils.substringAfter(pageId, "_");
        nodemap.put(pageId, areaIdList);
    }
    return nodemap;
}

From source file:de.fhg.iais.cortex.services.binding.IdHandler.java

@Override
public String doBinding(AipObject aipObject, IIngestContext context) {

    final String providerId = aipObject.getObjectFromFirstAvailablePathOrNull(String.class,
            OldSchemaPaths.PATH_PROVIDER_ID.path(), NewSchemaPaths.PATH_PROVIDER_ID.path());
    final String providerItemId = aipObject.getObjectFromFirstAvailablePathOrNull(String.class,
            OldSchemaPaths.PATH_PROVIDER_ITEM_ID.path(), NewSchemaPaths.PATH_PROVIDER_ITEM_ID.path());

    String itemId = IdGenerator.item(providerId, providerItemId).generate();

    if (Strings.isNullOrEmpty(itemId)) {
        context.reportAndThrowDataError(RevisionReport.INGEST_PART, ReportSections.ID_HANDLER,
                "Invalid XML Input, " + "" + "Item ID is missing.", null);
    }//from   w  ww.  j  a va  2s  .c om

    context.setItemId(itemId);

    if (context.getAipObject().isNewFormat()) {
        aipObject.setObjectForPath(NewSchemaPaths.PATH_CORTEX_ITEM_ID.path(), itemId);
    } else {
        aipObject.setObjectForPath(OldSchemaPaths.PATH_CORTEX_ITEM_ID.path(), itemId);
    }

    final Map<String, String> idMap = new HashMap<String, String>();

    Element model = aipObject.getModelElement();
    Parser parser = Parser.createParser(model);
    Graph graph = parser.load(model);

    graph.dfs(new Method1<Vertex>() {
        @Override
        public void call(Vertex vertex) {
            String localSubjectId = vertex.getId();
            if (vertex.outgoing().isEmpty() && !localSubjectId.startsWith(IdGenerator.GLOBAL_PREFIX)) {
                return;
            }
            if (localSubjectId.startsWith(IdGenerator.GLOBAL_PREFIX)) {
                String globalId = IdGenerator.global(providerId, localSubjectId).generate();
                idMap.put(localSubjectId, GlobalConstants.CORTEX_ITEM_IDENTIFIER_PREFIX + globalId);
            } else if (localSubjectId.startsWith(IdGenerator.UID_PREFIX)) {
                String uniqueId = StringUtils.substringAfter(localSubjectId, IdGenerator.UID_PREFIX);
                String ddbId = IdGenerator.item(providerId, uniqueId).generate();
                idMap.put(localSubjectId, IdGenerator.UID_PREFIX + ddbId);
            } else if (!localSubjectId.startsWith(GLOBAL_HTTP_PREFIX)
                    && !localSubjectId.startsWith(GLOBAL_HTTPS_PREFIX)) {
                String localId = IdGenerator.local(providerId, vertex).generate();
                idMap.put(localSubjectId, localId);
            }
        }
    });

    Vertex primary = graph.getPrimaryItemVertex();
    String localIdThis = primary.getId();
    idMap.put(localIdThis, GlobalConstants.CORTEX_ITEM_IDENTIFIER_PREFIX + itemId);

    JDomVisitor idRewriteVisitor = new JDomVisitor(new IdRewriteAction(idMap, aipObject.isNewFormat()));
    idRewriteVisitor.visit(model);

    if (model != null) {
        context.getAipObject().setModelElement(model);
    }

    return itemId;
}

From source file:com.opengamma.component.ComponentConfigLoader.java

private void parseReplacement(String line, ConcurrentMap<String, String> properties) {
    String key = StringUtils.substringBefore(line, "=").trim();
    String value = StringUtils.substringAfter(line, "=").trim();
    // do not overwrite properties that were passed in
    properties.putIfAbsent(key, value);//from   www. ja  va  2s .c o m
}

From source file:eionet.rod.scheduled.AbstractScheduledJob.java

/**
 * Parses job params value from props file and adds to job data map.
 *
 * @param clazz   class which is used for building the job
 * @param jobs    list of jobs// w ww  .j  ava2  s.c om
 * @param jobData full String for several jobs in format key1=valueA;key2=valueB|key1=valueC;key2=valueD|...|key1=valueN
 */
private void parseJobData(Class clazz, List<JobDetail> jobs, String jobData) {
    StringTokenizer differentJobs = new StringTokenizer(jobData, "|");
    while (differentJobs.hasMoreTokens()) {
        String jobParams = differentJobs.nextToken();
        JobDetail jobDetails = newJob(clazz)
                .withIdentity(clazz.getSimpleName() + ":" + jobParams, clazz.getName()).build();
        StringTokenizer args = new StringTokenizer(jobParams, ";");
        while (args.hasMoreTokens()) {
            String arg = args.nextToken();
            String key = StringUtils.substringBefore(arg, "=");
            String value = StringUtils.substringAfter(arg, "=");
            jobDetails.getJobDataMap().put(key, value);
        }
        jobs.add(jobDetails);
    }

}

From source file:edu.monash.merc.system.parser.gpm.GPMRSSReader.java

private GPMSyndEntry createGPMSyndEntry(String ftpLink, Date publishedDate) {
    if (publishedDate == null) {
        return null;
    }//  ww w .  j  a  v  a 2 s.c  om

    if (StringUtils.isBlank(ftpLink)) {
        return null;
    }

    GPMSyndEntry gpmSyndEntry = new GPMSyndEntry();
    gpmSyndEntry.setReleasedTime(publishedDate);

    String tmpFtpDir = StringUtils.substringBeforeLast(ftpLink, PATH_SEPARATOR);
    String ftpPath = StringUtils.substringAfter(tmpFtpDir, FTP_PROTOCOL);
    String ftpServerName = StringUtils.substringBefore(ftpPath, PATH_SEPARATOR);
    String workdir = StringUtils.substringAfter(ftpPath, PATH_SEPARATOR);
    String fileName = StringUtils.substringAfterLast(ftpLink, PATH_SEPARATOR);
    gpmSyndEntry.setGmpFtpServer(ftpServerName);
    gpmSyndEntry.setTpbWorkDir(PATH_SEPARATOR + workdir);
    gpmSyndEntry.setReleasedTpbFileName(fileName);
    return gpmSyndEntry;
}

From source file:edu.mayo.cts2.framework.core.xml.DelegatingMarshaller.java

/**
 * Instantiates a new delgating marshaller.
 *
 * @throws Exception the exception/*w w  w  .j  av a  2 s  . co m*/
 */
public DelegatingMarshaller(boolean validate, ModelXmlPropertiesHandler modelXmlPropertiesHandler) {
    super();
    this.modelXmlPropertiesHandler = modelXmlPropertiesHandler;
    this.castorBuilderProperties = this.modelXmlPropertiesHandler.getCastorBuilderProperties();
    this.namespaceLocationProperties = this.modelXmlPropertiesHandler.getNamespaceLocationProperties();
    this.namespaceMappingProperties = this.modelXmlPropertiesHandler.getNamespaceMappingProperties();

    this.populateNamespaceMaps(this.namespaceMappingProperties, this.namespaceLocationProperties);

    String proxyInterfaces = this.createMapFromProperties(this.modelXmlPropertiesHandler.getCastorProperties())
            .get(PROXY_INTERFACES_PROP);

    this.marshallSuperClasses = new HashSet<String>(Arrays.asList(StringUtils.split(proxyInterfaces, ',')));

    String nsMappings = (String) this.castorBuilderProperties.get(NS_PROP);

    String[] nsAndPackage = StringUtils.split(nsMappings, ",");

    List<String> allPackages = new ArrayList<String>();

    Map<String, String> namespacePackageMapping = new HashMap<String, String>();

    for (String entry : nsAndPackage) {
        String ns = StringUtils.substringBefore(entry, "=");
        String pkg = StringUtils.substringAfter(entry, "=");

        packageToMarshallerMap.put(pkg, createNewMarshaller(ns, validate));
        allPackages.add(pkg);

        namespacePackageMapping.put(ns, pkg);
    }

    this.defaultMarshaller = new PatchedCastorMarshaller();
    this.defaultMarshaller.setNamespaceMappings(this.namespaceMap);
    this.defaultMarshaller.setTargetPackages(Iterables.toArray(allPackages, String.class));
    this.defaultMarshaller.setNamespaceToPackageMapping(namespacePackageMapping);
    this.defaultMarshaller.setValidating(validate);

    try {
        this.defaultMarshaller.afterPropertiesSet();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:gobblin.config.store.deploy.ClasspathConfigSource.java

/**
 * Scan the classpath for {@link #classpathRootName} and opens an {@link InputStream} each resource under it.
 * {@inheritDoc}/*from w ww .jav  a  2 s  . c o  m*/
 * @see gobblin.config.store.deploy.DeployableConfigSource#getConfigStreams()
 */
@Override
public Set<ConfigStream> getConfigStreams() throws IOException {
    Set<ConfigStream> configStreams = Sets.newHashSet();
    for (String configPath : getDeployableConfigPaths()) {
        configStreams.add(new ConfigStream(Optional.of(getConfigStream(configPath)),
                StringUtils.substringAfter(Strings.nullToEmpty(configPath), this.classpathRootName + "/")));
    }
    return configStreams;
}