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.sfs.dao.EmailMessageDAOImpl.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param emailMessage the email message
 *
 * @throws SFSDaoException the SFS dao exception
 *///from   www  .  ja  v  a2 s  .c  o m
public final void send(final EmailMessageBean emailMessage) throws SFSDaoException {

    // Check to see whether the required fields are set (to, from, message)
    if (StringUtils.isBlank(emailMessage.getTo())) {
        throw new SFSDaoException("Error recording email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(emailMessage.getFrom())) {
        throw new SFSDaoException("Error recording email: Email requires " + "a return address");
    }
    if (StringUtils.isBlank(emailMessage.getMessage())) {
        throw new SFSDaoException("Error recording email: No email " + "message specified");
    }
    if (javaMailSender == null) {
        throw new SFSDaoException("The EmailMessageDAO has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    if (emailMessage.getHtmlMessage()) {
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new SFSDaoException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }
    if (helper == null) {
        throw new SFSDaoException("The MimeMessageHelper cannot be null");
    }
    try {
        if (StringUtils.isNotBlank(emailMessage.getTo())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getTo(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addTo(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getCC())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getCC(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addCc(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getBCC())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getBCC(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addBcc(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getFrom())) {
            if (StringUtils.isNotBlank(emailMessage.getFromName())) {
                try {
                    helper.setFrom(emailMessage.getFrom(), emailMessage.getFromName());
                } catch (UnsupportedEncodingException uee) {
                    dataLogger.error("Error setting email from", uee);
                }
            } else {
                helper.setFrom(emailMessage.getFrom());
            }
        }
        helper.setSubject(emailMessage.getSubject());
        helper.setPriority(emailMessage.getPriority());
        if (emailMessage.getHtmlMessage()) {
            final String htmlText = emailMessage.getMessage();
            String plainText = htmlText;
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(htmlText);
            } catch (Exception e) {
                dataLogger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, htmlText);
        } else {
            helper.setText(emailMessage.getMessage());
        }
        helper.setSentDate(emailMessage.getSentDate());

    } catch (MessagingException me) {
        throw new SFSDaoException("Error preparing email for sending: " + me.getMessage());
    }

    // Append any attachments (if an HTML email)
    if (emailMessage.getHtmlMessage()) {
        for (String id : emailMessage.getAttachments().keySet()) {
            final Object reference = emailMessage.getAttachments().get(id);

            if (reference instanceof File) {
                try {
                    FileSystemResource res = new FileSystemResource((File) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    dataLogger.error("Error appending File attachment: " + me.getMessage());
                }
            }
            if (reference instanceof URL) {
                try {
                    UrlResource res = new UrlResource((URL) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    dataLogger.error("Error appending URL attachment: " + me.getMessage());
                }
            }
        }
    }

    // If not in debug mode send the email
    if (!debugMode) {
        deliver(emailMessage, message);
    }
}

From source file:de.codesourcery.spring.contextrewrite.RewriteConfig.java

/**
 * Returns a Spring <code>Resource</code> that can be used to retrieve the XML that should be rewritten.
 *  //from  www  .ja va2  s.  c o  m
 * @return
 * @throws IllegalStateException if neither this configuration nor any of its parents has a non-blank context path.
 */
public Resource getResource() throws IllegalStateException {
    final String path = getContextPath();
    if (path.startsWith("file:")) {
        return new FileSystemResource(path.substring("file:".length()));
    }
    return new ClassPathResource(path);
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java

@Test
public void testResourceZipFileWrite() throws Exception {

    // Get somewhere temporary to write out to
    File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip");
    outputFile.deleteOnExit();/* w  w w .  java  2s .  c  o m*/
    String outputFileName = outputFile.getAbsolutePath();

    ZipFileWriterSource source = new ZipFileWriterSource();
    source.setResource(new FileSystemResource(outputFileName));

    // Configure the ItemWriter
    C24ItemWriter itemWriter = new C24ItemWriter();
    itemWriter.setSink(new TextualSink());
    itemWriter.setWriterSource(source);
    itemWriter.setup(getStepExecution(null));
    // Write the employees out
    itemWriter.write(employees);
    // Close the file
    itemWriter.cleanup();

    // Check that we wrote out what was expected
    ZipFile zipFile = new ZipFile(outputFileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    assertNotNull(entries);
    // Make sure there's at least one entry
    assertTrue(entries.hasMoreElements());
    ZipEntry entry = entries.nextElement();
    // Make sure that the trailing .zip has been removed and the leading path has been removed
    assertFalse(entry.getName().contains(System.getProperty("file.separator")));
    assertFalse(entry.getName().endsWith(".zip"));
    // Make sure that there aren't any other entries
    assertFalse(entries.hasMoreElements());

    try {
        compareCsv(zipFile.getInputStream(entry), employees);
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:com.apress.springosgi.ch9.testsosgi.testivyprovisions.LocalFileSystemIvyRepository.java

/**
 * Return the resource of the indicated bundle in the local Ivy repository
 * // w w w  .ja v  a 2 s.  c  om
 * @param groupId - the groupId of the organization supplying the bundle
 * @param artifact - the artifact id of the bundle
 * @param version - the version of the bundle
 * @return
 */
protected Resource localIvyBundle(String groupId, String artifact, String version, String type) {
    StringBuffer location = new StringBuffer(groupId);
    location.append(SLASH_CHAR);
    location.append(artifact);
    location.append(SLASH_CHAR);
    location.append("jars");
    location.append(SLASH_CHAR);
    location.append(artifact);
    location.append('-');
    location.append(version);
    location.append(".");
    location.append(type);

    return new FileSystemResource(new File(repositoryHome, location.toString()));
}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.FileReadingSettingsFactory.java

private Properties loadCatalinaProperties(final ConfigResponse config) throws IOException {
    Resource propResource = new FileSystemResource(
            Metric.decode(config.getValue("installpath")) + "/conf/catalina.properties");
    Properties catalinaProperties;
    if (propResource.exists()) {
        catalinaProperties = PropertiesLoaderUtils.loadProperties(propResource);
    } else {/*from   w w  w .ja v  a  2  s .co  m*/
        catalinaProperties = new Properties();
    }
    // add catalina.home and catalina.base which are not in the props file
    catalinaProperties.put("catalina.home", Metric.decode(config.getValue("catalina.home")));
    catalinaProperties.put("catalina.base", Metric.decode(config.getValue("installpath")));
    return catalinaProperties;
}

From source file:edu.dfci.cccb.mev.dataset.rest.google.GoogleWorkspace.java

@SneakyThrows({ InvalidDimensionTypeException.class, InvocationTargetException.class,
        IllegalAccessException.class, NoSuchMethodException.class })
public void load(final String id) throws IOException, InvalidDatasetNameException, DatasetBuilderException {
    try (TemporaryFile file = new TemporaryFile()) {
        try (FileOutputStream copy = new FileOutputStream(file)) {
            IOUtils.copy(google.driveOperations().downloadFile(id).getInputStream(), copy);
        } catch (Exception e) {
            log.warn("Failure downloading file", e);
            return;
        }//from   w  w w.j a va  2 s. co m
        workspaceDelegate.put(new Dataset() {
            private final Dataset delegate;
            private final Analyses analyses;

            {
                delegate = builder.get()
                        .build(new MockTsvInput(google.driveOperations().getFile(id).getTitle(), file));
                final Analyses analysesDelegate = this.delegate.analyses();
                if (!session.containsKey(id)) {
                    session.put(id, new HashMap<String, Class<? extends Analysis>>());
                } else {
                    for (Map.Entry<String, Class<? extends Analysis>> analysisId : session.get(id).entrySet())
                        analysesDelegate.put((Analysis) analysisId.getValue()
                                .getMethod("from", InputStream.class).invoke(null, google.driveOperations()
                                        .downloadFile(analysisId.getKey()).getInputStream()));
                }

                analyses = new Analyses() {

                    @Override
                    public void remove(String name) throws AnalysisNotFoundException {
                        analysesDelegate.remove(name);
                    }

                    @Override
                    @SneakyThrows({ FileNotFoundException.class, IllegalAccessException.class,
                            IOException.class, InvocationTargetException.class })
                    public void put(Analysis analysis) {
                        File tmp = File.createTempFile("mev-", ".analysis");
                        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tmp))) {
                            analysis.getClass().getMethod("to", OutputStream.class).invoke(analysis, out);
                            session.get(id)
                                    .put(google.driveOperations()
                                            .upload(new FileSystemResource(tmp),
                                                    DriveFile.builder().setTitle(analysis.name()).build(),
                                                    new UploadParameters())
                                            .getId(), analysis.getClass());
                        } catch (NoSuchMethodException e) {
                            log.warn("Unable to save analysis" + analysis, e);
                        } finally {
                            tmp.delete();
                        }
                        analysesDelegate.put(analysis);
                    }

                    @Override
                    public List<String> list() {
                        return analysesDelegate.list();
                    }

                    @Override
                    public Analysis get(String name) throws AnalysisNotFoundException {
                        return analysesDelegate.get(name);
                    }
                };
            }

            @Override
            public String name() {
                return delegate.name();
            }

            @Override
            public Values values() {
                return delegate.values();
            }

            @Override
            public Dimension dimension(Type type) throws InvalidDimensionTypeException {
                return delegate.dimension(type);
            }

            @Override
            public void set(Dimension dimension) throws InvalidDimensionTypeException {
                delegate.set(dimension);
            }

            @Override
            public Analyses analyses() {
                return analyses;
            }

            @Override
            public void exportSelection(String name, Type dimension, String selection, Workspace workspace,
                    DatasetBuilder datasetBuilder) throws InvalidDimensionTypeException,
                    SelectionNotFoundException, InvalidCoordinateException, IOException,
                    DatasetBuilderException, InvalidDatasetNameException {
                delegate.exportSelection(name, dimension, selection, workspace, datasetBuilder);
            }
        });
    }
}

From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java

public Map<String, Object> sendPostForUpload(String url, String path, Log log) throws IOException {
    File file = new File(path);
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.available();/*  w w  w.j a v  a 2  s  .co m*/
    fileInputStream.close();
    FileSystemResource resource = new FileSystemResource(file);
    Map<String, Object> params = new HashMap<>();
    params.put("file", resource);
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>();
    postParams.setAll(params);
    Map<String, Object> response = new HashMap<String, Object>();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "multipart/form-data");
    headers.set("Accept", "application/json");
    headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue());
    org.springframework.http.HttpEntity<Object> request = new org.springframework.http.HttpEntity<Object>(
            postParams, headers);
    ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    response.put("content-type", contentType);
    response.put("statusCode", statusCode);
    response.put("body", body);

    return response;
}

From source file:com.netflix.genie.web.services.impl.DiskJobFileServiceImpl.java

/**
 * {@inheritDoc}/*from w  w  w .j a v a 2  s. co m*/
 */
@Override
public Resource getJobFileAsResource(final String jobId, @Nullable final String relativePath) {
    log.debug("Attempting to get resource for job {} with relative path {}", jobId, relativePath);
    final Path jobDirectoryLocation = StringUtils.isBlank(relativePath) ? this.jobsDirRoot.resolve(jobId)
            : this.jobsDirRoot.resolve(jobId).resolve(relativePath);
    return new FileSystemResource(jobDirectoryLocation);
}

From source file:com.baomidou.mybatisplus.spring.MybatisMapperRefresh.java

public void run() {
    final GlobalConfiguration mybatisGlobalCache = GlobalConfiguration.GlobalConfig(configuration);
    /*/*from  ww w  .  j  a va 2 s  . co  m*/
     * ? XML 
     */
    if (enabled) {
        beforeTime = SystemClock.now();
        final MybatisMapperRefresh runnable = this;
        new Thread(new Runnable() {

            public void run() {
                if (fileSet == null) {
                    fileSet = new HashSet<String>();
                    for (Resource mapperLocation : mapperLocations) {
                        try {
                            if (ResourceUtils.isJarURL(mapperLocation.getURL())) {
                                String key = new UrlResource(
                                        ResourceUtils.extractJarFileURL(mapperLocation.getURL())).getFile()
                                                .getPath();
                                fileSet.add(key);
                                if (jarMapper.get(key) != null) {
                                    jarMapper.get(key).add(mapperLocation);
                                } else {
                                    List<Resource> resourcesList = new ArrayList<Resource>();
                                    resourcesList.add(mapperLocation);
                                    jarMapper.put(key, resourcesList);
                                }
                            } else {
                                fileSet.add(mapperLocation.getFile().getPath());
                            }
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    }
                }
                try {
                    Thread.sleep(delaySeconds * 1000);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                while (true) {
                    try {
                        for (String filePath : fileSet) {
                            File file = new File(filePath);
                            if (file != null && file.isFile() && file.lastModified() > beforeTime) {
                                mybatisGlobalCache.setRefresh(true);
                                List<Resource> removeList = jarMapper.get(filePath);
                                if (removeList != null && !removeList.isEmpty()) {// jarxmljarxml??jar?xml
                                    for (Resource resource : removeList) {
                                        runnable.refresh(resource);
                                    }
                                } else {
                                    runnable.refresh(new FileSystemResource(file));
                                }
                            }
                        }
                        if (mybatisGlobalCache.isRefresh()) {
                            beforeTime = SystemClock.now();
                        }
                        mybatisGlobalCache.setRefresh(true);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                    try {
                        Thread.sleep(sleepSeconds * 1000);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }

                }
            }
        }, "mybatis-plus MapperRefresh").start();
    }
}

From source file:org.apache.cxf.dosgi.systests.common.AbstractDosgiSystemTest.java

@Override
protected Resource[] getTestBundles() {
    // Return the bundles for the current distribution, filtering out the 
    // ones that are already installed as part of the testing framework.
    // At the end the test subclass is called to obtain the test bundles.

    List<String> frameworkBundleNames = new ArrayList<String>();
    for (Resource r : getTestFrameworkBundles()) {
        frameworkBundleNames.add(r.getFilename());
    }//from  w w  w .j a  v a2  s.  c om

    try {
        List<Resource> resources = new ArrayList<Resource>();
        for (File file : getDistributionBundles()) {
            if (!frameworkBundleNames.contains(file.getName())) {
                resources.add(new FileSystemResource(file));
            }
        }

        resources.addAll(Arrays.asList(super.getTestBundles()));
        return resources.toArray(new Resource[resources.size()]);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}