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.logsniffer.app.CoreAppConfig.java

@Bean(name = { BEAN_LOGSNIFFER_PROPS })
@Autowired/*w  w  w  .  j a v  a 2s . c o m*/
public PropertiesFactoryBean logSnifferProperties(final ApplicationContext ctx) throws IOException {
    if (ctx.getEnvironment().acceptsProfiles("!" + ContextProvider.PROFILE_NONE_QA)) {
        final File qaFile = File.createTempFile("logsniffer", "qa");
        qaFile.delete();
        final String qaHomeDir = qaFile.getPath();
        logger.info("QA mode active, setting random home directory: {}", qaHomeDir);
        System.setProperty("logsniffer.home", qaHomeDir);
    }
    final PathMatchingResourcePatternResolver pathMatcher = new PathMatchingResourcePatternResolver();
    Resource[] classPathProperties = pathMatcher.getResources("classpath*:/config/**/logsniffer-*.properties");
    final Resource[] metainfProperties = pathMatcher
            .getResources("classpath*:/META-INF/**/logsniffer-*.properties");
    final PropertiesFactoryBean p = new PropertiesFactoryBean();
    for (final Resource r : metainfProperties) {
        classPathProperties = (Resource[]) ArrayUtils.add(classPathProperties, r);
    }
    classPathProperties = (Resource[]) ArrayUtils.add(classPathProperties,
            new FileSystemResource(System.getProperty("logsniffer.home") + "/" + LOGSNIFFER_PROPERTIES_FILE));
    p.setLocations(classPathProperties);
    p.setProperties(System.getProperties());
    p.setLocalOverride(true);
    p.setIgnoreResourceNotFound(true);
    return p;
}

From source file:de.langmi.spring.batch.examples.readers.file.archive.ArchiveMultiResourceItemReaderTest.java

/**
 * Test with tar file with nested directories, contains 4 text files with
 * 20 lines each./*from ww  w  .j a va 2  s  .  c  om*/
 * 
 * @throws Exception 
 */
@Test
public void testOneTarFileNestedDirs() throws Exception {
    LOG.debug("testOneTarFileNestedDirs");
    ArchiveMultiResourceItemReader<String> mReader = new ArchiveMultiResourceItemReader<String>();
    // setup multResourceReader
    mReader.setArchives(new Resource[] {
            new FileSystemResource("src/test/resources/input/file/archive/input_nested_dir.tar") });

    // call general setup last
    generalMultiResourceReaderSetup(mReader);

    // open with mock context
    mReader.open(MetaDataInstanceFactory.createStepExecution().getExecutionContext());

    // read
    try {
        String item = null;
        int count = 0;
        do {
            item = mReader.read();
            if (item != null) {
                count++;
            }
        } while (item != null);
        assertEquals(80, count);
    } catch (Exception e) {
        throw e;
    } finally {
        mReader.close();
    }
}

From source file:org.beanio.spring.SpringTest.java

/**
 * Test BeanIO flat file writer./* w  w w.  j ava  2s  .  c o  m*/
 */
@Test
@SuppressWarnings("unchecked")
public void testItemWriter() throws Exception {
    ExecutionContext ec = new ExecutionContext();

    File tempFile = File.createTempFile("beanio-", "xml");
    tempFile.deleteOnExit();

    BeanIOFlatFileItemWriter<Map<String, Object>> writer = (BeanIOFlatFileItemWriter<Map<String, Object>>) context
            .getBean("itemWriter-standalone");
    writer.setResource(new FileSystemResource(tempFile));
    assertNotNull(writer);
    writer.open(ec);

    Map<String, Object> record = new HashMap<String, Object>();
    record.put("id", 1);
    record.put("name", "John");

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    list.add(record);
    writer.write(list);
    writer.update(ec);

    long position = ec.getLong("BeanIOFlatFileItemWriter.current.count");
    assertTrue(position > 0);

    writer.close();
    assertFileMatches("out1.txt", tempFile);

    // test appendAllowed = true, and saveState = false
    writer = (BeanIOFlatFileItemWriter<Map<String, Object>>) context.getBean("itemWriter-append");
    writer.setResource(new FileSystemResource(tempFile));
    assertNotNull(writer);
    writer.open(ec);

    record.put("id", 2);
    record.put("name", "Joe");
    writer.write(list);
    writer.update(ec);
    assertEquals(position, ec.getLong("BeanIOFlatFileItemWriter.current.count"));

    writer.close();
    assertFileMatches("out2.txt", tempFile);

    // test restart
    writer = (BeanIOFlatFileItemWriter<Map<String, Object>>) context.getBean("itemWriter-standalone");
    writer.setResource(new FileSystemResource(tempFile));
    assertNotNull(writer);
    writer.open(ec);
    record.put("id", 3);
    record.put("name", "Kevin");
    writer.write(list);
    writer.update(ec);
    assertTrue(ec.getLong("BeanIOFlatFileItemWriter.current.count") > position);

    writer.close();
    assertFileMatches("out3.txt", tempFile);
}

From source file:com.adaptc.mws.plugins.testing.transformations.TestForTransformation.java

@Override
public void visit(ASTNode[] astNodes, SourceUnit source) {
    if (!(astNodes[0] instanceof AnnotationNode) || !(astNodes[1] instanceof AnnotatedNode)) {
        throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class");
    }/*from w  w w .  j  a v a 2 s .c o m*/

    AnnotatedNode parent = (AnnotatedNode) astNodes[1];
    AnnotationNode node = (AnnotationNode) astNodes[0];
    if (!MY_TYPE.equals(node.getClassNode()) || !(parent instanceof ClassNode)) {
        return;
    }

    ClassNode classNode = (ClassNode) parent;
    if (classNode.isInterface() || Modifier.isAbstract(classNode.getModifiers())) {
        return;
    }

    boolean junit3Test = isJunit3Test(classNode);
    boolean spockTest = isSpockTest(classNode);
    boolean isJunit = classNode.getName().endsWith("Tests");

    if (!junit3Test && !spockTest && !isJunit)
        return;

    Expression value = node.getMember("value");
    ClassExpression ce;
    if (value instanceof ClassExpression) {
        ce = (ClassExpression) value;
        testFor(classNode, ce, true);
    } else {
        if (!junit3Test) {
            List<AnnotationNode> annotations = classNode.getAnnotations(MY_TYPE);
            if (annotations.size() > 0)
                return; // bail out, in this case it was already applied as a local transform
            // no explicit class specified try by convention
            String fileName = source.getName();
            String className = PluginsResourceUtils.getClassName(new FileSystemResource(fileName));
            if (className != null) {
                boolean isSpock = className.endsWith("Spec");
                String targetClassName = null;

                if (isJunit) {
                    targetClassName = className.substring(0, className.indexOf("Tests"));
                } else if (isSpock) {
                    targetClassName = className.substring(0, className.indexOf("Spec"));
                }

                if (targetClassName != null) {
                    Resource targetResource = findResourceForClassName(targetClassName);
                    if (targetResource != null) {
                        boolean isArtefact = false;
                        // Check for other artefact types
                        for (String artefactType : typeToTestMap.keySet()) {
                            if (targetClassName.endsWith(artefactType)) {
                                isArtefact = true;
                                testFor(classNode,
                                        new ClassExpression(
                                                new ClassNode(targetClassName, 0, ClassHelper.OBJECT_TYPE)),
                                        true);
                                break;
                            }
                        }
                        // Custom component?
                        if (!isArtefact)
                            testFor(classNode, new ClassExpression(
                                    new ClassNode(targetClassName, 0, ClassHelper.OBJECT_TYPE)), false);
                    }
                }
            }
        }
    }
}

From source file:net.triptech.metahive.service.EmailSenderService.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param email the email/*from   w ww.  j  a v  a2 s.c o  m*/
 * @param attachments the attachments
 * @throws ServiceException the service exception
 */
public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments)
        throws ServiceException {

    // Check to see whether the required fields are set (to, from, message)
    if (email.getTo() == null) {
        throw new ServiceException("Error sending email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(email.getFrom())) {
        throw new ServiceException("Error sending email: Email requires " + "a from address");
    }
    if (StringUtils.isBlank(email.getText())) {
        throw new ServiceException("Error sending email: No email " + "message specified");
    }
    if (mailSender == null) {
        throw new ServiceException("The JavaMail sender has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    boolean htmlMessage = false;
    if (StringUtils.containsIgnoreCase(email.getText(), "<html")) {
        htmlMessage = true;
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new ServiceException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }

    try {
        helper.setTo(email.getTo());
        helper.setFrom(email.getFrom());
        helper.setSubject(email.getSubject());

        if (email.getCc() != null) {
            helper.setCc(email.getCc());
        }
        if (email.getBcc() != null) {
            helper.setBcc(email.getBcc());
        }

        if (htmlMessage) {
            String plainText = email.getText();
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(email.getText());
            } catch (Exception e) {
                logger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, email.getText());
        } else {
            helper.setText(email.getText());
        }

        if (email.getSentDate() != null) {
            helper.setSentDate(email.getSentDate());
        } else {
            helper.setSentDate(Calendar.getInstance().getTime());
        }

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

    // Append any attachments (if an HTML email)
    if (htmlMessage && attachments != null) {
        for (String id : attachments.keySet()) {
            Object reference = attachments.get(id);

            if (reference instanceof File) {
                try {
                    FileSystemResource res = new FileSystemResource((File) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.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) {
                    logger.error("Error appending URL attachment: " + me.getMessage());
                }
            }
        }
    }

    // Send the email message
    try {
        mailSender.send(message);
    } catch (MailException me) {
        logger.error("Error sending email: " + me.getMessage());
        throw new ServiceException("Error sending email: " + me.getMessage());
    }
}

From source file:org.opennms.ng.services.snmpconfig.SnmpPeerFactory.java

/**
 * Private constructor/*  ww  w.  j a v a 2s  .  c  om*/
 * 
 * @exception java.io.IOException
 *                Thrown if the specified config file cannot be read
 * @exception org.exolab.castor.xml.MarshalException
 *                Thrown if the file does not conform to the schema.
 * @exception org.exolab.castor.xml.ValidationException
 *                Thrown if the contents do not match the required schema.
 */
private SnmpPeerFactory(final File configFile) throws IOException {
    this(new FileSystemResource(configFile));
}

From source file:coral.reef.web.ReefToCoralController.java

@RequestMapping(value = "/{exp}/**")
public void dispatchToExpHandler(@PathVariable("exp") String exp, HttpSession httpSession,
        HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException {

    httpResponse.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
    httpResponse.setHeader("Pragms", "no-cache");
    httpResponse.setHeader("Expires", "0");

    Integer id = (Integer) httpSession.getAttribute(REEF_ID);
    String sessionExp = (String) httpSession.getAttribute(REEF_EXP);

    String path = ((String) httpRequest.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE))
            .substring(exp.length() + 2);

    ReefHandler handler = service.handler(exp);

    if (path.startsWith(handler.startMarker())) {

        if (sessionExp != null || id != null) {
            // TODO remove old client (?)
        }//from   ww w  .j a  v a2s .c om

        String query = httpRequest.getQueryString();
        query = (query == null) ? "" : query;
        id = handler.addClient(null);
        String result = handler.process(id, path, query);
        result = service.replaceHost(exp, result);
        httpSession.setAttribute(REEF_ID, id);
        httpSession.setAttribute(REEF_EXP, exp);
        httpResponse.setContentType("text/html");
        httpResponse.getWriter().println(result);

    } else if (path.startsWith(handler.refreshMarker())) {

        if (sessionExp != null || id != null) {
            // TODO remove old client (?)
        }

        String query = httpRequest.getQueryString();
        query = (query == null) ? "" : query;
        id = Integer.parseInt(query.replaceAll("[^\\d]", ""));
        id = handler.addClient(id);
        String result = handler.process(id, "", "?refreshid=" + id);
        result = service.replaceHost(exp, result);
        httpSession.setAttribute(REEF_ID, id);
        httpSession.setAttribute(REEF_EXP, exp);
        httpResponse.setContentType("text/html");
        httpResponse.getWriter().println(result);

    } else if (path.startsWith(handler.processMarker()) && sessionExp != null && sessionExp.equals(exp)) {

        /*
         * PROCESS
         */

        String query = httpRequest.getQueryString();
        query = (query == null) ? "" : query;
        String result = handler.process(id, path, query);
        result = service.replaceHost(exp, result);
        httpResponse.setContentType("text/html");
        httpResponse.getWriter().println(result);

    } else if (path.startsWith(handler.serverMarker())) {

        /*
         * SERVER
         */

        String result = handler.server(path.substring(handler.serverMarker().length() + 1),
                httpRequest.getParameterMap());
        result = service.replaceHost(exp, result);
        httpResponse.setContentType("text/html");
        httpResponse.getWriter().println(result);

    } else if (handler.getResMap().containsKey(path)) {

        /*
         * RESOURCE
         */

        File f = handler.getResMap().get(path);
        FileSystemResource fr = new FileSystemResource(f);
        String type = servletContext.getMimeType(path);
        httpResponse.setContentType(type);

        IOUtils.copy(fr.getInputStream(), httpResponse.getOutputStream());
    } else {
        // no match = no response => should propagate to next controller
        System.out.println(path + " - " + handler.getResMap());
    }

}

From source file:com.sivalabs.jcart.admin.web.controllers.ProductController.java

@GetMapping(value = "/products/images/{productId}")
public void showProductImage(@PathVariable String productId, HttpServletRequest request,
        HttpServletResponse response) {/*from   ww  w .  j  a  v a 2  s.c o  m*/
    try {
        FileSystemResource file = new FileSystemResource(IMAGES_DIR + productId + ".jpg");
        response.setContentType("image/jpg");
        copy(file.getInputStream(), response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.netxforge.oss2.config.DiscoveryConfigFactory.java

/**
 * Private constructor/*from   ww w  . ja  va2s .  c o m*/
 * 
 * @exception java.io.IOException
 *                Thrown if the specified config file cannot be read
 * @exception org.exolab.castor.xml.MarshalException
 *                Thrown if the file does not conform to the schema.
 * @exception org.exolab.castor.xml.ValidationException
 *                Thrown if the contents do not match the required schema.
 */
private DiscoveryConfigFactory(final String configFile)
        throws IOException, MarshalException, ValidationException {
    final FileSystemResource resource = new FileSystemResource(configFile);
    setConfig(resource);
}

From source file:com.sinosoft.one.mvc.scanning.MvcScanner.java

public List<ResourceRef> getJarOrClassesFolderResources(String[] scope) throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info("[findFiles] start to found classes folders " + "or mvcd jar files by scope:"
                + Arrays.toString(scope));
    }/*w  ww  . j ava2s  . c  o  m*/
    List<ResourceRef> resources;
    if (scope == null) {
        resources = new LinkedList<ResourceRef>();
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] call 'classesFolder'");
        }
        resources.addAll(getClassesFolderResources());
        //
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] exits from 'classesFolder'");
            logger.debug("[findFiles] call 'jarFile'");
        }
        resources.addAll(getJarResources());
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] exits from 'jarFile'");
        }
    } else if (scope.length == 0) {
        return new ArrayList<ResourceRef>();
    } else {
        resources = new LinkedList<ResourceRef>();
        for (String scopeEntry : scope) {
            String packagePath = scopeEntry.replace('.', '/');
            Resource[] packageResources = resourcePatternResolver.getResources("classpath*:" + packagePath);
            for (Resource pkgResource : packageResources) {
                String uri = pkgResource.getURI().toString();
                uri = StringUtils.removeEnd(uri, "/");
                packagePath = StringUtils.removeEnd(packagePath, "/");
                uri = StringUtils.removeEnd(uri, packagePath);
                int beginIndex = uri.lastIndexOf("file:");
                if (beginIndex == -1) {
                    beginIndex = 0;
                } else {
                    beginIndex += "file:".length();
                }
                int endIndex = uri.lastIndexOf('!');
                if (endIndex == -1) {
                    endIndex = uri.length();
                }
                String path = uri.substring(beginIndex, endIndex);
                Resource folder = new FileSystemResource(path);
                ResourceRef ref = ResourceRef.toResourceRef(folder);
                if (!resources.contains(ref)) {
                    resources.add(ref);
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "[findFiles] found classes folders " + "or mvcd jar files by scope:" + ref);
                    }
                }
            }
        }
    }
    //
    if (logger.isInfoEnabled()) {
        logger.info("[findFiles] found " + resources.size() + " classes folders " + "or mvcd jar files : "
                + resources);
    }

    return resources;
}