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:org.cagrid.gaards.websso.utils.FileHelper.java

public URL getFileAsURL(String fileName) throws AuthenticationConfigurationException {
    ClassPathResource cpr = new ClassPathResource(fileName);
    if (!cpr.exists()) {
        throw new AuthenticationConfigurationException("Unable to load " + fileName + " file");
    }/*from ww  w . jav a2 s .co m*/
    try {
        return cpr.getURL();
    } catch (IOException ie) {
        throw new AuthenticationConfigurationException("Unable to load " + fileName + " file");
    }
}

From source file:org.ehcache.integrations.shiro.EhcacheShiroManager.java

private URL getResource() throws IOException {
    String cacheManagerConfigFile = getCacheManagerConfigFile();
    if (cacheManagerConfigFile.startsWith(ResourceUtils.CLASSPATH_PREFIX)) {
        ClassPathResource pajaxResource = new ClassPathResource(stripPrefix(cacheManagerConfigFile));
        return pajaxResource.getURL();
    }/*www .  j  a v a2 s.c o  m*/

    final String url = ResourceUtils.hasResourcePrefix(cacheManagerConfigFile)
            ? stripPrefix(cacheManagerConfigFile)
            : cacheManagerConfigFile;

    return new URL(url);
}

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

@Test
public void fillDbElasticsearch() throws Exception {

    //By using service u are sure than logic rules are applyed
    userService = (ICrudService<User>) applicationContext.getBean("userCrudService");
    providerService = (ICrudService<FoodProvider>) applicationContext.getBean("providerCrudService");
    menuService = (ICrudService<Menu>) applicationContext.getBean("menuCrudService");
    //Mock the security context
    SecurityMockService mockService = new SecurityMockService();
    userService.setSecurityService(mockService);
    menuService.setSecurityService(mockService);
    providerService.setSecurityService(mockService);

    ClassPathResource cpr = new ClassPathResource("data/OwnerAndProvider.csv");
    List<Map<String, String>> usersList = readContactCSV(SolveSpaceErrors(cpr.getURL().getPath()));

    User owner;/*from   w w w .  j  a  v a  2 s.  c o m*/
    FoodProvider foodProvider;
    Menu menu;
    Set<Tag> tags;
    Set<Comment> comments;

    for (Map<String, String> dataMap : usersList) {
        owner = getUser(dataMap.get("email"), dataMap.get("password"), Profile.PROVIDER);

        menu = getMenu(getMealsFromMap(dataMap));
        tags = getTagsFromMap(dataMap);
        comments = getCommentsFromMap(dataMap); // Care the method add user to the database
        Address address = getAddress(dataMap.get("street"), dataMap.get("city"), dataMap.get("postcode"));
        foodProvider = getFoodProvider(owner, menu, tags, dataMap.get("description"), comments, address,
                dataMap.get("name"), dataMap.get("phone"));

        userService.save(owner);
        menuService.save(menu);
        providerService.save(foodProvider);

    }
}

From source file:com.wavemaker.tools.javaservice.JavaServiceDefinition2Test.java

private ServiceDefinition getServiceDefFromJar(String jarFileName) throws Exception {

    List<File> classRoots = new ArrayList<File>();
    List<File> jarDirs = new ArrayList<File>();

    File jarDir = IOUtils.createTempDirectory();
    File srcJarFile = new ClassPathResource(
            this.getClass().getPackage().getName().replace(".", "/") + "/" + jarFileName).getFile();
    File jarFile = new File(jarDir, jarFileName);
    FileUtils.copyFile(srcJarFile, jarFile);
    jarDirs.add(jarDir);/*  w ww .j  a  v a 2  s  . com*/

    ClassPathResource runtimeServiceResource = new ClassPathResource(
            "com/wavemaker/runtime/service/LiveDataService.class");
    if (ResourceUtils.isJarURL(runtimeServiceResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(runtimeServiceResource.getURL());
        jarDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File runtimeServiceClassFile = runtimeServiceResource.getFile();
        File runtimeClassRoot = runtimeServiceClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(runtimeClassRoot);
    }

    ServiceDefinition ret = new JavaServiceDefinition("Foo", "serviceId", classRoots, jarDirs,
            new ArrayList<String>());

    jarFile.delete();
    jarDir.delete();

    return ret;
}

From source file:com.loy.MainFrame.java

@SuppressWarnings("rawtypes")
public void init() {

    String src = "ee.png";
    try {/*from   w  ww .  ja  v a2  s.  c  o  m*/
        ClassPathResource classPathResource = new ClassPathResource(src);
        image = ImageIO.read(classPathResource.getURL());
        this.setIconImage(image);
    } catch (IOException e) {
    }

    menu = new JMenu("LOG CONSOLE");
    this.jmenuBar = new JMenuBar();
    this.jmenuBar.add(menu);

    panel = new JPanel(new BorderLayout());
    this.add(panel);

    ClassPathResource classPathResource = new ClassPathResource("application.yml");
    Yaml yaml = new Yaml();
    Map result = null;
    try {
        result = (Map) yaml.load(classPathResource.getInputStream());
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String platformStr = result.get("platform").toString();
    String version = result.get("version").toString();
    String jvmOption = result.get("jvmOption").toString();
    @SuppressWarnings("unchecked")
    List<String> projects = (List<String>) result.get("projects");
    platform = Platform.valueOf(platformStr);
    final Runtime runtime = Runtime.getRuntime();
    File pidsForder = new File("./pids");
    if (!pidsForder.exists()) {
        pidsForder.mkdir();
    } else {
        File[] files = pidsForder.listFiles();
        if (files != null) {
            for (File f : files) {
                f.deleteOnExit();
                String pidStr = f.getName();
                try {
                    Long pid = new Long(pidStr);
                    if (Processes.isProcessRunning(platform, pid)) {
                        if (Platform.Windows == platform) {
                            Processes.tryKillProcess(null, platform, new NullProcessor(), pid);
                        } else {
                            Processes.killProcess(null, platform, new NullProcessor(), pid);
                        }

                    }
                } catch (Exception ex) {
                }
            }
        }
    }

    File currentForder = new File("");
    String rootPath = currentForder.getAbsolutePath();
    rootPath = rootPath.replace(File.separator + "build" + File.separator + "libs", "");
    rootPath = rootPath.replace(File.separator + "e-example-ms-start-w", "");

    for (String value : projects) {
        String path = value;
        String[] values = value.split("/");
        value = values[values.length - 1];
        String appName = value;
        value = rootPath + "/" + path + "/build/libs/" + value + "-" + version + ".jar";

        JMenuItem menuItem = new JMenuItem(appName);
        JTextArea textArea = new JTextArea();
        textArea.setVisible(true);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setAutoscrolls(true);
        JScrollPane scorll = new JScrollPane(textArea);
        this.textSreaMap.put(appName, scorll);
        EComposite ecomposite = new EComposite();
        ecomposite.setCommand(value);
        ecomposite.setTextArea(textArea);
        composites.put(appName, ecomposite);
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Collection<JScrollPane> values = textSreaMap.values();
                for (JScrollPane t : values) {
                    t.setVisible(false);
                }
                String actions = e.getActionCommand();
                JScrollPane textArea = textSreaMap.get(actions);
                if (textArea != null) {
                    textArea.setVisible(true);
                    panel.removeAll();
                    panel.add(textArea);
                    panel.repaint();
                    panel.validate();
                    self.repaint();
                    self.validate();
                }
            }
        });
        menu.add(menuItem);
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            int size = composites.keySet().size();
            int index = 1;
            for (String appName : composites.keySet()) {
                EComposite composite = composites.get(appName);
                try {

                    Process process = runtime.exec(
                            "java " + jvmOption + " -Dfile.encoding=UTF-8 -jar " + composite.getCommand());
                    Long pid = Processes.processId(process);
                    pids.add(pid);
                    File pidsFile = new File("./pids", pid.toString());
                    pidsFile.createNewFile();

                    new WriteLogThread(process.getInputStream(), composite.getTextArea()).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                synchronized (lock) {
                    try {
                        if (index < size) {
                            lock.wait();
                        } else {
                            index++;
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();

}

From source file:org.dspace.webmvc.controller.ResourceController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path)) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    }/*from w  ww. java 2  s .  c om*/

    final URL url;
    try {
        url = req.getSession().getServletContext().getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }

    final String mimeType = getMimeType(req, path);

    final String realpath = req.getSession().getServletContext().getRealPath(path);
    if (url != null && realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile()) {
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        } else {
            return new StaticFile(f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url);
        }
    } else {
        ClassPathResource cpr = new ClassPathResource(path);
        if (cpr.exists()) {
            URL cprURL = null;
            try {
                cprURL = cpr.getURL();

                // Try as a JAR Entry
                final ZipEntry ze = ((JarURLConnection) cprURL.openConnection()).getJarEntry();
                if (ze != null) {
                    if (ze.isDirectory()) {
                        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                    } else {
                        return new StaticFile(ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req),
                                cprURL);
                    }
                } else {
                    // Unexpected?
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                }
            } catch (ClassCastException e) {
                // Unknown resource type
                if (url != null) {
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                } else {
                    return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
                }
            } catch (IOException e) {
                return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
            }
        } else {
            return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");
        }
    }
}

From source file:com.iflytek.edu.cloud.frame.web.listener.LogBackLoadConfigureListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {/*from   w  w w .j a va 2 s. c  om*/
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();
        ClassPathResource resource = new ClassPathResource("logback-default.xml");
        if (!resource.exists()) {
            String profile = EnvUtil.getProfile();
            resource = new ClassPathResource("META-INF/logback/logback-" + profile + ".xml");
        }

        configurator.doConfigure(resource.getInputStream());
        logger.info("logback?" + resource.getURL().getPath());
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}

From source file:com.wavemaker.tools.javaservice.JavaServiceDefinition2Test.java

private ServiceDefinition getServiceDef(String className, List<File> serviceLibDirs) throws Exception {

    List<File> classRoots = new ArrayList<File>();
    serviceLibDirs = serviceLibDirs == null ? new ArrayList<File>() : serviceLibDirs;

    File classFile = new ClassPathResource(className.replace('.', '/') + ".class").getFile();
    File classRoot = classFile.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();
    classRoots.add(classRoot);/* ww  w  . java  2s  .c om*/

    File queryInfoClassFile = new ClassPathResource(
            JavaService_BeanClass.class.getName().replace('.', '/') + ".class").getFile();
    File queryInfoClassRoot = queryInfoClassFile.getParentFile().getParentFile().getParentFile().getParentFile()
            .getParentFile();
    classRoots.add(queryInfoClassRoot);

    ClassPathResource runtimeServiceResource = new ClassPathResource(
            LiveDataService.class.getName().replace(".", "/") + ".class");
    if (ResourceUtils.isJarURL(runtimeServiceResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(runtimeServiceResource.getURL());
        serviceLibDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File runtimeServiceClassFile = runtimeServiceResource.getFile();
        File runtimeClassRoot = runtimeServiceClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(runtimeClassRoot);
    }

    ClassPathResource typeDefinitionResource = new ClassPathResource(
            TypeDefinition.class.getName().replace(".", "/") + ".class");
    if (ResourceUtils.isJarURL(typeDefinitionResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(typeDefinitionResource.getURL());
        serviceLibDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File typeDefinitionClassFile = typeDefinitionResource.getFile();
        File typeDefinitionClassRoot = typeDefinitionClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(typeDefinitionClassRoot);
    }

    return new JavaServiceDefinition(className, "serviceId", classRoots, serviceLibDirs,
            new ArrayList<String>());
}

From source file:org.jbb.lib.cache.hazelcast.HazelcastConfigFilesManager.java

private void copyFromClasspath(String classpathFileName) {

    ClassPathResource classPathResource = new ClassPathResource(classpathFileName);
    File targetFile = new File(jbbMetaData.jbbConfigDirectory() + File.separator + classpathFileName);
    try {/*from   ww w  .  j  a v  a2 s . c  o m*/
        if (!targetFile.exists()) {
            FileUtils.copyURLToFile(classPathResource.getURL(), targetFile);
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}