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.google.api.ads.adwords.awreporting.AwReporting.java

/**
 * Initialize the application context, adding the properties configuration file depending on the
 * specified path./*from w ww  . java 2  s . c o  m*/
 *
 * @param propertiesPath the path to the file.
 * @param forceOnFileProcessor true if the processor will be created to run "on file"
 * @return the resource loaded from the properties file.
 * @throws IOException error opening the properties file.
 */
private static Properties initApplicationContextAndProperties(String propertiesPath,
        boolean forceOnFileProcessor) throws IOException {

    Resource resource = new ClassPathResource(propertiesPath);
    if (!resource.exists()) {
        resource = new FileSystemResource(propertiesPath);
    }
    LOGGER.trace("Innitializing Spring application context.");
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);

    // Selecting the XMLs to choose the Spring Beans to load.
    List<String> listOfClassPathXml = Lists.newArrayList();

    // Choose the DB type to use based properties file, default to MYSQL
    String dbType = (String) properties.get(AW_REPORT_MODEL_DB_TYPE);
    DataBaseType sqldbType = null;
    if (DataBaseType.MONGODB.name().equals(dbType)) {
        LOGGER.info("Using MONGO DB configuration properties.");
        listOfClassPathXml.add("classpath:aw-report-mongodb-beans.xml");
    } else {
        if (DataBaseType.MSSQL.name().equals(dbType)) {
            sqldbType = DataBaseType.MSSQL;
            LOGGER.info("Using MSSQL DB configuration properties.");
        } else {
            // default to MYSQL
            sqldbType = DataBaseType.MYSQL;
            LOGGER.info("Using MYSQL DB configuration properties.");
        }
        LOGGER.warn("Updating database schema, this could take a few minutes ...");
        listOfClassPathXml.add("classpath:aw-report-sql-beans.xml");
        LOGGER.warn("Done.");
    }

    // Choose the Processor type to use based properties file
    String processorType = (String) properties.get(AW_REPORT_PROCESSOR_TYPE);
    if (!forceOnFileProcessor && ProcessorType.ONMEMORY.name().equals(processorType)) {
        LOGGER.info("Using ONMEMORY Processor.");
        listOfClassPathXml.add("classpath:aw-report-processor-beans-onmemory.xml");
    } else {
        LOGGER.info("Using ONFILE Processor.");
        listOfClassPathXml.add("classpath:aw-report-processor-beans-onfile.xml");
    }

    appCtx = new ClassPathXmlApplicationContext();
    if (sqldbType != null) {
        appCtx.getEnvironment().setActiveProfiles(sqldbType.name());
    }

    appCtx.setConfigLocations(listOfClassPathXml.toArray(new String[listOfClassPathXml.size()]));
    appCtx.refresh();

    return properties;
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/data/{id:[0-9]+}", method = RequestMethod.GET)
@ResponseBody/* w w w . j a v  a2s. c  o  m*/
public ResponseEntity<FileSystemResource> downloadImage(@PathVariable("id") int id) {
    Image img = imageRepository.findOne(id);
    if (img == null)
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "image not found");
    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType(MediaType.parseMediaType(img.getContentType()));
    respHeaders.setContentLength(img.getFileSize());
    respHeaders.setContentDispositionFormData("attachment", img.getFileName());

    Optional<File> f = getImageRepository().getImageFile(img.getId());
    if (f.isPresent()) {
        log.info("fichier pour image no " + id + " trouv");
        FileSystemResource fsr = new FileSystemResource(f.get());
        return new ResponseEntity<FileSystemResource>(fsr, respHeaders, HttpStatus.OK);
    } else {
        log.info("fichier pour image no " + id + " introuvable");
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "image file not found");
    }
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public Resource getParent(Resource resource) {
    File f;/*from   w  ww  .  j a  v a2s  .  c om*/
    try {
        f = resource.getFile().getParentFile();
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }

    Resource parent = null;

    if (f != null) {
        String path = f.getAbsolutePath() + "/";
        parent = new FileSystemResource(path);
    }

    return parent;
}

From source file:annis.administration.DefaultAdministrationDao.java

private void bulkImportNode(String path) {
    BufferedReader reader = null;
    try {/*  ww w. j ava 2  s .c  o m*/
        // check column number by reading first line
        File nodeTabFile = new File(path, "node.tab");

        reader = new BufferedReader(new InputStreamReader(new FileInputStream(nodeTabFile), "UTF-8"));
        String firstLine = reader.readLine();

        int columnNumber = firstLine == null ? 13 : StringUtils.splitPreserveAllTokens(firstLine, '\t').length;
        if (columnNumber == 13) {
            // new node table with segmentations
            // no special handling needed
            bulkloadTableFromResource(tableInStagingArea("node"), new FileSystemResource(nodeTabFile));
        } else if (columnNumber == 10) {
            // old node table without segmentations
            // create temporary table for bulk import
            jdbcTemplate.execute("CREATE TEMPORARY TABLE _tmpnode" + "\n(\n" + "id bigint,\n"
                    + "text_ref integer,\n" + "corpus_ref integer,\n" + "namespace varchar(100),\n"
                    + "name varchar(100),\n" + "\"left\" integer,\n" + "\"right\" integer,\n"
                    + "token_index integer,\n" + "continuous boolean,\n" + "span varchar(2000)\n" + ");");

            bulkloadTableFromResource("_tmpnode", new FileSystemResource(nodeTabFile));

            log.info("copying nodes from temporary helper table into staging area");
            jdbcTemplate.execute("INSERT INTO " + tableInStagingArea("node") + "\n"
                    + " SELECT id, text_ref, corpus_ref, namespace, name, \"left\", "
                    + "\"right\", token_index, " + "NULL AS seg_name, NULL AS seg_left, NULL AS seg_right, "
                    + "continuous, span\n" + "FROM _tmpnode");
        } else {
            throw new RuntimeException(
                    "Illegal number of columns in node.tab, " + "should be 13 or 10 but was " + columnNumber);
        }
    } catch (IOException ex) {
        log.error(null, ex);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                log.error(null, ex);
            }
        }
    }
}

From source file:fr.acxio.tools.agia.tasks.ZipFilesTaskletTest.java

@Test
public void testExistingLockedZipFile() throws Exception {
    exception.expect(IOException.class);
    File aTargetFile = File.createTempFile("target/Z9-input", ".zip");
    aTargetFile.setWritable(false);/*  w ww.j a va  2  s . c  o m*/
    String aTargetFilename = aTargetFile.getAbsolutePath();

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();
    aTasklet.setSourceBaseDirectory(new FileSystemResource("src/test/resources/testFiles/"));
    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();
    aSourceFactory.setPattern("file:src/test/resources/testFiles/input.csv");
    aTasklet.setSourceFactory(aSourceFactory);
    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();
    aDestinationFactory.setExpression(aTargetFilename);
    aTasklet.setDestinationFactory(aDestinationFactory);

    assertTrue(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));
    verify(aStepContribution, times(1)).incrementReadCount();
    verify(aStepContribution, times(1)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());
    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));
    Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries();
    assertTrue(aEntries.hasMoreElements());
    assertEquals("input.csv", aEntries.nextElement().getName());
    assertFalse(aEntries.hasMoreElements());
    aZipFile.close();
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/thumbdata/{id:[0-9]+}", method = RequestMethod.GET)
@ResponseBody/*from   w ww  .  j a  v  a 2s. c o  m*/
public ResponseEntity<FileSystemResource> downloadThumbImage(@PathVariable("id") int id) {
    Image img = imageRepository.findOne(id);
    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType(MediaType.parseMediaType("image/jpeg"));
    respHeaders.setContentDispositionFormData("attachment", "thumb_" + id + ".jpeg");

    Optional<File> f = getImageRepository().getImageThumbFile(img.getId());
    if (f.isPresent()) {
        log.info("fichier pour thumbnail image no " + id + " trouv");
        FileSystemResource fsr = new FileSystemResource(f.get());
        return new ResponseEntity<FileSystemResource>(fsr, respHeaders, HttpStatus.OK);
    } else {
        log.info("fichier pour thumbnail image no " + id + " introuvable");
        return new ResponseEntity<FileSystemResource>(HttpStatus.NOT_FOUND);
    }
}

From source file:com.consol.citrus.admin.service.TestCaseService.java

private ClassLoader getTestClassLoader(Project project) throws IOException {
    List<URL> classpathUrls = new ArrayList<>();

    classpathUrls.add(new FileSystemResource(
            project.getProjectHome() + File.separator + "target" + File.separator + "classes").getURL());
    classpathUrls.add(new FileSystemResource(
            project.getProjectHome() + File.separator + "target" + File.separator + "test-classes").getURL());

    File[] mavenDependencies = Maven.configureResolver().workOffline()
            .loadPomFromFile(project.getMavenPomFile()).importRuntimeAndTestDependencies().resolve()
            .withTransitivity().asFile();

    for (File mavenDependency : mavenDependencies) {
        classpathUrls.add(new FileSystemResource(mavenDependency).getURL());
    }/*www . jav  a 2s . com*/

    return URLClassLoader.newInstance(classpathUrls.toArray(new URL[classpathUrls.size()]));
}

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

/**
 * Initialize the application context, adding the properties configuration file depending on the
 * specified path.//w w  w .  java2s .  co m
 * @throws IOException 
 */
public void initApplicationContextAndProperties(String propertiesFilePath) throws IOException {

    Resource resource = new ClassPathResource(propertiesFilePath);
    if (!resource.exists()) {
        resource = new FileSystemResource(propertiesFilePath);
    }
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);
    properties = PropertiesLoaderUtils.loadProperties(resource);

    // Set the server port from the properties file or use 8081 as default. 
    String strServerPort = properties.getProperty("serverport");
    if (strServerPort != null && strServerPort.length() > 0) {
        serverPort = Integer.valueOf(strServerPort);
    }

    listOfClassPathXml.add("classpath:storage-helper-beans.xml");

    listOfClassPathXml.add("classpath:kratu-processor-beans.xml");

    listOfClassPathXml.add("aw-reporting-server-webauthenticator.xml");

    listOfClassPathXml.add("aw-pdf-exporter-beans.xml");

    // Choose the DB type to use based properties file
    String dbType = (String) properties.get(AW_REPORT_MODEL_DB_TYPE);
    if (dbType != null && dbType.equals(DataBaseType.MONGODB.name())) {
        logger.info("Using MONGO DB configuration properties.");
        listOfClassPathXml.add("classpath:aw-report-mongodb-beans.xml");
    } else {
        logger.info("Using SQL DB configuration properties.");
        listOfClassPathXml.add("classpath:aw-report-sql-beans.xml");
    }

    // Choose the Processor type to use based properties file
    String processorType = (String) properties.get(AW_REPORT_PROCESSOR_TYPE);
    if (processorType != null && processorType.equals(ProcessorType.ONMEMORY.name())) {
        logger.info("Using ONMEMORY Processor.");
        listOfClassPathXml.add("classpath:aw-report-processor-beans-onmemory.xml");
    } else {
        logger.info("Using ONFILE Processor.");
        listOfClassPathXml.add("classpath:aw-report-processor-beans-onfile.xml");
    }

    appCtx = new ClassPathXmlApplicationContext(
            listOfClassPathXml.toArray(new String[listOfClassPathXml.size()]));
    persister = appCtx.getBean(EntityPersister.class);
    storageHelper = appCtx.getBean(StorageHelper.class);
    webAuthenticator = appCtx.getBean(WebAuthenticator.class);
}

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

private ModuleInstallationResult installModule(File file, MessageContext context, List<String> providedBundles,
        Map<Bundle, MessageResolver> collectedResolutionErrors, boolean forceUpdate, boolean autoStart)
        throws IOException, BundleException {

    JarFile jarFile = new JarFile(file);
    try {/*from w w  w .j  a  va  2 s.c  o m*/

        Manifest manifest = jarFile.getManifest();
        String symbolicName = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_BUNDLE_SYMBOLIC_NAME);
        if (symbolicName == null) {
            symbolicName = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_ROOT_FOLDER);
        }
        String version = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_IMPL_VERSION);
        String groupId = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_GROUP_ID);
        if (templateManagerService.differentModuleWithSameIdExists(symbolicName, groupId)) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.install.moduleWithSameIdExists").arg(symbolicName)
                    .error().build());
            return null;
        }
        ModuleVersion moduleVersion = new ModuleVersion(version);
        Set<ModuleVersion> allVersions = templatePackageRegistry.getAvailableVersionsForModule(symbolicName);
        if (!forceUpdate) {
            if (!moduleVersion.isSnapshot()) {
                if (allVersions.contains(moduleVersion)) {
                    context.addMessage(new MessageBuilder().source("moduleExists")
                            .code("serverSettings.manageModules.install.moduleExists")
                            .args(symbolicName, version).build());
                    return null;
                }
            }
        }

        String successMessage = (autoStart ? "serverSettings.manageModules.install.uploadedAndStarted"
                : "serverSettings.manageModules.install.uploaded");
        String resolutionError = null;

        boolean shouldAutoStart = autoStart;
        if (autoStart && !Boolean.valueOf(SettingsBean.getInstance().getPropertiesFile()
                .getProperty("org.jahia.modules.autoStartOlderVersions"))) {
            // verify that a newer version is not active already
            JahiaTemplatesPackage currentActivePackage = templateManagerService.getTemplatePackageRegistry()
                    .lookupById(symbolicName);
            ModuleVersion currentVersion = currentActivePackage != null ? currentActivePackage.getVersion()
                    : null;
            if (currentActivePackage != null && moduleVersion.compareTo(currentVersion) < 0) {
                // we do not start the uploaded older version automatically
                shouldAutoStart = false;
                successMessage = "serverSettings.manageModules.install.uploadedNotStartedDueToNewerVersionActive";
            }
        }

        try {
            moduleManager.install(new FileSystemResource(file), null, shouldAutoStart);
        } catch (ModuleManagementException e) {
            Throwable cause = e.getCause();
            if (cause != null && cause instanceof BundleException
                    && ((BundleException) cause).getType() == BundleException.RESOLVE_ERROR) {
                // we are dealing with unresolved dependencies here
                resolutionError = cause.getMessage();
            } else {
                // re-throw the exception
                throw e;
            }
        }

        Bundle bundle = BundleUtils.getBundle(symbolicName, version);

        JahiaTemplatesPackage module = BundleUtils.getModule(bundle);

        if (module.getState().getState() == ModuleState.State.WAITING_TO_BE_IMPORTED) {
            // This only can happen in a cluster.
            successMessage = "serverSettings.manageModules.install.waitingToBeImported";
        }

        if (resolutionError != null) {
            List<String> missingDeps = getMissingDependenciesFrom(module.getDepends(), providedBundles);
            if (!missingDeps.isEmpty()) {
                createMessageForMissingDependencies(context, missingDeps);
            } else {
                MessageResolver errorMessage = new MessageBuilder().source("moduleFile")
                        .code("serverSettings.manageModules.resolutionError").arg(resolutionError).error()
                        .build();
                if (collectedResolutionErrors != null) {
                    // we just collect the resolution errors for multiple module to double-check them after all modules are installed
                    collectedResolutionErrors.put(bundle, errorMessage);
                    return new ModuleInstallationResult(bundle, successMessage);
                } else {
                    // we directly add error message
                    context.addMessage(errorMessage);
                }
            }
        } else if (module.getState().getState() == ModuleState.State.ERROR_WITH_DEFINITIONS) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.errorWithDefinitions")
                    .arg(((Exception) module.getState().getDetails()).getCause().getMessage()).error().build());
        } else {
            return new ModuleInstallationResult(bundle, successMessage);
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }

    return null;
}