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:grails.plugin.searchable.internal.SearchableUtils.java

private static Map loadMetadata() {
    Resource r = new ClassPathResource(PROJECT_META_FILE);
    if (r.exists()) {
        return loadMetadata(r);
    }/*from   www  .  j  a  va 2s.co  m*/
    String basedir = System.getProperty("base.dir");
    if (basedir != null) {
        r = new FileSystemResource(new File(basedir, PROJECT_META_FILE));
        if (r.exists()) {
            return loadMetadata(r);
        }
    }
    return null;
}

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

@Test
public void testZipDirectoriesNotRecursive() throws Exception {
    FileUtils.forceMkdir(new File("target/Z-testfiles/source/subdir"));
    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/subdir/CP1-input.csv"));

    String aTargetFilename = "target/Z4-input.zip";
    ZipFilesTasklet aTasklet = new ZipFilesTasklet();
    aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/"));
    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();
    aSourceFactory.setPattern("file:target/Z-testfiles/source/");
    aTasklet.setSourceFactory(aSourceFactory);
    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();
    aDestinationFactory.setExpression(aTargetFilename);
    aTasklet.setDestinationFactory(aDestinationFactory);
    aTasklet.setRecursive(false);//  w  w w .  ja  v  a 2  s.  c  o  m

    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("source", aEntries.nextElement().getName());
    assertTrue(aEntries.hasMoreElements());
    assertEquals("source/CP0-input.csv", aEntries.nextElement().getName());
    assertFalse(aEntries.hasMoreElements());
    aZipFile.close();
}

From source file:com.fortify.processrunner.RunProcessRunnerFromSpringConfig.java

/**
 * Check whether the given configuration file exists and is readable. 
 * @param configFile/*from  w w  w .ja  va2s  . com*/
 */
protected final void checkConfigFile(String configFile) {
    Resource resource = new FileSystemResource(configFile);
    if (!resource.exists()) {
        throw new IllegalArgumentException("ERROR: Configuration file " + configFile + " does not exist");
    }
    if (!resource.isReadable()) {
        throw new IllegalArgumentException("ERROR: Configuration file " + configFile + " is not readable");
    }
}

From source file:edu.harvard.i2b2.ontology.util.OntologyUtil.java

/**
 * Load application property file into memory
 *//*from   w w w. ja  v a2 s. co m*/
private String getPropertyValue(String propertyName) throws I2B2Exception {
    if (appProperties == null) {
        // read application directory property file
        Properties loadProperties = ServiceLocator.getProperties(APPLICATION_DIRECTORY_PROPERTIES_FILENAME);

        // read application directory property
        String appDir = loadProperties.getProperty(APPLICATIONDIR_PROPERTIES);

        if (appDir == null) {
            throw new I2B2Exception("Could not find " + APPLICATIONDIR_PROPERTIES + "from "
                    + APPLICATION_DIRECTORY_PROPERTIES_FILENAME);
        }

        String appPropertyFile = appDir + "/" + APPLICATION_PROPERTIES_FILENAME;

        try {
            FileSystemResource fileSystemResource = new FileSystemResource(appPropertyFile);
            PropertiesFactoryBean pfb = new PropertiesFactoryBean();
            pfb.setLocation(fileSystemResource);
            pfb.afterPropertiesSet();
            appProperties = (Properties) pfb.getObject();
        } catch (IOException e) {
            throw new I2B2Exception("Application property file(" + appPropertyFile
                    + ") missing entries or not loaded properly");
        }

        if (appProperties == null) {
            throw new I2B2Exception("Application property file(" + appPropertyFile
                    + ") missing entries or not loaded properly");
        }
    }

    String propertyValue = appProperties.getProperty(propertyName);

    if ((propertyValue != null) && (propertyValue.trim().length() > 0)) {
        ;
    } else {
        throw new I2B2Exception("Application property file(" + APPLICATION_PROPERTIES_FILENAME + ") missing "
                + propertyName + " entry");
    }

    return propertyValue;
}

From source file:com.ssn.event.controller.SSNShareController.java

@Override
public void mouseClicked(MouseEvent e) {
    Object mouseEventObj = e.getSource();
    if (mouseEventObj != null && mouseEventObj instanceof JLabel) {
        JLabel label = (JLabel) mouseEventObj;
        getShareForm().setCursor(new Cursor(Cursor.WAIT_CURSOR));
        // Tracking this sharing event in Google Analytics
        GoogleAnalyticsUtil.track(SSNConstants.SSN_APP_EVENT_SHARING);
        Thread thread = null;/*from   w  ww.  j  a  v a2s.c om*/
        switch (label.getName()) {
        case "FacebookSharing":
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {

                    Set<String> sharedFileList = getFiles();
                    AccessGrant facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                    if (facebookAccessGrant == null) {
                        try {
                            LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                            loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                            loginWithFacebook.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                                if (facebookAccessGrant == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (InterruptedException ex) {
                            logger.error(ex);
                        }
                    }

                    FacebookConnectionFactory connectionFactory = new FacebookConnectionFactory(
                            SSNConstants.SSN_FACEBOOK_API_KEY, SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                    Connection<Facebook> connection = connectionFactory.createConnection(facebookAccessGrant);
                    Facebook facebook = connection.getApi();
                    MediaOperations mediaOperations = facebook.mediaOperations();

                    if (!isAlreadyLoggedIn) {
                        // SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                        FacebookProfile userProfile = facebook.userOperations().getUserProfile();
                        String userName = "";
                        if (userProfile != null) {
                            userName = userProfile.getName() != null ? userProfile.getName()
                                    : userProfile.getFirstName();
                        }
                        confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                "Confirmation", "",
                                "You are already logged in with " + userName + ", Click OK to continue.");
                        int result = confirmeDialog.getResult();
                        if (result == JOptionPane.YES_OPTION) {
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                    messageDialogBox.initDialogBoxUI(
                                            SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                            "Successfully uploaded.");
                                    messageDialogBox.setFocusable(true);

                                }
                            });
                        } else if (result == JOptionPane.NO_OPTION) {

                            AccessGrant facebookAccessGrant1 = null;
                            if (facebookAccessGrant1 == null) {
                                try {
                                    LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                                    loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                                    loginWithFacebook.login();

                                    boolean processFurther = false;
                                    while (!processFurther) {
                                        facebookAccessGrant1 = getHomeModel().getHomeForm()
                                                .getFacebookAccessGrant();
                                        if (facebookAccessGrant1 == null) {
                                            Thread.sleep(10000);
                                        } else {
                                            processFurther = true;
                                            //isAlreadyLoggedIn = true;
                                        }
                                    }
                                    connectionFactory = new FacebookConnectionFactory(
                                            SSNConstants.SSN_FACEBOOK_API_KEY,
                                            SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                                    connection = connectionFactory.createConnection(facebookAccessGrant);
                                    facebook = connection.getApi();
                                    mediaOperations = facebook.mediaOperations();
                                } catch (InterruptedException ex) {
                                    logger.error(ex);
                                }
                            }
                        }
                    }

                    String[] videoSupported = SSNConstants.SSN_VIDEO_FORMAT_SUPPORTED;
                    final List<String> videoSupportedList = Arrays.asList(videoSupported);

                    for (String file : sharedFileList) {
                        String fileExtension = file.substring(file.lastIndexOf(".") + 1, file.length());
                        Resource resource = new FileSystemResource(file);

                        if (!videoSupportedList.contains(fileExtension.toUpperCase())) {
                            String output = mediaOperations.postPhoto(resource);
                        } else {
                            String output = mediaOperations.postVideo(resource);
                        }

                    }

                    getShareForm().dispose();
                }
            };
            thread.start();
            break;
        case "TwitterSharing":
            LoginWithTwitter.deniedPermission = false;
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {
                    Set<String> sharedFileList = getFiles();
                    OAuthToken twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                    if (twitterOAuthToken == null) {
                        try {
                            LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                            loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                            loginWithTwitter.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                if (LoginWithTwitter.deniedPermission)
                                    break;

                                twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                                if (twitterOAuthToken == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (IOException | InterruptedException ex) {
                            logger.error(ex);
                        }
                    }
                    if (!LoginWithTwitter.deniedPermission) {
                        Twitter twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                SSNConstants.SSN_TWITTER_SECRET_KEY, twitterOAuthToken.getValue(),
                                twitterOAuthToken.getSecret());
                        TimelineOperations timelineOperations = twitter.timelineOperations();
                        if (!isAlreadyLoggedIn) {
                            SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                            TwitterProfile userProfile = twitter.userOperations().getUserProfile();

                            String userName = "";
                            if (userProfile != null) {
                                userName = twitter.userOperations().getScreenName() != null
                                        ? twitter.userOperations().getScreenName()
                                        : userProfile.getName();
                            }
                            confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                    "Confirmation", "",
                                    "You are already logged in with " + userName + ", Click OK to continue.");
                            int result = confirmeDialog.getResult();
                            if (result == JOptionPane.YES_OPTION) {
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {
                                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                        messageDialogBox.initDialogBoxUI(
                                                SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                                "Successfully uploaded.");
                                        messageDialogBox.setFocusable(true);

                                    }
                                });
                            } else if (result == JOptionPane.NO_OPTION) {

                                twitterOAuthToken = null;
                                if (twitterOAuthToken == null) {
                                    try {
                                        LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                                        loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                                        loginWithTwitter.login();

                                        boolean processFurther = false;
                                        while (!processFurther) {
                                            twitterOAuthToken = getHomeModel().getHomeForm()
                                                    .getTwitterOAuthToken();
                                            if (twitterOAuthToken == null) {
                                                Thread.sleep(10000);
                                            } else {
                                                processFurther = true;

                                            }
                                        }
                                        twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                                SSNConstants.SSN_TWITTER_SECRET_KEY,
                                                twitterOAuthToken.getValue(), twitterOAuthToken.getSecret());
                                        timelineOperations = twitter.timelineOperations();
                                    } catch (IOException | InterruptedException ex) {
                                        logger.error(ex);
                                    }
                                }
                            }
                        }

                        for (String file : sharedFileList) {
                            Resource image = new FileSystemResource(file);

                            TweetData tweetData = new TweetData("At " + new Date());
                            tweetData.withMedia(image);
                            timelineOperations.updateStatus(tweetData);
                        }
                    } else {
                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        messageDialogBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Alert",
                                "", "User denied for OurHive App permission on twitter.");
                        messageDialogBox.setFocusable(true);
                    }
                    getShareForm().dispose();
                }

            };
            thread.start();
            break;
        case "InstagramSharing":
            break;
        case "MailSharing":
            try {
                String OS = System.getProperty("os.name").toLowerCase();

                Set<String> sharedFileList = getFiles();
                Set<String> voiceNoteList = new HashSet<String>();
                for (String sharedFile : sharedFileList) {
                    String voiceNote = SSNDao.getVoiceCommandPath(new File(sharedFile).getAbsolutePath());
                    if (voiceNote != null && !voiceNote.isEmpty()) {
                        voiceNoteList.add(voiceNote);
                    }
                }
                sharedFileList.addAll(voiceNoteList);

                String fileFullPath = "";
                String caption = "";
                if (sharedFileList.size() == 1) {
                    fileFullPath = sharedFileList.toArray(new String[0])[0];

                    caption = SSMMediaGalleryPanel.readMetaDataForTitle(new File(fileFullPath));

                } else if (sharedFileList.size() > 1) {
                    fileFullPath = SSNHelper.createZipFileFromMultipleFiles(sharedFileList);
                }

                if (OS.contains("win")) {

                    // String subject = "SSN Subject";
                    String subject = caption.equals("") ? SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT : caption;
                    String body = "";
                    String m = "&subject=%s&body=%s";

                    String outLookExeDir = "C:\\Program Files\\Microsoft Office\\Office14\\Outlook.exe";
                    String mailCompose = "/c";
                    String note = "ipm.note";
                    String mailBodyContent = "/m";

                    m = String.format(m, subject, body);
                    String slashA = "/a";

                    String mailClientConfigParams[] = null;
                    Process startMailProcess = null;

                    mailClientConfigParams = new String[] { outLookExeDir, mailCompose, note, mailBodyContent,
                            m, slashA, fileFullPath };
                    startMailProcess = Runtime.getRuntime().exec(mailClientConfigParams);
                    OutputStream out = startMailProcess.getOutputStream();
                    File zipFile = new File(fileFullPath);
                    zipFile.deleteOnExit();
                } else if (OS.indexOf("mac") >= 0) {
                    //Process p = Runtime.getRuntime().exec(new String[]{String.format("open -a mail ", fileFullPath)});
                    Desktop desktop = Desktop.getDesktop();
                    String mailTo = caption.equals("") ? "?SUBJECT=" + SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT
                            : caption;
                    URI uriMailTo = null;
                    uriMailTo = new URI("mailto", mailTo, null);
                    desktop.mail(uriMailTo);
                }

                this.getShareForm().dispose();
            } catch (Exception ex) {
                logger.error(ex);
            }
            break;
        case "moveCopy":
            getShareForm().dispose();
            File album = new File(SSNHelper.getSsnHiveDirPath());
            File[] albumPaths = album.listFiles();
            Vector albumNames = new Vector();
            for (int i = 0; i < albumPaths.length; i++) {
                if (!(albumPaths[i].getName().equals("OurHive")) && SSNHelper.lastAlbum != null
                        && !(albumPaths[i].getName().equals(SSNHelper.lastAlbum)))
                    albumNames.add(albumPaths[i].getName());
            }
            if (SSNHelper.lastAlbum != null && !SSNHelper.lastAlbum.equals("OurHive"))
                albumNames.insertElementAt("OurHive", 0);

            SSNInputDialogBox inputBox = new SSNInputDialogBox(true, albumNames);
            inputBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Copy Media",
                    "Please Select Album Name");
            String destAlbumName = inputBox.getTextValue();
            if (StringUtils.isNotBlank(destAlbumName)) {
                homeModel.moveAlbum(destAlbumName, getFiles());
            }

        }
        getShareForm().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
}

From source file:net.sourceforge.vulcan.spring.SpringPluginManagerTest.java

public void testInitLoadsBundlesPlugins() throws Exception {
    mgr.setImportBundledPlugins(true);//from w  ww. ja va 2  s  . co m
    final String resourcePattern = "/plugins/*.zip";
    final FileSystemResource resource = new FileSystemResource(
            resolveRelativeFile("source/test/pluginTests/mockPlugin.zip"));

    mgr.setBundledPluginResourcesPattern(resourcePattern);
    final MockApplicationContext ctx = new MockApplicationContext() {
        @Override
        public Resource[] getResources(String locationPattern) throws java.io.IOException {
            assertEquals(resourcePattern, locationPattern);
            return new Resource[] { resource };
        };
    };
    ctx.refresh();
    mgr.setApplicationContext(ctx);

    final PluginMetaDataDto pluginConfig = createFakePluginConfig(true);

    expect(store.extractPlugin((InputStream) anyObject())).andReturn(pluginConfig);

    expect(store.getPluginConfigs()).andReturn(new PluginMetaDataDto[] { pluginConfig });
    expert.registerPlugin((ClassLoader) anyObject(), (String) anyObject());

    replay();

    assertEquals(0, mgr.plugins.size());

    mgr.init();

    verify();
    assertEquals(1, mgr.plugins.size());
}

From source file:de.zib.gndms.gndmc.AbstractClient.java

/**
 * Upload (POST) multiple files on a url.
 *
 * The request header contains a given user name, the body of the request contains
 * a given object of type P./*from  w  ww  .j  a  va  2 s.c  om*/
 *
 * @param <T> The body type of the response.
 * @param clazz The type of the return value.
 * @param fileNames A collection of all files to upload
 * @param url The url of the request.
 * @param dn The user name.
 * @return The response as entity.
 */
protected final <T> ResponseEntity<T> postFile(final Class<T> clazz, final Collection<String> fileNames,
        final String url, final String dn) {

    GNDMSResponseHeader requestHeaders = new GNDMSResponseHeader();
    MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
    final HttpEntity requestEntity;

    if (dn != null) {
        requestHeaders.setDN(dn);
    }

    List<FileSystemResource> files = new LinkedList<FileSystemResource>();
    for (String f : fileNames) {
        files.add(new FileSystemResource(f));
    }
    form.add("files", files);
    requestEntity = new HttpEntity(form, requestHeaders);

    if (null == restTemplate)
        throw new NullPointerException("Please set RestTemplate in Client!");

    return restTemplate.postForEntity(url, requestEntity, clazz);
}

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

/**
 * Adds the citrus admin connector dependency to the target project Maven POM.
 *//*  w w  w .  ja v a  2 s . co  m*/
public void addConnector() {
    if (project.isMavenProject()) {
        try {
            String pomXml = FileUtils.readToString(new FileSystemResource(project.getMavenPomFile()));

            if (!pomXml.contains("<artifactId>citrus-admin-connector</artifactId>")) {
                pomXml = pomXml.replaceAll("</dependencies>", "  <dependency>" + System.lineSeparator()
                        + "      <groupId>com.consol.citrus</groupId>" + System.lineSeparator()
                        + "      <artifactId>citrus-admin-connector</artifactId>" + System.lineSeparator()
                        + "      <version>1.0.0-beta-5</version>" + System.lineSeparator() + "    </dependency>"
                        + System.lineSeparator() + "  </dependencies>");

                FileUtils.writeToFile(pomXml, new FileSystemResource(project.getMavenPomFile()).getFile());
            }

            project.getSettings().setUseConnector(true);
            project.getSettings().setConnectorActive(true);
            saveProject(project);

            if (springBeanService.getBeanDefinition(getProjectContextConfigFile(), getActiveProject(),
                    WebSocketPushMessageListener.class.getSimpleName(), SpringBean.class) == null) {
                SpringBean pushMessageListener = new SpringBean();
                pushMessageListener.setId(WebSocketPushMessageListener.class.getSimpleName());
                pushMessageListener.setClazz(WebSocketPushMessageListener.class.getName());

                if (!environment.getProperty("local.server.port", "8080").equals("8080")) {
                    Property portProperty = new Property();
                    portProperty.setName("port");
                    portProperty.setValue(environment.getProperty("local.server.port"));
                    pushMessageListener.getProperties().add(portProperty);
                }
                springBeanService.addBeanDefinition(getProjectContextConfigFile(), getActiveProject(),
                        pushMessageListener);
            }
        } catch (IOException e) {
            throw new ApplicationRuntimeException(
                    "Failed to add admin connector dependency to Maven pom.xml file", e);
        }
    }
}

From source file:gov.nih.nci.cabig.caaers.esb.client.MessageNotificationService.java

public void sendMail(String[] to, String subject, String content, String attachment) throws Exception {

    MimeMessage message = caaersJavaMailSender.createMimeMessage();
    message.setSubject(subject);//from  ww  w. j  a  v  a2s  .  c  o  m
    message.setFrom(new InternetAddress(configuration.get(Configuration.SYSTEM_FROM_EMAIL)));

    // use the true flag to indicate you need a multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(to);
    helper.setText(content);

    if (attachment != null) {
        File f = new File(attachment);
        FileSystemResource file = new FileSystemResource(f);
        helper.addAttachment(file.getFilename(), file);
    }

    caaersJavaMailSender.send(message);

}

From source file:annis.administration.AdministrationDao.java

protected void populateSchema() {
    log.info("populating the schemas with default values");
    bulkloadTableFromResource("resolver_vis_map",
            new FileSystemResource(new File(getScriptPath(), FILE_RESOLVER_VIS_MAP + annisFileSuffix)));
    // update the sequence
    executeSqlFromScript("update_resolver_sequence.sql");

    log.info("creating immutable functions for extracting annotations");
    executeSqlFromScript("functions_get.sql");
}