Example usage for org.springframework.core.io ClassPathResource getURL

List of usage examples for org.springframework.core.io ClassPathResource getURL

Introduction

In this page you can find the example usage for org.springframework.core.io ClassPathResource getURL.

Prototype

@Override
public URL getURL() throws IOException 

Source Link

Document

This implementation returns a URL for the underlying class path resource, if available.

Usage

From source file:ratpack.spring.config.RatpackProperties.java

static Resource initBaseDir() {
    ClassPathResource classPath = new ClassPathResource("");
    try {//from   ww w  .  j ava 2s . com
        if (classPath.getURL().toString().startsWith("jar:")) {
            return classPath;
        }
    } catch (IOException e) {
    }
    FileSystemResource resources = new FileSystemResource("src/main/resources");
    if (resources.exists()) {
        return resources;
    }
    return new FileSystemResource(".");
}

From source file:com.aol.advertising.qiao.util.CommonUtils.java

/**
 * Extends scheme to include 'classpath'.
 *
 * @param uriString/*from  w w w  .ja  va2s  .  co m*/
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
public static URL uriToURL(String uriString) throws URISyntaxException, IOException {
    URI uri = new URI(uriString);
    String scheme = uri.getScheme();
    if (scheme == null)
        throw new URISyntaxException(uriString, "Invalid URI syntax: missing scheme => " + uriString);

    if (scheme.equals("classpath")) {
        ClassPathResource res = new ClassPathResource(uri.getSchemeSpecificPart());
        return res.getURL();
    } else {
        return uri.toURL();
    }
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * /*  w  w  w .j  av a  2 s  .  c om*/
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

From source file:org.xmlactions.common.io.ResourceUtils.java

/**
 * Get a URL for a given resource. The resource must exist or an exception
 * is caused.//from w ww  .j ava  2  s  . co  m
 * 
 * @param resourceName
 * @return the URL of the resource.
 */
public static URL getResourceURL(ApplicationContext appContext, String resourceName, Class<?> clas) {
    URL resource = null;
    try {
        if (appContext != null) {
            resource = appContext.getResource(resourceName).getURL();
        } else {
            ClassPathResource cpr = new ClassPathResource(resourceName);
            resource = cpr.getURL();
        }

        if (resource == null) {
            resource = ResourceUtils.class.getResource(resourceName);
            if (resource == null) {
                resource = clas.getResource(resourceName);
            }
        }
    } catch (IOException ex) {
        // TODO Auto-generated catch block
        throw new IllegalArgumentException("Unable to load resource [" + resourceName + "]", ex);
    }
    Validate.notNull(resource, "Unable to load resource [" + resourceName + "]");

    return resource;
}

From source file:com.example.PathTests.java

@Test
public void test() throws Exception {
    ClassPathResource classPath = new ClassPathResource("");
    System.err.println(classPath.getURL().toString());
    System.err.println(Paths.get(new FileSystemResource(new FileSystemResource("src/main/resources").getURL()
            .toURI().toString().substring("file:".length())).getFile().toURI()).isAbsolute());
}

From source file:com.textocat.textokit.morph.opencorpora.OpencorporaMorphDictionaryAPI.java

@Override
public GramModel getGramModel() throws Exception {
    ClassPathResource cpRes = locateDictionaryClasspathResource();
    return GramModelDeserializer.from(cpRes.getInputStream(), cpRes.getURL().toString());
}

From source file:fr.esiea.windmeal.fill.database.UserImportationTest.java

@Test
public void fillDbElasticsearch() throws Exception {
    ICrudService<User> userService;

    //By using service u are sure than logic rules are applyed
    userService = (ICrudService<User>) applicationContext.getBean("userCrudService");
    //Mock the security context
    SecurityMockService mockService = new SecurityMockService();
    userService.setSecurityService(mockService);
    ClassPathResource cpr = new ClassPathResource("data/users.csv");
    List<Map<String, String>> usersList = readContactCSV(SolveSpaceErrors(cpr.getURL().getPath()));

    User user;/*from  w w  w  .  ja  va2 s.c  o  m*/

    for (Map<String, String> userMap : usersList) {
        user = getUser(userMap.get("email"), userMap.get("password"), Profile.valueOf(userMap.get("profile")));
        userService.insert(user);
    }
}

From source file:org.openvpms.esci.adapter.AbstractESCITest.java

/**
 * Helper to return the URL of a WSDL file, given its resource path.
 *
 * @param resourcePath the path to the WSDL resource
 * @return the URL of the WSDL resource/*from w  ww. ja va2 s .c  o  m*/
 * @throws RuntimeException if the URL is invalid
 */
protected String getWSDL(String resourcePath) {
    ClassPathResource wsdl = new ClassPathResource(resourcePath);
    try {
        return wsdl.getURL().toString();
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    }
}

From source file:com.textocat.textokit.morph.opencorpora.OpencorporaMorphDictionaryAPI.java

@Override
public CachedResourceTuple<MorphDictionary> getCachedInstance() throws Exception {
    ClassPathResource cpRes = locateDictionaryClasspathResource();
    CachedDictionaryDeserializer.GetDictionaryResult gdr = CachedDictionaryDeserializer.getInstance()
            .getDictionary(cpRes.getURL(), cpRes.getInputStream());
    return new CachedResourceTuple<>(gdr.cacheKey, gdr.dictionary);
}

From source file:org.apache.shiro.samples.spring.ui.WebStartView.java

public void afterPropertiesSet() throws Exception {
    ClassPathResource resource = new ClassPathResource("logo.png");
    ImageIcon icon = new ImageIcon(resource.getURL());
    JLabel logo = new JLabel(icon);

    valueField = new JTextField(20);
    updateValueLabel();/*from w  ww . java2  s.  c  o  m*/

    saveButton = new JButton("Save Value");
    saveButton.addActionListener(this);

    refreshButton = new JButton("Refresh Value");
    refreshButton.addActionListener(this);

    JPanel valuePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    valuePanel.add(valueField);
    valuePanel.add(saveButton);
    valuePanel.add(refreshButton);

    secureMethod1Button = new JButton("Method #1");
    secureMethod1Button.addActionListener(this);

    secureMethod2Button = new JButton("Method #2");
    secureMethod2Button.addActionListener(this);

    secureMethod3Button = new JButton("Method #3");
    secureMethod3Button.addActionListener(this);

    JPanel methodPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    methodPanel.add(secureMethod1Button);
    methodPanel.add(secureMethod2Button);
    methodPanel.add(secureMethod3Button);

    frame = new JFrame("Apache Shiro Sample Application");
    frame.setSize(500, 200);

    Container panel = frame.getContentPane();
    panel.setLayout(new BorderLayout());
    panel.add(logo, BorderLayout.NORTH);
    panel.add(valuePanel, BorderLayout.CENTER);
    panel.add(methodPanel, BorderLayout.SOUTH);

    frame.setVisible(true);
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}