Example usage for org.springframework.core.io FileSystemResource FileSystemResource

List of usage examples for org.springframework.core.io FileSystemResource FileSystemResource

Introduction

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

Prototype

public FileSystemResource(Path filePath) 

Source Link

Document

Create a new FileSystemResource from a Path handle, performing all file system interactions via NIO.2 instead of File .

Usage

From source file:com.siberhus.tdfl.DataFileLoader.java

/**
 * /*from   w  w  w .j  a  v  a 2s  .  c  o  m*/
 * @return
 * @throws DataFileLoaderException
 */
private Resource[] getSources() throws DataFileLoaderException {

    Assert.notNull(resource, "resource is a required property");

    Resource sources[] = null;

    File resourceFile = null;

    try {

        resourceFile = resource.getFile();

        if (resourceFile.exists()) {
            if (resourceFile.isDirectory()) {
                if (destination != null) {
                    if (!destination.getFile().exists()) {
                        if (!destination.getFile().mkdir()) {
                            throw new IOException("Failed to create directory: " + destination);
                        }
                    }
                    if (!destination.getFile().isDirectory()) {
                        throw new IllegalArgumentException(
                                "resource and destination must be the same file type [file|directory].");
                    }
                }
            }
        } else {
            throw new FileNotFoundException("Resource: " + resource + " not found.");
        }

        if (resourceFile.isDirectory()) {
            File files[] = resourceFile.listFiles(directoryListingFilter);
            List<Resource> sourceList = new ArrayList<Resource>();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory())
                    continue;
                //for now we support only FileSystemResource
                sourceList.add(new FileSystemResource(files[i].getCanonicalPath()));
            }
            sources = sourceList.toArray(new Resource[0]);
        } else {
            sources = new Resource[] { resource };
        }

    } catch (Exception e) {
        throw new DataFileLoaderException(e.getMessage(), e);
    }

    if (sources.length == 0) {
        logger.warn("No resources to read");
        return null;
    }

    Arrays.sort(sources, comparator);
    return sources;
}

From source file:com.google.api.ads.adwords.awreporting.server.appengine.RestServer.java

/**
 * Initialize the application context, adding the properties configuration file depending on the
 * specified path.//from w ww.ja  v  a  2s.  c  o  m
 */
protected synchronized static void initApplicationContextAndProperties() {

    // Resister all Model Objects in the ObjectifyService
    ObjectifyService.factory().getTranslators().add(new BigDecimalLongTranslatorFactory(1000000000));

    ObjectifyService.register(UserToken.class);

    // AwReporting Server model objects
    ObjectifyService.register(Account.class);
    ObjectifyService.register(HtmlTemplate.class);

    // AwReporting model objects
    ObjectifyService.register(AuthMcc.class);
    ObjectifyService.register(ReportAccount.class);
    ObjectifyService.register(ReportAd.class);
    ObjectifyService.register(ReportAdExtension.class);
    ObjectifyService.register(ReportAdGroup.class);
    ObjectifyService.register(ReportBudget.class);
    ObjectifyService.register(ReportCampaign.class);
    ObjectifyService.register(ReportCampaignNegativeKeyword.class);
    ObjectifyService.register(ReportCriteriaPerformance.class);
    ObjectifyService.register(ReportDestinationUrl.class);
    ObjectifyService.register(ReportKeyword.class);
    ObjectifyService.register(ReportPlaceholderFeedItem.class);
    ObjectifyService.register(ReportUrl.class);

    try {
        Resource resource = new ClassPathResource(PROPERTIES_FILE);
        if (!resource.exists()) {
            resource = new FileSystemResource(PROPERTIES_FILE);
        }
        DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);

        properties = PropertiesLoaderUtils.loadProperties(resource);

    } catch (IOException e) {
        LOGGER.severe("Error reading properties file " + e.getMessage());
    }

    // Loading AppEngine DB type by default (ignoring DB type from properties file)
    appCtx = new ClassPathXmlApplicationContext("classpath:aw-reporting-appengine-beans.xml");
    persister = appCtx.getBean(EntityPersister.class);
    authenticator = appCtx.getBean(AppEngineOAuth2Authenticator.class);
    webAuthenticator = appCtx.getBean(WebAuthenticator.class);
}

From source file:org.trpr.platform.batch.impl.spring.admin.SimpleJobConfigurationService.java

/**
 * Scans XML Spring Batch Config files and adds them to jobXMLFile map
 *//*from  w w w  . ja  v a 2s  . co m*/
private void scanXMLFiles() {
    File[] jobBeansFiles = FileLocator.findFiles(BatchFrameworkConstants.SPRING_BATCH_CONFIG);
    for (File jobBeansFile : jobBeansFiles) {
        for (String jobName : ConfigFileUtils.getJobName(new FileSystemResource(jobBeansFile))) {
            this.jobXMLFile.put(jobName, jobBeansFile.toURI());
        }
    }
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private void registerCndFiles(File file) throws IOException, ParseException, RepositoryException {
    String cndPath = StringUtils.substringAfter(file.getPath(),
            File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator);
    // transform \ to / for windows filesystem compatibility
    cndPath = StringUtils.replace(cndPath, File.separator, "/");
    final File folder;
    if (file.getName().toLowerCase().startsWith(LEGACY_DEFS_FILE_PREFIX)
            || ((folder = file.getParentFile()) != null
                    && LEGACY_DEFS_FOLDER_NAME.equalsIgnoreCase(folder.getName()))) {
        logger.debug("Skipping legacy definitions file: " + cndPath);
        return;//from  w w w  .  j  av  a2  s . c  o  m
    }

    List<String> definitionsFiles = module.getDefinitionsFiles();
    if (file.exists() && !definitionsFiles.contains(cndPath)) {
        definitionsFiles.add(cndPath);
    } else if (!file.exists() && definitionsFiles.contains(cndPath)) {
        definitionsFiles.remove(cndPath);
    }

    String systemId = module.getId();
    NodeTypeRegistry nodeTypeRegistry = NodeTypeRegistry.getInstance();

    // Gather all definitions files
    List<Resource> resourceList = new ArrayList<>();
    long lastModified = 0;
    for (String path : definitionsFiles) {
        File realFile = getRealFile(SRC_MAIN_RESOURCES + path);
        resourceList.add(new FileSystemResource(realFile));
        if (realFile.lastModified() > lastModified) {
            lastModified = realFile.lastModified();
        }
    }
    logger.info("Registering CND from source file " + file);
    boolean latestDefinitions = JCRStoreService.getInstance().isLatestDefinitions(systemId, module.getVersion(),
            lastModified);
    if (latestDefinitions) {
        try {
            // Register in local NodeTypeRegistry
            nodeTypeRegistry.addDefinitionsFile(resourceList, systemId);
            // Register into jackrabbit
            jcrStoreService.deployDefinitions(systemId, module.getVersion().toString(), lastModified);
        } catch (IOException | ParseException e) {
            throw new RepositoryException(e.getMessage(), e);
        }
    }
}

From source file:org.globus.security.stores.PEMKeyStore.java

@SuppressWarnings("unchecked")
private CredentialWrapper createProxyCredential(String s, X509Credential credential) throws KeyStoreException {
    CredentialWrapper wrapper;//from  w  w w.j a v a 2s.  co m
    CredentialWrapper proxyCredential = getKeyEntry(s);
    File file;
    if (proxyCredential != null && proxyCredential instanceof AbstractResourceSecurityWrapper) {
        AbstractResourceSecurityWrapper proxyWrapper = (AbstractResourceSecurityWrapper) proxyCredential;
        file = proxyWrapper.getFile();
    } else {
        // FIXME: should alias be file name? or generate?
        file = new File(defaultDirectory, s + "-key.pem");
    }
    try {
        wrapper = new ResourceProxyCredential(new FileSystemResource(file), credential);
    } catch (ResourceStoreException e) {
        throw new KeyStoreException(e);
    }
    return wrapper;
}

From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.java

private UrlSet buildUrlSet() throws IOException {
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(classLoaderInterface, this.fileProtocols);

    //excluding the urls found by the parent class loader is desired, but fails in JBoss (all urls are removed)
    if (excludeParentClassLoader) {
        //exclude parent of classloaders
        ClassLoaderInterface parent = classLoaderInterface.getParent();
        //if reload is enabled, we need to step up one level, otherwise the UrlSet will be empty
        //this happens because the parent of the realoding class loader is the web app classloader
        if (parent != null && isReloadEnabled())
            parent = parent.getParent();

        if (parent != null)
            urlSet = urlSet.exclude(parent);

        try {//from   w ww .  ja v a2 s .  c  om
            // This may fail in some sandboxes, ie GAE
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
            urlSet = urlSet.exclude(new ClassLoaderInterfaceDelegate(systemClassLoader.getParent()));

        } catch (SecurityException e) {
            if (LOG.isWarnEnabled())
                LOG.warn(
                        "Could not get the system classloader due to security constraints, there may be improper urls left to scan");
        }
    }

    //try to find classes dirs inside war files
    urlSet = urlSet.includeClassesUrl(classLoaderInterface);

    urlSet = urlSet.excludeJavaExtDirs();
    urlSet = urlSet.excludeJavaEndorsedDirs();
    try {
        urlSet = urlSet.excludeJavaHome();
    } catch (NullPointerException e) {
        // This happens in GAE since the sandbox contains no java.home directory
        if (LOG.isWarnEnabled())
            LOG.warn("Could not exclude JAVA_HOME, is this a sandbox jvm?");
    }
    urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", ""));
    urlSet = urlSet.exclude(".*/JavaVM.framework/.*");

    if (includeJars == null) {
        urlSet = urlSet.exclude(".*?\\.jar(!/|/)?");
    } else {
        Set<URL> includeUrls = new HashSet<URL>();
        boolean[] patternUsed = new boolean[includeJars.length];
        for (int i = 0; i < includeJars.length; i++) {
            try {
                String includeJar = includeJars[i];
                FileSystemResource resource = new FileSystemResource(FileUtils.getAbsolutePath(includeJar));
                includeUrls.add(resource.getURL());
                patternUsed[i] = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (LOG.isWarnEnabled()) {
            for (int i = 0; i < patternUsed.length; i++) {
                if (!patternUsed[i]) {
                    LOG.warn("The includeJars pattern [#0] did not match any jars in the classpath",
                            includeJars[i]);
                }
            }
        }
        return new UrlSet(includeUrls);
    }

    return urlSet;
}

From source file:org.globus.security.stores.PEMKeyStore.java

private CredentialWrapper createCertKeyCredential(String s, X509Credential credential)
        throws KeyStoreException {
    Resource certResource;/*from  w  w w. j a  v a2  s .c om*/
    Resource keyResource;
    CredentialWrapper wrapper;
    CredentialWrapper credentialWrapper = getKeyEntry(s);
    if (credentialWrapper != null && credentialWrapper instanceof CertKeyCredential) {
        CertKeyCredential certKeyCred = (CertKeyCredential) credentialWrapper;
        certResource = certKeyCred.getCertificateFile();
        keyResource = certKeyCred.getKeyFile();
    } else {
        certResource = new FileSystemResource(new File(defaultDirectory, s + ".0"));
        keyResource = new FileSystemResource(new File(defaultDirectory, s + "-key.pem"));
    }
    try {
        wrapper = new CertKeyCredential(certResource, keyResource, credential);
    } catch (ResourceStoreException e) {
        throw new KeyStoreException(e);
    }
    return wrapper;
}

From source file:com.gooddata.dataload.processes.ProcessService.java

private DataloadProcess postProcess(DataloadProcess process, File processData, URI postUri) {
    File tempFile = createTempFile("process", ".zip");

    try (FileOutputStream output = new FileOutputStream(tempFile)) {
        ZipHelper.zip(processData, output);
    } catch (IOException e) {
        throw new GoodDataException("Unable to zip process data", e);
    }/*from   ww w.j  a  v  a  2  s .  c  o m*/

    Object processToSend;
    HttpMethod method = HttpMethod.POST;
    if (tempFile.length() > MAX_MULTIPART_SIZE) {
        try {
            process.setPath(dataStoreService.getUri(tempFile.getName()).getPath());
            dataStoreService.upload(tempFile.getName(), new FileInputStream(tempFile));
            processToSend = process;
            if (DataloadProcess.TEMPLATE.matches(postUri.toString())) {
                method = HttpMethod.PUT;
            }
        } catch (FileNotFoundException e) {
            throw new GoodDataException("Unable to access zipped process data at " + tempFile.getAbsolutePath(),
                    e);
        }
    } else {
        final MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(2);
        parts.add("process", process);
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MEDIA_TYPE_ZIP);
        parts.add("data", new HttpEntity<>(new FileSystemResource(tempFile), headers));
        processToSend = parts;
    }

    try {
        final ResponseEntity<DataloadProcess> response = restTemplate.exchange(postUri, method,
                new HttpEntity<>(processToSend), DataloadProcess.class);
        if (response == null) {
            throw new GoodDataException("Unable to post dataload process. No response returned from API.");
        }
        return response.getBody();
    } catch (GoodDataException | RestClientException e) {
        throw new GoodDataException("Unable to post dataload process.", e);
    } finally {
        deleteTempFile(tempFile);
    }
}

From source file:com.wavemaker.studio.StudioService.java

@ExposeToClient
public FileUploadResponse uploadExtensionZip(MultipartFile file) {
    FileUploadResponse ret = new FileUploadResponse();
    java.io.File tmpDir;/*from  ww  w. ja  va2 s  .c  om*/
    try {
        java.io.File webapproot = new java.io.File(WMAppContext.getInstance().getAppContextRoot());

        String filename = file.getOriginalFilename();
        int dotindex = filename.lastIndexOf(".");
        String ext = dotindex == -1 ? "" : filename.substring(dotindex + 1);
        if (dotindex == -1) {
            throw new IOException("Please upload a zip file");
        } else if (!ext.equals("zip")) {
            throw new IOException("Please upload a zip file, not a " + ext + " file");
        }

        String originalName = file.getOriginalFilename();
        tmpDir = new java.io.File(webapproot, "tmp");
        com.wavemaker.common.util.IOUtils.makeDirectories(tmpDir, webapproot);

        java.io.File outputFile = new java.io.File(tmpDir, originalName);
        String newName = originalName.replaceAll("[ 0-9()]*.zip$", "");
        System.out.println("OLD NAME:" + originalName + "; NEW NAME:" + newName);
        FileOutputStream fos = new FileOutputStream(outputFile);
        com.wavemaker.common.util.IOUtils.copy(file.getInputStream(), fos);
        file.getInputStream().close();
        fos.close();
        java.io.File extFolder = com.wavemaker.tools.project.ResourceManager
                .unzipFile(this.fileSystem, new FileSystemResource(outputFile)).getFile();

        /*
         * Import the pages from the pages folder STATUS: DONE
         */
        java.io.File webapprootPages = new java.io.File(webapproot, "pages");
        java.io.File pagesFolder = new java.io.File(extFolder, "pages");
        java.io.File[] pages = pagesFolder.listFiles();
        for (int i = 0; i < pages.length; i++) {
            com.wavemaker.common.util.IOUtils.copy(pages[i],
                    new java.io.File(webapprootPages, pages[i].getName()));
        }

        /*
         * Import the language files from the dictionaries folder and subfolder STATUS: DONE
         */
        java.io.File dictionaryDest = new java.io.File(webapproot, "language/nls");
        java.io.File dictionarySrc = new java.io.File(extFolder, "language/nls");
        java.io.File[] languages = dictionarySrc.listFiles();
        for (int i = 0; i < languages.length; i++) {
            if (languages[i].isDirectory()) {
                System.out.println("GET LISTING OF " + languages[i].getName());
                java.io.File[] languages2 = languages[i].listFiles();
                for (int j = 0; j < languages2.length; j++) {
                    System.out.println("COPY " + languages2[j].getName() + " TO "
                            + new java.io.File(dictionaryDest, languages[i].getName()).getAbsolutePath());
                    com.wavemaker.common.util.IOUtils.copy(languages2[j],
                            new java.io.File(dictionaryDest, languages[i].getName()));
                }
            } else {
                com.wavemaker.common.util.IOUtils.copy(languages[i], dictionaryDest);
            }
        }

        /*
         * Import the designtime jars STATUS: DONE
         */
        java.io.File studioLib = new java.io.File(webapproot, "WEB-INF/lib");
        java.io.File designtimeFolder = new java.io.File(extFolder, "designtime");
        java.io.File[] designJars = designtimeFolder.listFiles();
        for (int i = 0; i < designJars.length; i++) {
            com.wavemaker.common.util.IOUtils.copy(designJars[i], studioLib);
        }

        /*
         * Import the runtime jars STATUS: DONE
         */
        java.io.File templatesPwsFolder = new java.io.File(webapproot, "app/templates/pws/" + newName);
        java.io.File templatesPwsWEBINFFolder = new java.io.File(templatesPwsFolder, "WEB-INF");
        java.io.File templatesPwsWEBINFLibFolder = new java.io.File(templatesPwsWEBINFFolder, "lib");
        /* Delete any old jars from prior imports */
        if (templatesPwsFolder.exists()) {
            com.wavemaker.common.util.IOUtils.deleteRecursive(templatesPwsFolder);
        }

        com.wavemaker.common.util.IOUtils.makeDirectories(templatesPwsWEBINFLibFolder, webapproot);

        java.io.File runtimeFolder = new java.io.File(extFolder, "runtime");
        java.io.File[] runJars = runtimeFolder.listFiles();
        for (int i = 0; i < runJars.length; i++) {
            com.wavemaker.common.util.IOUtils.copy(runJars[i], studioLib);
            com.wavemaker.common.util.IOUtils.copy(runJars[i], templatesPwsWEBINFLibFolder);
        }

        /*
         * Import packages.js
         */
        java.io.File packagesFile = new java.io.File(webapproot, "app/packages.js");
        String packagesExt = "";
        try {
            // Get the packages.js file from our extensions.zip file */
            packagesExt = com.wavemaker.common.util.IOUtils.read(new java.io.File(extFolder, "packages.js"));
        } catch (Exception e) {
            packagesExt = "";
        }
        /* If there is a packages file provided... */
        if (packagesExt.length() > 0) {
            /* Build the string we're appending to packages.js */
            String startPackagesExt = "/* START PARTNER " + newName + " */\n";
            String endPackagesExt = "/* END PARTNER " + newName + " */\n";
            packagesExt = ",\n" + startPackagesExt + packagesExt + "\n" + endPackagesExt;

            String packages = com.wavemaker.common.util.IOUtils.read(packagesFile);

            /* Remove previous packages entries for this partner */
            int packagesStartIndex = packages.indexOf(startPackagesExt);
            if (packagesStartIndex != -1) {
                packagesStartIndex = packages.lastIndexOf(",", packagesStartIndex);
                int packagesEndIndex = packages.indexOf(endPackagesExt);
                if (packagesEndIndex != -1) {
                    packagesEndIndex += endPackagesExt.length();
                    packages = packages.substring(0, packagesStartIndex) + packages.substring(packagesEndIndex);
                }
            }

            /* Append the string to packages.js and write it */
            packages += packagesExt;
            com.wavemaker.common.util.IOUtils.write(packagesFile, packages);
        }

        /*
         * Import spring config files STATUS: DONE
         */
        java.io.File webinf = new java.io.File(webapproot, "WEB-INF");
        java.io.File designxml = new java.io.File(extFolder, newName + "-tools-beans.xml");
        java.io.File runtimexml = new java.io.File(extFolder, newName + "-runtime-beans.xml");
        com.wavemaker.common.util.IOUtils.copy(designxml, webinf);
        com.wavemaker.common.util.IOUtils.copy(runtimexml, webinf);
        com.wavemaker.common.util.IOUtils.copy(runtimexml, templatesPwsWEBINFFolder);

        /*
         * Modify Spring files to include beans in the partner package.
         */
        java.io.File studioSpringApp = new java.io.File(webinf, "studio-springapp.xml");
        PwsInstall.insertImport(studioSpringApp, newName + "-tools-beans.xml");
        PwsInstall.insertImport(studioSpringApp, newName + "-runtime-beans.xml");

        java.io.File studioPartnerBeans = new java.io.File(webinf, "studio-partner-beans.xml");
        PwsInstall.insertEntryKey(studioPartnerBeans, runJars, designJars, newName);

        java.io.File templatesPwsRootFolder = new java.io.File(webapproot, "app/templates/pws/");
        java.io.File templatesPwsRootWEBINFFolder = new java.io.File(templatesPwsRootFolder, "WEB-INF");
        java.io.File projectSpringApp = new java.io.File(templatesPwsRootWEBINFFolder, "project-springapp.xml");
        PwsInstall.insertImport(projectSpringApp, newName + "-runtime-beans.xml");

        java.io.File projectPartnerBeans = new java.io.File(templatesPwsRootWEBINFFolder,
                "project-partner-beans.xml");
        PwsInstall.insertEntryKey(projectPartnerBeans, runJars, designJars, newName);

        ret.setPath("/tmp");
        ret.setError("");
        ret.setWidth("");
        ret.setHeight("");

    } catch (Exception e) {
        ret.setError(e.getMessage());
        return ret;
    }

    try {
        com.wavemaker.common.util.IOUtils.deleteRecursive(tmpDir);
    } catch (Exception e) {
        return ret;
    }
    return ret;
}

From source file:org.globus.security.stores.PEMKeyStore.java

/**
 * Add a certificate to the keystore./*from   ww  w . j a va2s .  co m*/
 * 
 * @param alias
 *            The certificate alias.
 * @param certificate
 *            The certificate to store.
 * @throws KeyStoreException
 */
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) throws KeyStoreException {

    if (!(certificate instanceof X509Certificate)) {
        throw new KeyStoreException("Certificate must be instance of X509Certificate");
    }
    File file;
    ResourceTrustAnchor trustAnchor = getCertificateEntry(alias);
    if (trustAnchor != null) {
        file = trustAnchor.getFile();
    } else {
        file = new File(defaultDirectory, alias);
    }
    X509Certificate x509Cert = (X509Certificate) certificate;
    try {
        writeCertificate(x509Cert, file);
        ResourceTrustAnchor anchor = new ResourceTrustAnchor(new FileSystemResource(file),
                new TrustAnchor(x509Cert, null));
        this.aliasObjectMap.put(alias, anchor);
        this.certFilenameMap.put(x509Cert, alias);
    } catch (ResourceStoreException e) {
        throw new KeyStoreException(e);
    } catch (IOException e) {
        throw new KeyStoreException(e);
    } catch (CertificateEncodingException e) {
        throw new KeyStoreException(e);
    }
}