Example usage for org.springframework.util StringUtils tokenizeToStringArray

List of usage examples for org.springframework.util StringUtils tokenizeToStringArray

Introduction

In this page you can find the example usage for org.springframework.util StringUtils tokenizeToStringArray.

Prototype

public static String[] tokenizeToStringArray(@Nullable String str, String delimiters) 

Source Link

Document

Tokenize the given String into a String array via a StringTokenizer .

Usage

From source file:org.springframework.jca.context.SpringContextResourceAdapter.java

/**
 * Build a Spring ApplicationContext for the given JCA BootstrapContext.
 * <p>The default implementation builds a {@link ResourceAdapterApplicationContext}
 * and delegates to {@link #loadBeanDefinitions} for actually parsing the
 * specified configuration files./*  w  w  w .  ja v a 2 s .c  o m*/
 * @param bootstrapContext this ResourceAdapter's BootstrapContext
 * @return the Spring ApplicationContext instance
 */
protected ConfigurableApplicationContext createApplicationContext(BootstrapContext bootstrapContext) {
    ResourceAdapterApplicationContext applicationContext = new ResourceAdapterApplicationContext(
            bootstrapContext);

    // Set ResourceAdapter's ClassLoader as bean class loader.
    applicationContext.setClassLoader(getClass().getClassLoader());

    // Extract individual config locations.
    String[] configLocations = StringUtils.tokenizeToStringArray(getContextConfigLocation(),
            CONFIG_LOCATION_DELIMITERS);

    loadBeanDefinitions(applicationContext, configLocations);
    applicationContext.refresh();

    return applicationContext;
}

From source file:org.springframework.osgi.context.ContextLoaderBundleActivator.java

/**
 * Retrieves the org.springframework.context manifest header attribute and
 * parses it to create a String[] of resource names for creating the
 * application context./*w ww. j av  a  2s.  c o  m*/
 * 
 * If the org.springframework.context header is not present, the default
 * <bundle-symbolic-name>-context.xml file will be returned.
 */
protected String[] getApplicationContextLocations(Bundle bundle) {
    Dictionary manifestHeaders = bundle.getHeaders();
    String contextLocationsHeader = (String) manifestHeaders.get(CONTEXT_LOCATION_HEADER);
    if (contextLocationsHeader != null) {
        // (Dictionary does not offer a "containsKey" operation)
        return addBundlePrefixTo(
                StringUtils.tokenizeToStringArray(contextLocationsHeader, CONTEXT_LOCATION_DELIMITERS));
    } else {
        String defaultName = DEFAULT_CONTEXT_PREFIX + bundle.getSymbolicName() + DEFAULT_CONTEXT_POSTFIX;
        return addBundlePrefixTo(new String[] { defaultName });
    }
}

From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java

private boolean supportsInternal(Class<?> clazz, boolean checkForXmlRootElement) {
    if (checkForXmlRootElement && AnnotationUtils.findAnnotation(clazz, XmlRootElement.class) == null) {
        return false;
    }// ww  w .ja  v a 2  s .c o m
    if (StringUtils.hasLength(this.contextPath)) {
        String packageName = ClassUtils.getPackageName(clazz);
        String[] contextPaths = StringUtils.tokenizeToStringArray(this.contextPath, ":");
        for (String contextPath : contextPaths) {
            if (contextPath.equals(packageName)) {
                return true;
            }
        }
        return false;
    } else if (!ObjectUtils.isEmpty(this.classesToBeBound)) {
        return Arrays.asList(this.classesToBeBound).contains(clazz);
    }
    return false;
}

From source file:org.springframework.social.oauth1.SigningSupport.java

private MultiValueMap<String, String> parseFormParameters(String parameterString) {
    if (parameterString == null || parameterString.length() == 0) {
        return EmptyMultiValueMap.instance();
    }//from   w ww. ja va2 s.c o m
    String[] pairs = StringUtils.tokenizeToStringArray(parameterString, "&");
    MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(pairs.length);
    for (String pair : pairs) {
        int idx = pair.indexOf('=');
        if (idx == -1) {
            result.add(formDecode(pair), "");
        } else {
            String name = formDecode(pair.substring(0, idx));
            String value = formDecode(pair.substring(idx + 1));
            result.add(name, value);
        }
    }
    return result;
}

From source file:org.springframework.web.context.ContextLoader.java

/**
 * Return the {@link ApplicationContextInitializer} implementation classes to use
 * if any have been specified by {@link #CONTEXT_INITIALIZER_CLASSES_PARAM}.
 * @param servletContext current servlet context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 *//*from   w ww.  ja v a2 s  .  c o  m*/
protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> determineContextInitializerClasses(
        ServletContext servletContext) {

    List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes = new ArrayList<>();

    String globalClassNames = servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM);
    if (globalClassNames != null) {
        for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) {
            classes.add(loadInitializerClass(className));
        }
    }

    String localClassNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM);
    if (localClassNames != null) {
        for (String className : StringUtils.tokenizeToStringArray(localClassNames, INIT_PARAM_DELIMITERS)) {
            classes.add(loadInitializerClass(className));
        }
    }

    return classes;
}

From source file:org.springframework.web.socket.sockjs.AbstractSockJsService.java

/**
 * TODO/*w w  w  . ja  v  a 2 s  .c  om*/
 *
 * @param request
 * @param response
 * @param sockJsPath
 *
 * @throws Exception
 */
@Override
public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
        WebSocketHandler handler) throws IOException, TransportErrorException {

    String sockJsPath = getSockJsPath(request);
    if (sockJsPath == null) {
        logger.warn("Could not determine SockJS path for URL \"" + request.getURI().getPath()
                + ". Consider setting validSockJsPrefixes.");
        response.setStatusCode(HttpStatus.NOT_FOUND);
        return;
    }

    logger.debug(request.getMethod() + " with SockJS path [" + sockJsPath + "]");

    try {
        request.getHeaders();
    } catch (IllegalArgumentException ex) {
        // Ignore invalid Content-Type (TODO)
    }

    try {
        if (sockJsPath.equals("") || sockJsPath.equals("/")) {
            response.getHeaders().setContentType(new MediaType("text", "plain", Charset.forName("UTF-8")));
            response.getBody().write("Welcome to SockJS!\n".getBytes("UTF-8"));
            return;
        } else if (sockJsPath.equals("/info")) {
            this.infoHandler.handle(request, response);
            return;
        } else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) {
            this.iframeHandler.handle(request, response);
            return;
        } else if (sockJsPath.equals("/websocket")) {
            handleRawWebSocketRequest(request, response, handler);
            return;
        }

        String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/");
        if (pathSegments.length != 3) {
            logger.warn("Expected \"/{server}/{session}/{transport}\" but got \"" + sockJsPath + "\"");
            response.setStatusCode(HttpStatus.NOT_FOUND);
            return;
        }

        String serverId = pathSegments[0];
        String sessionId = pathSegments[1];
        String transport = pathSegments[2];

        if (!validateRequest(serverId, sessionId, transport)) {
            response.setStatusCode(HttpStatus.NOT_FOUND);
            return;
        }

        handleTransportRequest(request, response, sessionId, TransportType.fromValue(transport), handler);
    } finally {
        response.flush();
    }
}

From source file:org.springframework.web.socket.sockjs.support.AbstractSockJsService.java

/**
 * This method determines the SockJS path and handles SockJS static URLs.
 * Session URLs and raw WebSocket requests are delegated to abstract methods.
 *//*from   w w w  .j  a v a2s  . com*/
@Override
public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
        @Nullable String sockJsPath, WebSocketHandler wsHandler) throws SockJsException {

    if (sockJsPath == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Expected SockJS path. Failing request: " + request.getURI());
        }
        response.setStatusCode(HttpStatus.NOT_FOUND);
        return;
    }

    try {
        request.getHeaders();
    } catch (InvalidMediaTypeException ex) {
        // As per SockJS protocol content-type can be ignored (it's always json)
    }

    String requestInfo = (logger.isDebugEnabled() ? request.getMethod() + " " + request.getURI() : null);

    try {
        if (sockJsPath.equals("") || sockJsPath.equals("/")) {
            if (requestInfo != null) {
                logger.debug("Processing transport request: " + requestInfo);
            }
            response.getHeaders().setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
            response.getBody().write("Welcome to SockJS!\n".getBytes(StandardCharsets.UTF_8));
        }

        else if (sockJsPath.equals("/info")) {
            if (requestInfo != null) {
                logger.debug("Processing transport request: " + requestInfo);
            }
            this.infoHandler.handle(request, response);
        }

        else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) {
            if (!this.allowedOrigins.isEmpty() && !this.allowedOrigins.contains("*")) {
                if (requestInfo != null) {
                    logger.debug("Iframe support is disabled when an origin check is required. "
                            + "Ignoring transport request: " + requestInfo);
                }
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            }
            if (this.allowedOrigins.isEmpty()) {
                response.getHeaders().add(XFRAME_OPTIONS_HEADER, "SAMEORIGIN");
            }
            if (requestInfo != null) {
                logger.debug("Processing transport request: " + requestInfo);
            }
            this.iframeHandler.handle(request, response);
        }

        else if (sockJsPath.equals("/websocket")) {
            if (isWebSocketEnabled()) {
                if (requestInfo != null) {
                    logger.debug("Processing transport request: " + requestInfo);
                }
                handleRawWebSocketRequest(request, response, wsHandler);
            } else if (requestInfo != null) {
                logger.debug("WebSocket disabled. Ignoring transport request: " + requestInfo);
            }
        }

        else {
            String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/");
            if (pathSegments.length != 3) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Invalid SockJS path '" + sockJsPath + "' - required to have 3 path segments");
                }
                if (requestInfo != null) {
                    logger.debug("Ignoring transport request: " + requestInfo);
                }
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            }

            String serverId = pathSegments[0];
            String sessionId = pathSegments[1];
            String transport = pathSegments[2];

            if (!isWebSocketEnabled() && transport.equals("websocket")) {
                if (requestInfo != null) {
                    logger.debug("WebSocket disabled. Ignoring transport request: " + requestInfo);
                }
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            } else if (!validateRequest(serverId, sessionId, transport) || !validatePath(request)) {
                if (requestInfo != null) {
                    logger.debug("Ignoring transport request: " + requestInfo);
                }
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            }

            if (requestInfo != null) {
                logger.debug("Processing transport request: " + requestInfo);
            }
            handleTransportRequest(request, response, wsHandler, sessionId, transport);
        }
        response.close();
    } catch (IOException ex) {
        throw new SockJsException("Failed to write to the response", null, ex);
    }
}

From source file:org.springframework.web.struts.ContextLoaderPlugIn.java

/**
 * Instantiate the WebApplicationContext for the ActionServlet, either a default
 * XmlWebApplicationContext or a custom context class if set. This implementation
 * expects custom contexts to implement ConfigurableWebApplicationContext.
 * Can be overridden in subclasses./*from w  ww  . j  a  v  a  2  s.c  om*/
 * @throws org.springframework.beans.BeansException if the context couldn't be initialized
 * @see #setContextClass
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
        throws BeansException {

    if (logger.isDebugEnabled()) {
        logger.debug("ContextLoaderPlugIn for Struts ActionServlet '" + getServletName() + "', module '"
                + getModulePrefix() + "' will try to create custom WebApplicationContext "
                + "context of class '" + getContextClass().getName() + "', using parent context [" + parent
                + "]");
    }
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(getContextClass())) {
        throw new ApplicationContextException(
                "Fatal initialization error in ContextLoaderPlugIn for Struts ActionServlet '"
                        + getServletName() + "', module '" + getModulePrefix()
                        + "': custom WebApplicationContext class [" + getContextClass().getName()
                        + "] is not of type ConfigurableWebApplicationContext");
    }

    ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils
            .instantiateClass(getContextClass());
    wac.setParent(parent);
    wac.setServletContext(getServletContext());
    wac.setNamespace(getNamespace());
    if (getContextConfigLocation() != null) {
        wac.setConfigLocations(StringUtils.tokenizeToStringArray(getContextConfigLocation(),
                ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));
    }
    wac.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            beanFactory.addBeanPostProcessor(new ActionServletAwareProcessor(getActionServlet()));
        }
    });
    wac.refresh();
    return wac;
}