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.uima.ruta.resource.MultiTreeWordList.java

/**
 * Default constructor uses just one file.
 * //from   w ww.  ja va  2s  .  co  m
 * @param pathname
 *          the pathname of the used file.
 */
public MultiTreeWordList(String pathname) throws IOException {
    this(new FileSystemResource(pathname));
}

From source file:com.hs.mail.deliver.Deliver.java

private void init(String path) {
    try {//from w ww. j a va 2 s  .com
        File configFile = new File(path);
        Properties props = PropertiesLoaderUtils.loadProperties(new FileSystemResource(configFile));
        String dir = props.getProperty("queue_directory");
        spool = (dir != null) ? new File(dir) : new File(configFile.getParentFile().getParentFile(), "spool");
        if (!spool.isDirectory()) {
            logger.error("Spool directory does not exist: " + spool.getAbsolutePath());
            System.exit(EX_CONFIG);
        }
        Config.setSpoolDirectory(spool);
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
        System.exit(EX_CONFIG);
    }
}

From source file:com.dreamworks.dsp.server.EmbeddedSftpServer.java

@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override//  w  w  w.  ja va 2s  . co  m
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }

    });
    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
    this.server.setSubsystemFactories(
            Collections.<NamedFactory<Command>>singletonList(new SftpSubsystem.Factory()));
    final String virtualDir = new FileSystemResource("").getFile().getAbsolutePath();
    this.server.setFileSystemFactory(new NativeFileSystemFactory() {

        @Override
        public FileSystemView createFileSystemView(org.apache.sshd.common.Session session) {
            return new NativeFileSystemView(session.getUsername(), false) {

                @Override
                public String getVirtualUserDir() {
                    return virtualDir;
                }
            };
        }

    });
}

From source file:architecture.ee.component.core.lifecycle.RepositoryImpl.java

public ConfigRoot getConfigRoot() {
    try {//  w  w w .j a  v a2s  .  c  o m

        File file = new File(getRootResource().getFile(), "config");
        Resource child = new FileSystemResource(file);

        log.debug("config root:" + child.getURI());

        if (!child.exists()) {
            child.getFile().mkdirs();
        }
        return new ConfigRootImpl(child);
    } catch (Exception e) {
    }
    return null;
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategy.java

@Override
public String uploadDataSet(final InstanceConfig config, final File file) throws ResponseStatusException {
    Preconditions.checkArgument(config != null);
    Preconditions.checkArgument(file != null);

    final RestTemplate restTemplate = restTemplateProvider.createTemplate(config.getHost(), config.getPort(),
            config.getUsername(), config.getPassword());
    final String checkSum = createCheckSum(file);

    final List<NameValuePair> params = Arrays
            .asList(new NameValuePair[] { new BasicNameValuePair("checksum", checkSum) });
    final URI url = createUri(config.getScheme(), config.getHost(), config.getPort(), config.getServername(),
            UPLOAD_PATH, params);//from  w  w w.j av  a 2s.  com

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf("application/zip"));
    final HttpEntity<Resource> httpEntity = new HttpEntity<>(new FileSystemResource(file), headers);

    final ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity,
            String.class);

    final HttpStatus status = response.getStatusCode();
    if (status.equals(HttpStatus.CREATED)) {
        return response.getBody().trim();
    } else {
        throw new ResponseStatusException(
                "HttpStatus " + status.toString() + " response received. File upload failed.");
    }
}

From source file:org.jboss.examples.spring.batch.BatchConfiguration.java

@Bean
@StepScope//w w  w .  j av a  2 s.  c om
public FlatFileItemReader<AggregateItem> flatFileItemReader(
        @Value("#{jobParameters[inputFile]}") String fileName, LineTokenizer lineTokenizer) {
    FlatFileItemReader<AggregateItem> rc = new FlatFileItemReader<>();
    rc.setResource(new FileSystemResource(fileName));
    DefaultLineMapper<AggregateItem> mapper = new DefaultLineMapper<>();

    // tokenizer
    mapper.setLineTokenizer(lineTokenizer);

    // field mapper
    AggregateItemFieldSetMapper fieldSetMapper = new AggregateItemFieldSetMapper();
    fieldSetMapper.setDelegate(new TradeFieldSetMapper());
    mapper.setFieldSetMapper(fieldSetMapper);

    rc.setLineMapper(mapper);
    return rc;
}

From source file:com.newinit.email.MailServiceImpl.java

/**
 * envo de email con attachments/*from   w  w w  . j a v a  2 s  .  c  o  m*/
 *
 * @param to correo electrnico del destinatario
 * @param subject asunto del mensaje
 * @param text cuerpo del mensaje
 * @param attachments ficheros que se anexarn al mensaje
 */
@Override
public void send(String to, String subject, String text, File... attachments) {
    // chequeo de parmetros 
    Assert.hasLength(to, "email 'to' needed");
    Assert.hasLength(subject, "email 'subject' needed");
    Assert.hasLength(text, "email 'text' needed");

    // asegurando la trazabilidad
    if (log.isDebugEnabled()) {
        final boolean usingPassword = !"".equals(mailSender.getPassword());
        log.debug("Sending email to: '" + to + "' [through host: '" + mailSender.getHost() + ":"
                + mailSender.getPort() + "', username: '" + mailSender.getUsername() + "' usingPassword:"
                + usingPassword + "].");
        log.debug("isActive: " + active);
    }
    // el servicio esta activo?
    if (!active) {
        return;
    }

    // plantilla para el envo de email
    final MimeMessage message = mailSender.createMimeMessage();

    try {
        // el flag a true indica que va a ser multipart
        final MimeMessageHelper helper = new MimeMessageHelper(message, true);

        // settings de los parmetros del envo
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setFrom(getFrom());
        helper.setText(text);

        // adjuntando los ficheros
        if (attachments != null) {
            for (int i = 0; i < attachments.length; i++) {
                FileSystemResource file = new FileSystemResource(attachments[i]);
                helper.addAttachment(attachments[i].getName(), file);
                if (log.isDebugEnabled()) {
                    log.debug("File '" + file + "' attached.");
                }
            }
        }

    } catch (MessagingException e) {
        new RuntimeException(e);
    }

    // el envo
    this.mailSender.send(message);
}

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

static Path resourceToPath(URL resource) {

    Objects.requireNonNull(resource, "Resource URL cannot be null");
    URI uri;//from   w ww  . ja  v a2s  .c  om
    try {
        uri = resource.toURI();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Could not extract URI", e);
    }

    String scheme = uri.getScheme();
    if (scheme.equals("file")) {
        String path = uri.toString().substring("file:".length());
        if (path.contains("//")) {
            path = StringUtils.cleanPath(path.replace("//", ""));
        }
        return Paths.get(new FileSystemResource(path).getFile().toURI());
    }

    if (!scheme.equals("jar")) {
        throw new IllegalArgumentException("Cannot convert to Path: " + uri);
    }

    String s = uri.toString();
    int separator = s.indexOf("!/");
    String entryName = s.substring(separator + 2);
    URI fileURI = URI.create(s.substring(0, separator));

    FileSystem fs;
    try {
        fs = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap());
        return fs.getPath(entryName);
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not create file system for resource: " + resource, e);
    }
}

From source file:org.eclipse.swordfish.core.test.util.spring.LocalFileSystemMavenRepository.java

/**
 * Initialization method It determines the repository path by checking the
 * existence of <code>localRepository</code> system property and falling
 * back to the <code>settings.xml</code> file and then the traditional
 * <code>user.home/.m2/repository</code>.
 * //from w  w  w .  ja v a  2  s .c  om
 * <p/> This method is used to postpone initialization until an artifact is
 * actually located. As the test class is instantiated on each test run, the
 * init() method prevents repetitive, waste-less initialization.
 * 
 */
public void init() {
    // already discovered a repository home, bailing out
    if (repositoryHome != null)
        return;

    boolean trace = log.isDebugEnabled();

    // check system property
    String localRepository = System.getProperty(SYS_PROPERTY);
    String userHome = System.getProperty(USER_HOME_PROPERTY);
    if (trace)
        log.trace("M2 system property [" + SYS_PROPERTY + "] has value=" + localRepository);

    if (localRepository == null) {
        // if it's not present then check settings.xml local repository property
        Resource settingsFile = new FileSystemResource(new File(userHome, M2_SETTINGS));
        localRepository = getMavenSettingsLocalRepository(settingsFile);
        if (trace)
            log.trace("Falling back to M2 settings.xml [" + settingsFile + "]; found value=" + localRepository);
        if (localRepository == null) {
            // fall back to the default location
            localRepository = new File(userHome, DEFAULT_DIR).getAbsolutePath();
            if (trace)
                log.trace("No custom setting found; using default M2 local repository=" + localRepository);

        }
    }

    repositoryHome = localRepository;
    log.info("Local Maven2 repository used: [" + repositoryHome + "]");
}

From source file:net.sourceforge.vulcan.spring.jdbc.JdbcSchemaMigratorTest.java

static FileSystemResource resolveSqlScript(String scriptName) {
    final File file = TestUtils.resolveRelativeFile("source/main/sql/hsql/" + scriptName);
    return new FileSystemResource(file);
}