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.apache.niolex.commons.mail.EmailUtil.java

/**
 * Send an email.//from  w  w  w  .  j a  v a 2s  .c  om
 * ????
 *
 * @param from the email sender
 * @param tos the email receiver list
 * @param title the email title
 * @param text the email body
 * @param attachments a list of files attachments
 * @param priority priority from 1-5 the smaller is higher
 * @param isHtml is the text in HTML format or not
 * @param encoding the encoding of email, i.e. "GBK"?"UTF-8"
 * @throws MailException
 * @throws MessagingException
 */
public static void sendMail(String from, List<String> tos, String title, String text, List<File> attachments,
        String priority, boolean isHtml, String encoding) throws MailException, MessagingException {
    List<Pair<String, InputStreamSource>> att = null;
    if (attachments != null) {
        att = Lists.newArrayList();
        for (File file : attachments) {
            InputStreamSource source = new FileSystemResource(file);
            Pair<String, InputStreamSource> pair = Pair.create(file.getName(), source);
            att.add(pair);
        }
    }
    String[] toArr = null;
    if (tos != null) {
        toArr = tos.toArray(new String[tos.size()]);
    }
    sendMail(from, toArr, null, title, text, att, priority, isHtml, encoding);
}

From source file:net.bubble.common.utils.PropertiesUtil.java

/**
 * ?classpath?//  w w w . j av a  2 s .  c o  m
 * @param location 
 * @param locationKind ?LocationEnum
 * @return Properties ??
 * @throws CommonException ?
 */
public Properties loadProperties(String location, LocationEnum locationKind) throws CommonException {
    try {
        Resource resource = null;
        switch (locationKind) {
        case CLASSPATH:
            resource = new ClassPathResource(location);
            break;
        case FILESYSTEM:
            resource = new FileSystemResource(location);
            break;
        }
        return PropertiesLoaderUtils.loadProperties(resource);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new CommonException("Read property file has error !", e);
    }
}

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

/**
 * Include an attachment./*from   w  ww  .ja  va  2s . c  o  m*/
 *
 * @param attachmentFilename
 *            the filename in the email
 * @param fileName
 *            the path of the file
 * @return this
 */
public EmailBuilder addAttachmentFromFile(String attachmentFilename, String fileName) {
    attachments.add(new EmailAttachment(attachmentFilename, new FileSystemResource(fileName)));
    return this;
}

From source file:org.cloudfoundry.identity.batch.BootstrapTests.java

private GenericXmlApplicationContext getServletContext(String... resources) {

    String profiles = null;/*  ww w  . ja  v  a2 s  . c o m*/
    String[] resourcesToLoad = resources;
    if (!resources[0].endsWith(".xml")) {
        profiles = resources[0];
        resourcesToLoad = new String[resources.length - 1];
        System.arraycopy(resources, 1, resourcesToLoad, 0, resourcesToLoad.length);
    }

    GenericXmlApplicationContext context = new GenericXmlApplicationContext();
    context.load(resourcesToLoad);

    if (profiles != null) {
        context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles));
    }

    // Simulate what happens in the webapp when the YamlServletProfileInitializer kicks in
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(
            new Resource[] { new FileSystemResource("./src/test/resources/test/config/batch.yml") });
    context.getEnvironment().getPropertySources()
            .addLast(new PropertiesPropertySource("servletProperties", factory.getObject()));

    context.refresh();

    return context;

}

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

@Test
public void testZipFile() throws Exception {
    String aTargetFilename = "target/Z0-input.zip";
    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);

    assertFalse(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 ww w .  j a va2  s  .co  m
}

From source file:com.ogaclejapan.dotapk.controller.ApkApiController.java

@RequestMapping(value = "/{name:.+}", method = RequestMethod.GET)
public void download(@PathVariable String name, HttpServletResponse response) throws Exception {
    log.info("download: " + name);

    Resource file = new FileSystemResource(apkManager.getByName(name));
    response.setContentType("application/vnd.android.package-archive");
    response.setContentLength((int) FileUtils.sizeOf(file.getFile()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFile().getName() + "\"");
    FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());

}

From source file:org.opennms.tools.EventsGenerator.java

/**
 * Generate threshold events.//w  w  w.  java  2 s  .c o m
 *
 * @param onmsHome the OpenNMS home directory
 * @throws Exception the exception
 */
public void generateThresholdEvents(File onmsHome) throws Exception {
    File thresholdsFile = new File(onmsHome, "etc/thresholds.xml");
    if (!thresholdsFile.exists()) {
        throw new FileNotFoundException(thresholdsFile.getAbsolutePath());
    }
    ThresholdingConfig thresholdsConfig = CastorUtils.unmarshal(ThresholdingConfig.class,
            new FileSystemResource(thresholdsFile), true);

    File graphTemplatesFile = new File(onmsHome, "etc/snmp-graph.properties");
    if (!graphTemplatesFile.exists()) {
        throw new FileNotFoundException(graphTemplatesFile.getAbsolutePath());
    }
    PropertiesGraphDao graphDao = new PropertiesGraphDao();
    graphDao.loadProperties("performance", new FileSystemResource(graphTemplatesFile));

    Events events = eventProcessor.getEvents(thresholdsConfig.getGroupCollection(),
            graphDao.getAllPrefabGraphs());
    File eventFile = new File(onmsHome, "etc/events/" + EVENTS_FILENAME);
    System.out.println("Generating " + eventFile);
    JaxbUtils.marshal(events, new FileWriter(eventFile));
}

From source file:org.trpr.platform.integration.impl.email.SpringMailSender.java

/**
 * Interface method implementation. Sends an email using the specified values and the configured mail sender.
 * @see org.trpr.platform.integration.spi.email.MailSender#sendMail(java.lang.String, java.lang.String[], java.lang.String, java.net.URL)
 *///w  w  w.j a v a 2  s.c  o  m
public void sendMail(final String senderAddress, final String subject, final String[] recipients,
        final String message, final URL attachmentURL) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            InternetAddress[] recipientAddresses = new InternetAddress[recipients.length];
            for (int i = 0; i < recipientAddresses.length; i++) {
                recipientAddresses[i] = new InternetAddress(recipients[i]);
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, recipientAddresses);
            mimeMessage.setFrom(new InternetAddress(senderAddress));
            mimeMessage.setSubject(subject);
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); // multi-part flag is set to true for accommodating attachments
            if (attachmentURL != null) {
                helper.addAttachment(attachmentURL.getFile(), new FileSystemResource(attachmentURL.toString()));
            }
            helper.setText(message);
        }
    };
    this.mailSender.send(preparator);
}

From source file:com.textocat.textokit.commons.cpe.XmiFileListReader.java

@Override
protected Iterable<Resource> getResources(UimaContext ctx) throws IOException {
    String baseDirPath = this.baseDirPath;
    baseDirPath = FilenameUtils.normalize(baseDirPath);
    // ensure that baseDirPath ends with slash for proper relative path handling
    if (!baseDirPath.endsWith(File.separator)) {
        baseDirPath += File.separator;
    }//from w w  w .ja v  a  2s.  c  o m
    baseDir = new FileSystemResource(baseDirPath);
    if (!baseDir.exists()) {
        throw new IllegalStateException(String.format("Directory %s does not exist", baseDir));
    }
    List<String> lines = FileUtils.readLines(listFile, "utf-8");
    resources = Lists.transform(Lists.newArrayList(Iterables.filter(lines, notBlankString)),
            relativeFileResourceFunc);
    return resources;
}

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

@Test(expected = FileOperationException.class)
public void testExecuteCopyFileNotFound() throws Exception {
    FileOperationTasklet aTasklet = new FileOperationTasklet();
    aTasklet.setOrigin(new FileSystemResource("src/test/resources/testFiles/notfound.csv"));
    aTasklet.setDestination(new FileSystemResource("target/input-copy.csv"));
    aTasklet.setOperation(Operation.COPY);
    aTasklet.afterPropertiesSet();// www .  j a  v  a2  s  .  c  o m
    StepContribution aStepContribution = mock(StepContribution.class);
    aTasklet.execute(aStepContribution, null);
    verify(aStepContribution, times(0)).incrementReadCount();
    verify(aStepContribution, times(0)).incrementWriteCount(1);
}