Example usage for org.springframework.util ResourceUtils isUrl

List of usage examples for org.springframework.util ResourceUtils isUrl

Introduction

In this page you can find the example usage for org.springframework.util ResourceUtils isUrl.

Prototype

public static boolean isUrl(@Nullable String resourceLocation) 

Source Link

Document

Return whether the given resource location is a URL: either a special "classpath" pseudo URL or a standard URL.

Usage

From source file:com.shengpay.commons.bp.logback.LogbackWebConfigurer.java

/**
 * Initialize logback, including setting the web app root system property.
 * /*w w  w.ja v a  2s.com*/
 * @param servletContext
 *            the current ServletContext
 * @see WebUtils#setWebAppRootSystemProperty
 */
public static void initLogging(ServletContext servletContext) {
    // Expose the web app root system property.
    if (exposeWebAppRoot(servletContext)) {
        WebUtils.setWebAppRootSystemProperty(servletContext);
    }

    // Only perform custom logback initialization in case of a config file.
    String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
    if (location != null) {
        // Perform actual logback initialization; else rely on logback's default initialization.
        try {
            // Return a URL (e.g. "classpath:" or "file:") as-is;
            // consider a plain file path as relative to the web application root directory.
            if (!ResourceUtils.isUrl(location)) {
                // Resolve system property placeholders before resolving real path.
                location = SystemPropertyUtils.resolvePlaceholders(location);
                location = WebUtils.getRealPath(servletContext, location);
            }

            // Write log message to server log.
            servletContext.log("Initializing logback from [" + location + "]");

            // Initialize without refresh check, i.e. without logback's watchdog thread.
            LogbackConfigurer.initLogging(location);

        } catch (FileNotFoundException ex) {
            throw new IllegalArgumentException("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage());
        }
    }
}

From source file:com.excilys.ebi.utils.spring.log.logback.web.LogbackWebConfigurer.java

/**
 * Initialize Logback, including setting the web app root system property.
 * /*from w  w  w  .  j a  v a  2  s .c  o  m*/
 * @param servletContext
 *            the current ServletContext
 * @see org.springframework.web.util.WebUtils#setWebAppRootSystemProperty
 */
public static void initLogging(ServletContext servletContext) {

    // Only perform custom Logback initialization in case of a config file.
    String location = getConfigLocation(servletContext);

    if (location != null) {
        // Perform actual Logback initialization; else rely on Logback's
        // default initialization.
        try {
            // Return a URL (e.g. "classpath:" or "file:") as-is;
            // consider a plain file path as relative to the web application
            // root directory.
            if (!ResourceUtils.isUrl(location)) {
                // Resolve system property placeholders before resolving
                // real path.
                location = SystemPropertyUtils.resolvePlaceholders(location);
                location = WebUtils.getRealPath(servletContext, location);
            }

            // Write log message to server log.
            servletContext.log("Initializing Logback from [" + location + "]");

            // Initialize
            LogbackConfigurer.initLogging(location);
        } catch (FileNotFoundException ex) {
            throw new IllegalArgumentException("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage());
        } catch (JoranException e) {
            throw new RuntimeException("Unexpected error while configuring logback", e);
        }
    }
}

From source file:com.haulmont.cuba.core.sys.AbstractAppContextLoader.java

protected void replaceLocationsFromConf(String[] locations) {
    String confDirProp = AppContext.getProperty("cuba.confDir");
    if (confDirProp == null)
        throw new IllegalStateException("cuba.confDir app property is not set");
    File confDir = new File(confDirProp);
    for (int i = 0; i < locations.length; i++) {
        String location = locations[i];
        if (ResourceUtils.isUrl(location))
            continue;
        if (location.startsWith("/"))
            location = location.substring(1);
        File file = new File(confDir, location);
        if (file.exists()) {
            locations[i] = file.toURI().toString();
        }/*from  www.  ja  v  a  2s .com*/
    }
}

From source file:com.haulmont.cuba.core.sys.remoting.RemotingServlet.java

@Override
public String getContextConfigLocation() {
    String configProperty = AppContext.getProperty(SPRING_CONTEXT_CONFIG);
    if (StringUtils.isBlank(configProperty)) {
        throw new IllegalStateException("Missing " + SPRING_CONTEXT_CONFIG + " application property");
    }/*w  ww.  jav  a 2  s.  c  o  m*/
    File baseDir = new File(AppContext.getProperty("cuba.confDir"));

    StrTokenizer tokenizer = new StrTokenizer(configProperty);
    String[] tokenArray = tokenizer.getTokenArray();
    StringBuilder locations = new StringBuilder();
    for (String token : tokenArray) {
        String location;
        if (ResourceUtils.isUrl(token)) {
            location = token;
        } else {
            if (token.startsWith("/"))
                token = token.substring(1);
            File file = new File(baseDir, token);
            if (file.exists()) {
                location = file.toURI().toString();
            } else {
                location = "classpath:" + token;
            }
        }
        locations.append(location).append(" ");
    }
    return locations.toString();
}

From source file:ch.qos.logback.ext.spring.web.WebLogbackConfigurer.java

/**
 * Initialize Logback, including setting the web app root system property.
 *
 * @param servletContext the current ServletContext
 * @see org.springframework.web.util.WebUtils#setWebAppRootSystemProperty
 *//*from w w  w  .j  a  va  2  s .  c o  m*/
public static void initLogging(ServletContext servletContext) {
    // Expose the web app root system property.
    if (exposeWebAppRoot(servletContext)) {
        WebUtils.setWebAppRootSystemProperty(servletContext);
    }

    // Only perform custom Logback initialization in case of a config file.
    String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
    if (location != null) {
        // Perform actual Logback initialization; else rely on Logback's default initialization.
        try {
            // Resolve system property placeholders before potentially resolving real path.
            location = ServletContextPropertyUtils.resolvePlaceholders(location);
            // Return a URL (e.g. "classpath:" or "file:") as-is;
            // consider a plain file path as relative to the web application root directory.
            if (!ResourceUtils.isUrl(location)) {
                location = WebUtils.getRealPath(servletContext, location);
            }

            // Write log message to server log.
            servletContext.log("Initializing Logback from [" + location + "]");

            // Initialize
            LogbackConfigurer.initLogging(location);
        } catch (FileNotFoundException ex) {
            throw new IllegalArgumentException("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage());
        } catch (JoranException e) {
            throw new RuntimeException("Unexpected error while configuring logback", e);
        }
    }

    //If SLF4J's java.util.logging bridge is available in the classpath, install it. This will direct any messages
    //from the Java Logging framework into SLF4J. When logging is terminated, the bridge will need to be uninstalled
    try {
        Class<?> julBridge = ClassUtils.forName("org.slf4j.bridge.SLF4JBridgeHandler",
                ClassUtils.getDefaultClassLoader());

        Method removeHandlers = ReflectionUtils.findMethod(julBridge, "removeHandlersForRootLogger");
        if (removeHandlers != null) {
            servletContext.log("Removing all previous handlers for JUL to SLF4J bridge");
            ReflectionUtils.invokeMethod(removeHandlers, null);
        }

        Method install = ReflectionUtils.findMethod(julBridge, "install");
        if (install != null) {
            servletContext.log("Installing JUL to SLF4J bridge");
            ReflectionUtils.invokeMethod(install, null);
        }
    } catch (ClassNotFoundException ignored) {
        //Indicates the java.util.logging bridge is not in the classpath. This is not an indication of a problem.
        servletContext.log("JUL to SLF4J bridge is not available on the classpath");
    }
}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

protected void initAppProperties(ServletContext sc) {
    // get properties from web.xml
    String appProperties = sc.getInitParameter(APP_PROPS_PARAM);
    if (appProperties != null) {
        StrTokenizer tokenizer = new StrTokenizer(appProperties);
        for (String str : tokenizer.getTokenArray()) {
            int i = str.indexOf("=");
            if (i < 0)
                continue;
            String name = StringUtils.substring(str, 0, i);
            String value = StringUtils.substring(str, i + 1);
            if (!StringUtils.isBlank(name)) {
                AppContext.setProperty(name, value);
            }/* w  w w. j  av a 2  s .  com*/
        }
    }

    // get properties from a set of app.properties files defined in web.xml
    String propsConfigName = getAppPropertiesConfig(sc);
    if (propsConfigName == null)
        throw new IllegalStateException(APP_PROPS_CONFIG_PARAM + " servlet context parameter not defined");

    final Properties properties = new Properties();

    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    StrTokenizer tokenizer = new StrTokenizer(propsConfigName);
    tokenizer.setQuoteChar('"');
    for (String str : tokenizer.getTokenArray()) {
        log.trace("Processing properties location: {}", str);
        str = StrSubstitutor.replaceSystemProperties(str);
        InputStream stream = null;
        try {
            if (ResourceUtils.isUrl(str) || str.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
                Resource resource = resourceLoader.getResource(str);
                if (resource.exists())
                    stream = resource.getInputStream();
            } else {
                stream = sc.getResourceAsStream(str);
            }

            if (stream != null) {
                log.info("Loading app properties from {}", str);
                try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                    properties.load(reader);
                }
            } else {
                log.trace("Resource {} not found, ignore it", str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    for (Object key : properties.keySet()) {
        AppContext.setProperty((String) key, properties.getProperty((String) key).trim());
    }
}

From source file:org.biopax.validator.Main.java

public static Collection<Resource> getResourcesToValidate(String input) throws IOException {
    Set<Resource> setRes = new HashSet<Resource>();

    File fileOrDir = new File(input);
    if (fileOrDir.isDirectory()) {
        // validate all the OWL files in the folder
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return (name.endsWith(".owl"));
            }/*from   w w w  . j  a va 2s  .co m*/
        };
        for (String s : fileOrDir.list(filter)) {
            String uri = "file:" + fileOrDir.getCanonicalPath() + File.separator + s;
            setRes.add(ctx.getResource(uri));
        }
    } else if (input.startsWith("list:")) {
        // consider it's a file that contains a list of (pseudo-)URLs
        String batchFile = input.replaceFirst("list:", "file:");
        Reader isr = new InputStreamReader(ctx.getResource(batchFile).getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        String line;
        while ((line = reader.readLine()) != null && !"".equals(line.trim())) {
            // check the source URL
            if (!ResourceUtils.isUrl(line)) {
                log.error("Invalid URL: " + line + ". A resource must be either a "
                        + "pseudo URL (classpath: or file:) or standard URL!");
                continue;
            }
            setRes.add(ctx.getResource(line));
        }
        reader.close();
    } else {
        // a single local OWL file or remote data
        Resource resource = null;
        if (!ResourceUtils.isUrl(input))
            input = "file:" + input;
        resource = ctx.getResource(input);
        setRes.add(resource);
    }

    return setRes;
}

From source file:org.apache.syncope.core.logic.SAML2SPLogic.java

private void validateUrl(final String url) {
    boolean isValid = true;
    if (url.contains("..")) {
        isValid = false;/*from  w  ww. ja  va2 s.  c  om*/
    }
    if (isValid) {
        isValid = ResourceUtils.isUrl(url);
    }

    if (!isValid) {
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add("Invalid URL: " + url);
        throw sce;
    }
}

From source file:org.codenergic.theskeleton.core.security.SecurityConfig.java

/**
* Token converter and enhancer//from  w w w.j a  va2s . c  o m
* @return
*/
@Bean
public JwtAccessTokenConverter accessTokenConverter(@Value("${security.jwt.signing-key:}") String signingKey,
        ResourceLoader resourceLoader) throws IOException {
    DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
    accessTokenConverter.setUserTokenConverter(new UserAccessTokenAuthenticationConverter());
    JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAccessTokenConverter.setAccessTokenConverter(accessTokenConverter);
    if (StringUtils.isBlank(signingKey))
        return jwtAccessTokenConverter;
    if (ResourceUtils.isUrl(signingKey)) {
        Resource signingKeyResource = resourceLoader.getResource(signingKey);
        signingKey = IOUtils.toString(signingKeyResource.getURI(), StandardCharsets.UTF_8);
    }
    jwtAccessTokenConverter.setSigningKey(signingKey);
    jwtAccessTokenConverter.setVerifierKey(signingKey);
    return jwtAccessTokenConverter;
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.resource.openmrs1_8.ModuleActionResource1_8.java

/**
 * Overriding create directly, because ModuleFactory requires ServletContext to execute any
 * action/*from   w  w  w .  ja v  a  2  s.c o  m*/
 */
@Override
public Object create(SimpleObject post, RequestContext context) throws ResponseException {
    moduleFactoryWrapper.checkPrivilege();

    ModuleAction action = newDelegate();
    setConvertedProperties(action, post, getCreatableProperties(), true);
    String installUri = action.getInstallUri();

    Collection<Module> modules;
    if (action.isAllModules() != null && action.isAllModules()) {
        modules = moduleFactoryWrapper.getLoadedModules();
        action.setModules(new ArrayList<Module>(modules));
    } else {
        modules = action.getModules();
    }

    ServletContext servletContext = getServletContext(context);

    if (modules == null || modules.isEmpty()) {
        throw new IllegalRequestException(
                "Cannot execute action " + action.getAction() + " on empty set of modules.");
    } else {
        if (action.getAction() == Action.INSTALL) {
            if (installUri == null || !ResourceUtils.isUrl(installUri)) {
                throw new IllegalRequestException(
                        "The installUri needs to be a URL for this action to be performed");
            }
        } else {
            if (action.isAllModules() == null || !action.isAllModules()) {
                // ensure all specified modules exist
                // ensure they're not trying to modify the REST module
                for (Module module : modules) {
                    // if they specified a module that's not loaded, it will show up here as null
                    if (module == null) {
                        throw new IllegalRequestException(
                                "One or more of the modules you specified are not loaded on this server");
                    }
                    if (module.getModuleId().equals(RestConstants.MODULE_ID)) {
                        throw new IllegalRequestException("You are not allowed to modify "
                                + module.getModuleId() + " via this REST call");
                    }
                }
            }

            // even if they said allModule=true, don't touch the REST module
            Module restModule = moduleFactoryWrapper.getModuleById(RestConstants.MODULE_ID);
            modules.remove(restModule);
        }

        switch (action.getAction()) {
        case START:
            startModules(modules, servletContext);
            break;
        case STOP:
            stopModules(modules, servletContext, true);
            break;
        case RESTART:
            restartModules(modules, servletContext);
            break;
        case UNLOAD:
            unloadModules(modules, servletContext);
            break;
        case INSTALL:
            Module module = installModule(modules, installUri, servletContext);
            modules.clear();
            modules.add(module);
            action.setModules(new ArrayList<Module>(modules));
            break;
        }
    }

    return ConversionUtil.convertToRepresentation(action, Representation.DEFAULT);
}