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.apdplat.platform.compass.APDPlatLocalCompassBean.java

/**
 * Sets an optional connection based on Spring <code>Resource</code>
 * abstraction. Will be used if none is set as part of other possible
 * configuration of Compass connection./*from   w ww.  j a v  a 2s .  c  o m*/
 * <p/>
 * Will use <code>Resource#getFile</code> in order to get the absolute
 * path.
 */
public void setConnection(Resource connection) {
    //this.connection = connection;
    //compass
    //???
    Resource resource = new FileSystemResource(IndexManager.getIndexDir());
    this.connection = resource;
    try {
        log.info("apdplatcompass1 :? "
                + connection.getFile().getPath() + " ?? "
                + this.connection.getFile().getAbsolutePath() + "");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.eclipse.swordfish.core.test.util.base.TargetPlatformOsgiTestCase.java

@Override
protected Resource[] getTestBundles() {
    String targetPlatformPath = getTargetPlatformPath();
    Assert.notNull(targetPlatformPath, "Either system property [" + TARGET_PLATFORM_SYS_PORPERTY
            + "] should be set or there should be the org.eclipse.swordfish.bundles project containing bundles "
            + "needed to launch the Swordfish env");
    List<Resource> bundles = new ArrayList<Resource>();
    bundles.add(BaseMavenOsgiTestCase.getMavenRepositoryBundle("org.eclipse.swordfish",
            "org.eclipse.swordfish.core.test.util"));
    List<Pattern> excludePatterns = getExcludeBundlePatterns();
    boolean exclude;
    for (File bundle : new File(targetPlatformPath).listFiles()) {
        exclude = false;/*from w  w w .  j  ava2s .  c om*/
        for (Pattern pattern : excludePatterns) {
            if (pattern.matcher(bundle.getName()).matches()) {
                exclude = true;
            }
        }
        if (!exclude && bundle.isFile() && bundle.getName().endsWith("jar")) {
            bundles.add(new FileSystemResource(bundle));
        }
    }
    /*Because of the strange behavior of the spring osgi
     *test framework we need to load org.eclipse.swordfish.core.configuration and org.eclipse.swordfish.core.event bundles
     *before org.eclipse.swordfish.core
     *TODO: Could anyone propose any less uglier solution  */
    Resource[] bundleArray = bundles.toArray(new Resource[bundles.size()]);
    adjustBundleOrder(bundleArray);
    for (Resource bundle : bundleArray) {
        System.out.println(bundle.getFilename());
    }
    return bundleArray;
}

From source file:com.google.api.ads.adwords.awalerting.AwAlerting.java

/**
 * Load JSON configuration file specified in the properties file. First try to load the JSON
 * configuration file from the same folder as the properties file; if it does not exist, try to
 * load it from the default location.//  w ww. j av a 2s  .c o m
 *
 * @param propertiesPath the path to the properties file
 * @return JSON configuration loaded from the json file
 * @throws AlertConfigLoadException error reading properties / json file
 */
private static JsonObject getAlertsConfig(String propertiesPath) throws AlertConfigLoadException {
    LOGGER.info("Using properties file: {}", propertiesPath);

    Resource propertiesResource = new ClassPathResource(propertiesPath);
    if (!propertiesResource.exists()) {
        propertiesResource = new FileSystemResource(propertiesPath);
    }

    JsonObject alertsConfig = null;
    try {
        Properties properties = initApplicationContextAndProperties(propertiesResource);

        // Load alerts config from the same folder as the properties file
        String alertsConfigFilename = properties.getProperty("aw.alerting.alerts");
        String propertiesFolder = propertiesResource.getFile().getParent();
        File alertsConfigFile = new File(propertiesFolder, alertsConfigFilename);

        // If it does not exist, try the default resource folder according to maven structure.
        if (!alertsConfigFile.exists()) {
            String alertsConfigFilepath = "src/main/resources/" + alertsConfigFilename;
            alertsConfigFile = new File(alertsConfigFilepath);
        }

        LOGGER.debug("Loading alerts config file from {}", alertsConfigFile.getAbsolutePath());
        JsonParser jsonParser = new JsonParser();
        alertsConfig = jsonParser.parse(new FileReader(alertsConfigFile)).getAsJsonObject();
        LOGGER.debug("Done.");
    } catch (IOException e) {
        throw new AlertConfigLoadException("Error loading alerts config at " + propertiesPath, e);
    } catch (JsonParseException e) {
        throw new AlertConfigLoadException("Error parsing config file at " + propertiesPath, e);
    }

    return alertsConfig;
}

From source file:com.anuz.dummyapi.controller.ClientController.java

@RequestMapping(value = "/contents_file/{id}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadFiles(@PathVariable("id") int id) throws IOException {

    List<Content> contentList = contentUpdateService.getUnsynchronizedContentList(id);
    if (!contentList.isEmpty()) {
        String fileName = "zipFile" + new Date().getTime() + ".zip";
        ZipUtil zipFile = new ZipUtil();
        for (Content content : contentList) {
            System.out.println(CONSTANTS.CONTENTS + content.getContentLocation());
            zipFile.generateFileList(new File(CONSTANTS.CONTENTS + content.getContentLocation()));
        }/*from www .jav a2 s.c o  m*/
        String finalZip = zipFile.zipIt(CONSTANTS.CONTENTS + fileName);
        //            System.out.println(finalZip);
        //            if(finalZip!=null){
        //                contentUpdateService.updateContentStatus(id,Boolean.FALSE);
        //            }

        FileSystemResource file = new FileSystemResource(finalZip);

        //            return ResponseEntity.ok().contentLength(file.contentLength())
        //                    .contentType(MediaType.parseMediaType("application/octet-stream"))
        //                    .header("Content-Disposition", "attachment; filename=" + fileName)
        //                    .body(new InputStreamResource(file.getInputStream()));

        return ResponseEntity.ok().contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/zip"))
                .header("Content-Disposition", "attachment; filename=" + fileName)
                .body(new InputStreamResource(file.getInputStream()));

    }
    return ResponseEntity.ok().body(null);

}

From source file:net.bafeimao.umbrella.web.test.MailTests.java

@Test
public void testSendMailWithAttachedImage() throws MessagingException {
    // ?,???html/*  w  w  w .  jav  a 2s. co m*/
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // ?boolean,?MimeMessageHelpertrue?
    // multipart? true?? ?html?
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

    // 
    messageHelper.setTo("29283212@qq.com");
    messageHelper.setFrom("29283212@qq.com");
    messageHelper.setSubject("!?");
    // true ?HTML?
    messageHelper.setText(
            "<html><head></head><body><h1>?</h1></body></html>", true);

    FileSystemResource file = new FileSystemResource(new File(imagePath));
    // ???
    messageHelper.addAttachment("image", file);

    // ??
    senderImpl.send(mailMessage);

    System.out.println("???..");
}

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

@Test
public void testResourceFileWrite() throws Exception {

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

    FileWriterSource source = new FileWriterSource();
    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
    FileInputStream inputStream = new FileInputStream(outputFileName);
    try {
        compareCsv(inputStream, employees);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

From source file:com.consol.citrus.admin.service.report.TestNGTestReportService.java

/**
 * Access file resource representing the TestNG results file.
 * @param activeProject//w  w w. ja va  2s.  c om
 * @return
 */
private Resource getTestResultsFile(Project activeProject) {
    return new FileSystemResource(
            activeProject.getProjectHome() + "/target/failsafe-reports/testng-results.xml");
}

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

@Test
public void testManageConnector() throws Exception {
    Project testProject = new Project(new ClassPathResource("projects/maven").getFile().getCanonicalPath());
    projectService.setActiveProject(testProject);

    Assert.assertFalse(FileUtils.readToString(new FileSystemResource(testProject.getMavenPomFile()))
            .contains("citrus-admin-connector"));

    when(springBeanService.getBeanDefinition(any(File.class), eq(testProject),
            eq(WebSocketPushMessageListener.class.getSimpleName()), eq(SpringBean.class))).thenReturn(null);
    when(environment.getProperty("local.server.port", "8080")).thenReturn("8080");
    projectService.addConnector();//from   ww w .ja  va  2 s . c  o  m

    Assert.assertTrue(FileUtils.readToString(new FileSystemResource(testProject.getMavenPomFile()))
            .contains("citrus-admin-connector"));

    when(springBeanService.getBeanNames(any(File.class), eq(testProject),
            eq(WebSocketPushMessageListener.class.getName())))
                    .thenReturn(Collections.singletonList(WebSocketPushMessageListener.class.getSimpleName()));
    projectService.removeConnector();

    Assert.assertFalse(FileUtils.readToString(new FileSystemResource(testProject.getMavenPomFile()))
            .contains("citrus-admin-connector"));

    verify(springBeanService).addBeanDefinition(any(File.class), eq(testProject), any(SpringBean.class));
    verify(springBeanService).removeBeanDefinition(any(File.class), eq(testProject),
            eq(WebSocketPushMessageListener.class.getSimpleName()));
}

From source file:com.lm.lic.manager.controller.MobiHandWithdrawLicHandler.java

@SuppressWarnings("unchecked")
public boolean verifyMobiHandRequest(HttpServletRequest request) {
    boolean valid = false;
    com.hhc.client.CertificateReader reader = new com.hhc.client.CertificateReader();
    java.security.PublicKey publicKey = null;
    try {//from w ww. j av a2 s .c  o m
        String pathToClassesDir = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        int index = pathToClassesDir.indexOf("/WEB-INF/");
        String fullPath = pathToClassesDir.substring(0, index + "/WEB-INF/".length())
                + "certificates/Handango.cert";

        FileSystemResource fr = new FileSystemResource(fullPath);
        publicKey = reader.getPublicKey(fr.getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
        return false;
    }

    com.hhc.client.Authenticator authenticator = new com.hhc.client.Authenticator(publicKey);
    try {
        if (authenticator.verify(request.getParameterMap())) {
            valid = true;
        } else {
            valid = false;
        }
    } catch (AuthenticatorException e) {
        e.printStackTrace();
        return false;
    }

    valid = true;
    return valid;
}