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.processors.onmemory.ReportProcessorOnMemoryTest.java

@SuppressWarnings("unchecked")
@Before/*from w w w.jav a 2 s .c o  m*/
public void setUp() throws IOException, OAuthException {

    for (int i = 1; i <= NUMBER_OF_ACCOUNTS; i++) {
        CIDS.add(Long.valueOf(i));
    }

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

    reportProcessorOnMemory = new ReportProcessorOnMemory(2, NUMBER_OF_THREADS);

    authenticator = new InstalledOAuth2Authenticator("DevToken", "ClientId", "ClientSecret",
            ReportWriterType.FileSystemWriter);

    MockitoAnnotations.initMocks(this);

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

    reportProcessorOnMemory.setCsvReportEntitiesMapping(appCtx.getBean(CsvReportEntitiesMapping.class));
    reportProcessorOnMemory.setAuthentication(authenticator);
    reportProcessorOnMemory.setPersister(mockedEntitiesPersister);

    // Mocking the Authentication because in OAuth2 we are force to call buildOAuth2Credentials
    AdWordsSession.Builder builder = new AdWordsSession.Builder().withEndpoint("http://www.google.com")
            .withDeveloperToken("DeveloperToken").withClientCustomerId("123").withUserAgent("UserAgent")
            .withOAuth2Credential(new GoogleCredential.Builder().build());

    doReturn(builder).when(authenticator).authenticate(Mockito.anyString(), Mockito.anyBoolean());

    // Modifying ReportProcessorOnMemory to use the Mocked objects and avoid calling the real API 
    doAnswer(new Answer<RunnableProcessorOnMemory<Report>>() {
        @Override
        public RunnableProcessorOnMemory<Report> answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();

            RunnableProcessorOnMemory<Report> runnableProcessorOnMemory = Mockito
                    .spy((RunnableProcessorOnMemory<Report>) args[0]);

            doAnswer(new Answer<ByteArrayInputStream>() {
                @Override
                public ByteArrayInputStream answer(InvocationOnMock invocation) throws Throwable {

                    RunnableProcessorOnMemory<Report> rr = (RunnableProcessorOnMemory<Report>) invocation
                            .getMock();

                    byte[] reportData = getReporDatafromCsv(rr.getReportDefinition().getReportType());

                    return new ByteArrayInputStream(reportData);
                }
            }).when(runnableProcessorOnMemory).getReportInputStream();

            runnableProcessorOnMemoryList.add(runnableProcessorOnMemory);
            return runnableProcessorOnMemory;
        }
    }).when(reportProcessorOnMemory).getRunnableProcessorOnMemory(Mockito.any(RunnableProcessorOnMemory.class));
}

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

static Resource initBaseDir() {
    ClassPathResource classPath = new ClassPathResource("");
    try {//from   ww  w.  j  ava2 s .c om
        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.github.cherimojava.orchidae.config.WebMvcConfig.java

@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setLocation(new FileSystemResource(new File("./application.properties")));
    return configurer;
}

From source file:com.foilen.smalltools.email.EmailBuilder.java

/**
 * Include an inline attachment. Used with images.
 *
 * @param contentId//from ww  w.j a v  a 2s . c  o  m
 *            the content id to use. This is the "Content-ID" header in the body part. Can be used in HTML source with src="cid:theId"
 * @param fileName
 *            the path of the file
 * @return this
 */
public EmailBuilder addInlineAttachmentFromFile(String contentId, String fileName) {
    inlineAttachments.add(new EmailAttachment(contentId, new FileSystemResource(fileName)));
    return this;
}

From source file:de.langmi.spring.batch.examples.readers.support.CompositeItemStreamReaderTest.java

/**
 * Helpermethod to create FlatFileItemReader, sets the name too, to make restart
 * scenario possible - otherwise one flatFileItemReader would overwrite the 
 * other (in context)./*  ww  w.  ja  v a  2s  . c  om*/
 *
 * @param inputFile
 * @return configured FlatFileItemReader cast as ItemStreamReader
 */
private ItemStreamReader<String> createFlatFileItemReader(final String inputFile) {
    FlatFileItemReader<String> ffir = new FlatFileItemReader<String>();
    // init reader
    ffir.setLineMapper(new PassThroughLineMapper());
    ffir.setResource(new FileSystemResource(inputFile));
    ffir.setName(inputFile);

    return (ItemStreamReader<String>) ffir;
}

From source file:org.opentides.eventhandler.EmailHandler.java

public void sendEmail(String[] to, String[] cc, String[] bcc, String replyTo, String subject, String body,
        File[] attachments) {//  w  w  w  .ja v a  2s  .  co  m
    try {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(toInetAddress(to));
        InternetAddress[] ccAddresses = toInetAddress(cc);
        if (ccAddresses != null)
            mimeMessageHelper.setCc(ccAddresses);
        InternetAddress[] bccAddresses = toInetAddress(bcc);
        if (bccAddresses != null)
            mimeMessageHelper.setBcc(bccAddresses);
        if (!StringUtil.isEmpty(replyTo))
            mimeMessageHelper.setReplyTo(replyTo);
        Map<String, Object> templateVariables = new HashMap<String, Object>();

        templateVariables.put("message-title", subject);
        templateVariables.put("message-body", body);

        StringWriter writer = new StringWriter();
        VelocityEngineUtils.mergeTemplate(velocityEngine, mailVmTemplate, "UTF-8", templateVariables, writer);

        mimeMessageHelper.setFrom(new InternetAddress(this.fromEmail, this.fromName));
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(writer.toString(), true);

        // check for attachment
        if (attachments != null && attachments.length > 0) {
            for (File attachment : attachments) {
                mimeMessageHelper.addAttachment(attachment.getName(), attachment);
            }
        }

        /**
         * The name of the identifier should be image
         * the number after the image name is the counter 
         * e.g. <img src="cid:image1" />
         */
        if (imagesPath != null && imagesPath.size() > 0) {
            int x = 1;
            for (String path : imagesPath) {
                FileSystemResource res = new FileSystemResource(new File(path));
                String imageName = "image" + x;
                mimeMessageHelper.addInline(imageName, res);
                x++;
            }
        }
        javaMailSender.send(mimeMessage);
    } catch (MessagingException e) {
        _log.error(e, e);
    } catch (UnsupportedEncodingException uee) {
        _log.error(uee, uee);
    }
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.restapi.PublisherController.java

@ApiOperation(value = "Exposes H2O scoring engine model for download as JAR file", notes = "Privilege level: Any consumer of this endpoint must have a valid access token")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = FileSystemResource.class),
        @ApiResponse(code = 400, message = "Request was malformed"),
        @ApiResponse(code = 500, message = "Internal server error, e.g. error building or publishing model") })
@RequestMapping(method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded", value = "/rest/h2o/engines/{modelName}/downloads", produces = "application/java-archive")
@ResponseBody/*  ww w .j ava  2  s .  co  m*/
public FileSystemResource downloadEngine(@Valid @RequestBody MultiValueMap<String, String> request,
        @PathVariable String modelName) throws EngineBuildingException, ValidationException {

    LOGGER.info("Got download request: " + request + " modelName:" + modelName);
    validationRules.forEach(rule -> rule.validate(request));

    BasicAuthServerCredentials h2oServerCredentials = new BasicAuthServerCredentials(request.get("host").get(0),
            request.get("username").get(0), request.get("password").get(0));

    return new FileSystemResource(publisher.getScoringEngineJar(h2oServerCredentials, modelName).toFile());
}

From source file:net.jakubholy.jeeutils.jsfelcheck.beanfinder.SpringContextBeanFinder.java

private Resource[] toResources(Collection<InputResource> resourceFiles) {
    Resource[] locations = new Resource[resourceFiles.size()];

    int index = 0;
    for (InputResource configFile : resourceFiles) {
        if (configFile.getFileIfAvailable() != null) {
            locations[index++] = new FileSystemResource(configFile.getFileIfAvailable());
        } else {//w w  w.ja  v  a  2s  .  c  o  m
            locations[index++] = new InputStreamResource(configFile.getStream());
        }
    }

    return locations;
}

From source file:co.paralleluniverse.galaxy.Grid.java

private Grid(String configFile, Object properties) throws InterruptedException {
    if (configFile == null)
        configFile = System.getProperty("co.paralleluniverse.galaxy.configFile");
    if (properties == null)
        properties = System.getProperty("co.paralleluniverse.galaxy.propertiesFile");
    this.context = SpringContainerHelper.createContext("co.paralleluniverse.galaxy",
            configFile != null ? new FileSystemResource(configFile) : new ClassPathResource("galaxy.xml"),
            properties instanceof String ? new FileSystemResource((String) properties) : properties,
            new BeanFactoryPostProcessor() {
                @Override/*from   ww w.j  av a  2  s .com*/
                public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory1)
                        throws BeansException {
                    final DefaultListableBeanFactory beanFactory = ((DefaultListableBeanFactory) beanFactory1);

                    // messenger
                    //                        BeanDefinition messengerBeanDefinition = SpringContainerHelper.defineBean(
                    //                                MessengerImpl.class,
                    //                                SpringContainerHelper.constructorArgs("messenger", new RuntimeBeanReference("cache")),
                    //                                null);
                    //                        messengerBeanDefinition.setDependsOn(new String[]{"cache"});
                    //                        beanFactory.registerBeanDefinition("messenger", messengerBeanDefinition);

                    //beanFactory.registerSingleton(name, object);
                }
            });
    this.cluster = context.getBean("cluster", Cluster.class);
    this.clusterMonitor = new ClusterMonitor(cluster);

    this.backup = context.getBean("backup", Backup.class);

    this.cache = context.getBean("cache", Cache.class);
    this.store = new StoreImpl(cache);
    this.messenger = context.getBean("messenger", Messenger.class); // new MessengerImpl(cache);
}