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:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.utils.PentahoSystemHelper.java

private static ApplicationContext getSpringApplicationContext() {

    String[] fns = { "pentahoObjects.spring.xml", "adminPlugins.xml", "sessionStartupActions.xml",
            "systemListeners.xml", "pentahoSystemConfig.xml" }; //$NON-NLS-2$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$

    GenericApplicationContext appCtx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appCtx);

    for (String fn : fns) {
        File f = new File(getSolutionPath() + SYSTEM_FOLDER + "/" + fn); //$NON-NLS-1$
        if (f.exists()) {
            FileSystemResource fsr = new FileSystemResource(f);
            xmlReader.loadBeanDefinitions(fsr);
        }/* w w w  .  ja  va2s.  c  o  m*/
    }

    String[] beanNames = appCtx.getBeanDefinitionNames();
    System.out.println("Loaded Beans: "); //$NON-NLS-1$
    for (String n : beanNames) {
        System.out.println("bean: " + n); //$NON-NLS-1$
    }
    return appCtx;
}

From source file:org.apache.uima.ruta.resource.MultiTreeWordList.java

/**
 * @param lists/*from w ww  .  j  a va 2  s . com*/
 *          Resources to load.
 * @throws IOException
 *           When there is a problem reading a resource.
 */
public MultiTreeWordList(Resource... lists) throws IOException {
    this.root = new MultiTextNode();
    this.costMap = new EditDistanceCostMap();

    for (Resource list : lists) {
        // check if the resource is a directory
        File directory = null;
        try {
            directory = list.getFile();
        } catch (IOException e) {
            // resource is not on the file system
            directory = null;
        }

        if (directory != null && directory.isDirectory()) {
            // resource is a directory, load its content
            for (File data : directory.listFiles()) {
                load(new FileSystemResource(data));
            }
        } else {
            // resource is not a directory, load it normally
            load(list);
        }
    }
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

@Test
public void testWithAttachment() throws Exception {
    // Given:/*www.java2s  .  co m*/
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a test with a PDF attachment.";
    List<FileSystemResource> filesToAttach = new ArrayList<FileSystemResource>();
    filesToAttach.add(
            new FileSystemResource(this.getClass().getClassLoader().getResource("HelloWorld.pdf").getFile()));

    // When:
    service.sendWithAttachments(expectedTo, expectedSubject, expectedTextBody, filesToAttach);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());
    WiserMessage message = messages.get(0);
    MimeMessage mimeMessage = message.getMimeMessage();

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 2, body.getCount());

    MimeBodyPart attachment = ((MimeBodyPart) body.getBodyPart(1));
    assertTrue("Attachment MIME Type should be application/pdf", attachment.isMimeType("application/pdf"));
    assertEquals("Attachment filename;", "HelloWorld.pdf", attachment.getFileName());
    assertTrue("No content found in the attachment.", isNotBlank(attachment.getContent().toString()));
}

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

@Test
public void testZipTwoFile() throws Exception {
    FileUtils.forceMkdir(new File("target/Z-testfiles/source"));
    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"),
            new File("target/Z-testfiles/source/CP0-input.csv"));
    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"),
            new File("target/Z-testfiles/source/CP1-input.csv"));

    String aTargetFilename = "target/Z1-input.zip";
    ZipFilesTasklet aTasklet = new ZipFilesTasklet();
    aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/source/"));
    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();
    aSourceFactory.setPattern("file:target/Z-testfiles/source/*input*.csv");
    aTasklet.setSourceFactory(aSourceFactory);
    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();
    aDestinationFactory.setExpression(aTargetFilename);
    aTasklet.setDestinationFactory(aDestinationFactory);

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

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

    assertTrue(new File(aTargetFilename).exists());
    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));
    Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries();
    assertTrue(aEntries.hasMoreElements());
    assertEquals("CP0-input.csv", aEntries.nextElement().getName());
    assertTrue(aEntries.hasMoreElements());
    assertEquals("CP1-input.csv", aEntries.nextElement().getName());
    assertFalse(aEntries.hasMoreElements());
    aZipFile.close();/*from   ww  w  . j  a va2  s  . com*/
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateScenario.java

/**
 * Method, where scenario information is pushed to server in order to new scenario.
 * All heavy lifting is made here.//from   w ww.  j  ava2  s .c  o  m
 *
 * @param scenarios only one scenario is accepted - scenario to be uploaded
 * @return scenario stored
 */
@Override
protected Scenario doInBackground(Scenario... scenarios) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_SCENARIOS;

    setState(RUNNING, R.string.working_ws_create_scenario);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    //so files wont buffer in memory
    factory.setBufferRequestBody(false);
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    Scenario scenario = scenarios[0];

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(scenario.getFilePath());

        //due to multipart file, MultiValueMap is the simplest approach for performing the post request
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("scenarioName", scenario.getScenarioName());
        form.add("researchGroupId", scenario.getResearchGroupId());
        form.add("description", scenario.getDescription());
        form.add("mimeType", scenario.getMimeType());
        form.add("private", Boolean.toString(scenario.isPrivate()));
        form.add("file", toBeUploadedFile);

        HttpEntity<Object> entity = new HttpEntity<Object>(form, requestHeaders);
        // Make the network request
        ResponseEntity<Scenario> response = restTemplate.postForEntity(url, entity, Scenario.class);
        return response.getBody();
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:com.google.api.ads.adwords.awreporting.processors.onfile.ReportProcessorOnFileTest.java

@Before
public void setUp() throws InterruptedException, IOException, OAuthException, ValidationException {

    for (int i = 1; i <= NUMBER_OF_ACCOUNTS; i++) {
        CIDS.add(Long.valueOf(i));
    }//from w w w.ja  v a 2 s  .co  m

    Resource resource = new FileSystemResource("src/test/resources/aw-report-sample.properties");
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);
    properties = PropertiesLoaderUtils.loadProperties(resource);
    appCtx = new ClassPathXmlApplicationContext("classpath:aw-report-test-beans.xml");

    reportProcessorOnFile = new ReportProcessorOnFile(10, NUMBER_OF_THREADS);
    authenticator = new InstalledOAuth2Authenticator("DevToken", "ClientId", "ClientSecret",
            ReportWriterType.FileSystemWriter);

    MockitoAnnotations.initMocks(this);

    when(mockedAuthTokenPersister.getAuthToken(Mockito.anyString()))
            .thenReturn(new AuthMcc("1", "AccountName", "TOKEN", "scope"));

    Mockito.doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(mockedEntitiesPersister).persistReportEntities(Mockito.<List<? extends Report>>anyObject());

    mockDownloadReports(CIDS.size());

    reportProcessorOnFile.setMultipleClientReportDownloader(mockedMultipleClientReportDownloader);
    reportProcessorOnFile.setPersister(mockedEntitiesPersister);
    reportProcessorOnFile.setCsvReportEntitiesMapping(appCtx.getBean(CsvReportEntitiesMapping.class));
    reportProcessorOnFile.setAuthentication(authenticator);

    // Mocking the Authentication because in OAuth2 we are force to call buildOAuth2Credentials
    AdWordsSession.Builder builder = new AdWordsSession.Builder().withClientCustomerId("1");
    Mockito.doReturn(builder).when(authenticator).authenticate(Mockito.anyString(), Mockito.anyBoolean());
}

From source file:com.google.api.ads.adwords.jaxws.extensions.processors.onfile.ReportProcessorOnFileTest.java

@Before
public void setUp() throws InterruptedException, IOException, OAuthException, ValidationException {

    for (int i = 1; i <= NUMBER_OF_ACCOUNTS; i++) {
        CIDS.add(Long.valueOf(i));
    }//from w  w w .  ja  v  a  2s.  c  o  m

    Resource resource = new FileSystemResource("src/test/resources/aw-report-sample.properties");
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);
    properties = PropertiesLoaderUtils.loadProperties(resource);
    appCtx = new ClassPathXmlApplicationContext("classpath:aw-report-test-beans.xml");

    reportProcessorOnFile = new ReportProcessorOnFile(10, NUMBER_OF_THREADS);
    authenticator = new InstalledOAuth2Authenticator("DevToken", "ClientId", "ClientSecret",
            ReportWriterType.FileSystemWriter);

    MockitoAnnotations.initMocks(this);

    when(mockedAuthTokenPersister.getAuthToken(Mockito.anyString()))
            .thenReturn(new AuthMcc("1", "AccountName", "TOKEN", "scope"));

    Mockito.doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(mockedEntitiesPersister).persistReportEntities(Mockito.<List<? extends Report>>anyObject());

    mockDownloadReports(CIDS.size());

    reportProcessorOnFile.setMultipleClientReportDownloader(mockedMultipleClientReportDownloader);
    reportProcessorOnFile.setPersister(mockedEntitiesPersister);
    reportProcessorOnFile.setCsvReportEntitiesMapping(appCtx.getBean(CsvReportEntitiesMapping.class));
    reportProcessorOnFile.setAuthentication(authenticator);

    // Mocking the Authentication because in OAuth2 we are force to call buildOAuth2Credentials
    AdWordsSession.Builder builder = new AdWordsSession.Builder().withClientCustomerId("1");
    Mockito.doReturn(builder).when(authenticator).authenticate(Mockito.anyString(), Mockito.anyString(),
            Mockito.anyBoolean());
}

From source file:net.solarnetwork.node.backup.FileBackupResourceProvider.java

@Override
public Iterable<BackupResource> getBackupResources() {
    if (resourceDirectories == null || resourceDirectories.length < 1) {
        return Collections.emptyList();
    }/*from  w w w  . ja v  a2s  . c  om*/
    final Pattern pat = (fileNamePattern == null ? null
            : Pattern.compile(fileNamePattern, Pattern.CASE_INSENSITIVE));
    List<BackupResource> fileList = new ArrayList<BackupResource>(20);
    for (String path : resourceDirectories) {
        File rootDir = (rootPath != null && rootPath.length() > 0 ? new File(rootPath, path) : new File(path));
        if (!rootDir.isDirectory()) {
            log.info("Skipping path {} because does not exist or is not a directory",
                    rootDir.getAbsolutePath());
            continue;
        }
        File[] files = rootDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return pat.matcher(name).find();
            }
        });
        if (files == null || files.length < 1) {
            continue;
        }
        for (File f : files) {
            // make sure backup path is relative
            final String backupPath = path + '/' + f.getName();
            String digest = null;
            InputStream in = null;
            try {
                in = new BufferedInputStream(new FileInputStream(f));
                digest = DigestUtils.sha256Hex(in);
            } catch (IOException e) {
                log.warn("Error calculating SHA-256 digest of {}: {}", f, e.getMessage());
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }

            fileList.add(new ResourceBackupResource(new FileSystemResource(f), backupPath, getKey(), digest));
        }
    }
    return fileList;
}

From source file:coral.reef.web.ReefController.java

@RequestMapping(value = "/images/bg")
public void bg(HttpServletResponse httpResponse) throws IOException {
    Resource res = appContext.getResource("classpath:CORAL_bg.png");

    File f = res.getFile();//ww w  . ja  v  a2s.  c  om
    FileSystemResource fr = new FileSystemResource(f);
    String type = servletContext.getMimeType(f.getAbsolutePath());
    httpResponse.setContentType(type);

    IOUtils.copy(fr.getInputStream(), httpResponse.getOutputStream());
}

From source file:org.jahia.modules.modulemanager.rest.ModuleManagerResource.java

private Resource getUploadedFileAsResource(InputStream inputStream, String filename)
        throws InternalServerErrorException {

    File tempFile;//  w  ww .j  a  v  a 2s  .co  m
    try {
        tempFile = File.createTempFile(FilenameUtils.getBaseName(filename) + "-",
                "." + FilenameUtils.getExtension(filename), FileUtils.getTempDirectory());
        FileUtils.copyInputStreamToFile(inputStream, tempFile);
    } catch (IOException e) {
        log.error("Error copy uploaded stream to local temp file for " + filename, e);
        throw new InternalServerErrorException("Error while deploying bundle " + filename, e);
    }
    return new FileSystemResource(tempFile);
}