Example usage for org.springframework.core.io ResourceEditor setAsText

List of usage examples for org.springframework.core.io ResourceEditor setAsText

Introduction

In this page you can find the example usage for org.springframework.core.io ResourceEditor setAsText.

Prototype

@Override
    public void setAsText(String text) 

Source Link

Usage

From source file:com.joshlong.esb.springintegration.modules.net.sftp.config.SFTPMessageSourceFactoryBean.java

@Override
protected SFTPMessageSource createInstance() throws Exception {
    try {/*  ww w  .j  a v  a 2s .  c  o  m*/
        if ((localWorkingDirectory == null) || StringUtils.isEmpty(localWorkingDirectory)) {
            File tmp = SystemUtils.getJavaIoTmpDir();
            File sftpTmp = new File(tmp, "sftpInbound");
            this.localWorkingDirectory = "file://" + sftpTmp.getAbsolutePath();
        }
        assert !StringUtils
                .isEmpty(this.localWorkingDirectory) : "the local working directory mustn't be null!";

        // resource for local directory
        ResourceEditor editor = new ResourceEditor(this.resourceLoader);
        editor.setAsText(this.localWorkingDirectory);
        this.localDirectoryResource = (Resource) editor.getValue();

        fileReadingMessageSource = new FileReadingMessageSource();

        synchronizer = new SFTPInboundSynchronizer();

        if (null == taskScheduler) {
            Map<String, TaskScheduler> tss = null;

            if ((tss = applicationContext.getBeansOfType(TaskScheduler.class)).keySet().size() != 0) {
                taskScheduler = tss.get(tss.keySet().iterator().next());
            }
        }

        if (null == taskScheduler) {
            ThreadPoolTaskScheduler ts = new ThreadPoolTaskScheduler();
            ts.setPoolSize(10);
            ts.setErrorHandler(new ErrorHandler() {
                public void handleError(Throwable t) {
                    // todo make this forward a message onto the error channel (how does that work?)
                    logger.debug("error! ", t);
                }
            });

            ts.setWaitForTasksToCompleteOnShutdown(true);
            ts.initialize();
            this.taskScheduler = ts;
        }

        SFTPSessionFactory sessionFactory = SFTPSessionUtils.buildSftpSessionFactory(this.getHost(),
                this.getPassword(), this.getUsername(), this.getKeyFile(), this.getKeyFilePassword(),
                this.getPort());

        QueuedSFTPSessionPool pool = new QueuedSFTPSessionPool(15, sessionFactory);
        pool.afterPropertiesSet();
        synchronizer.setRemotePath(this.getRemoteDirectory());
        synchronizer.setPool(pool);
        synchronizer.setAutoCreatePath(this.isAutoCreateDirectories());
        synchronizer.setShouldDeleteDownloadedRemoteFiles(this.isAutoDeleteRemoteFilesOnSync());

        SFTPMessageSource sftpMessageSource = new SFTPMessageSource(fileReadingMessageSource, synchronizer);

        sftpMessageSource.setTaskScheduler(taskScheduler);

        if (null != this.trigger) {
            sftpMessageSource.setTrigger(trigger);
        }

        sftpMessageSource.setLocalDirectory(this.localDirectoryResource);
        sftpMessageSource.afterPropertiesSet();
        sftpMessageSource.start();

        return sftpMessageSource;
    } catch (Throwable thr) {
        logger.debug("error occurred when trying to configure SFTPmessageSource ", thr);
    }

    return null;
}

From source file:org.jspringbot.keyword.db.DbHelper.java

public void init() {
    ResourceEditor editor = new ResourceEditor();
    editor.setAsText("classpath:db-queries/");
    Resource dbDirResource = (Resource) editor.getValue();

    boolean hasDBDirectory = true;
    boolean hasDBProperties = true;

    if (dbDirResource != null) {
        try {/*from   w w  w .  j  a va2s . c  o m*/
            File configDir = dbDirResource.getFile();

            if (configDir.isDirectory()) {
                File[] propertiesFiles = configDir.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        return StringUtils.endsWith(file.getName(), ".properties")
                                || StringUtils.endsWith(file.getName(), ".xml");
                    }
                });

                for (File propFile : propertiesFiles) {
                    addExternalQueries(propFile);
                }
            }
        } catch (IOException ignore) {
            hasDBDirectory = false;
        }
    }

    editor.setAsText("classpath:db-queries.properties");
    Resource dbPropertiesResource = (Resource) editor.getValue();

    if (dbPropertiesResource != null) {
        try {
            if (dbPropertiesResource.getFile().isFile()) {
                addExternalQueries(dbPropertiesResource.getFile());
            }
        } catch (IOException e) {
            hasDBProperties = false;
        }
    }

    editor.setAsText("classpath:db-queries.xml");
    Resource dbXMLResource = (Resource) editor.getValue();

    if (dbXMLResource != null && !hasDBProperties) {
        try {
            if (dbXMLResource.getFile().isFile()) {
                addExternalQueries(dbXMLResource.getFile());
            }
        } catch (IOException e) {
            hasDBProperties = false;
        }
    }

    if (!hasDBDirectory && !hasDBProperties) {
        LOGGER.warn("No query sources found.");
    }

    begin();
}

From source file:org.jspringbot.keyword.config.ConfigHelper.java

public void init() throws IOException {
    ResourceEditor editor = new ResourceEditor();
    editor.setAsText("classpath:config/");
    Resource configDirResource = (Resource) editor.getValue();

    boolean hasConfigDirectory = true;
    boolean hasConfigProperties = true;

    if (configDirResource != null) {
        try {// w  w  w.j av  a 2 s.co m
            File configDir = configDirResource.getFile();

            if (configDir.isDirectory()) {
                File[] propertiesFiles = configDir.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        return StringUtils.endsWith(file.getName(), ".properties")
                                || StringUtils.endsWith(file.getName(), ".xml");
                    }
                });

                for (File propFile : propertiesFiles) {
                    String filename = propFile.getName();
                    String name = StringUtils.substring(filename, 0, StringUtils.indexOf(filename, "."));

                    addProperties(name, propFile);
                }
            }
        } catch (IOException e) {
            hasConfigDirectory = false;
        }
    }

    editor.setAsText("classpath:config.properties");
    Resource configPropertiesResource = (Resource) editor.getValue();

    if (configPropertiesResource != null) {
        try {
            File configPropertiesFile = configPropertiesResource.getFile();

            if (configPropertiesFile.isFile()) {
                Properties configs = new Properties();

                configs.load(new FileReader(configPropertiesFile));

                for (Map.Entry entry : configs.entrySet()) {
                    String name = (String) entry.getKey();
                    editor.setAsText(String.valueOf(entry.getValue()));

                    try {
                        Resource resource = (Resource) editor.getValue();
                        addProperties(name, resource.getFile());
                    } catch (Exception e) {
                        throw new IOException(String.format("Unable to load config '%s'.", name), e);
                    }
                }
            }
        } catch (IOException e) {
            hasConfigProperties = false;
        }
    }

    if (!hasConfigDirectory && !hasConfigProperties) {
        LOGGER.warn("No configuration found.");
    }
}

From source file:org.jspringbot.keyword.csv.CSVState.java

public void parseCSVResource(String resource) throws IOException {
    ResourceEditor editor = new ResourceEditor();
    editor.setAsText(resource);

    Resource r = (Resource) editor.getValue();

    readAll(new InputStreamReader(r.getInputStream()));

    LOG.createAppender().appendBold("Parse CSV Resource:").append(" (count=%d)", CollectionUtils.size(lines))
            .appendText(toCSV(lines)).log();
}

From source file:org.jspringbot.keyword.json.JSONHelper.java

public void setJsonString(String jsonString) throws IOException {
    if (StringUtils.startsWith(jsonString, "file:") || StringUtils.startsWith(jsonString, "classpath:")) {
        ResourceEditor editor = new ResourceEditor();
        editor.setAsText(jsonString);
        Resource resource = (Resource) editor.getValue();

        jsonString = new String(IOUtils.toCharArray(resource.getInputStream(), CharEncoding.UTF_8));
    }// ww  w.  j  av a 2 s .co m

    if (!StringUtils.startsWith(jsonString, "[") || !StringUtils.startsWith(jsonString, "{")) {
        //   LOG.warn("jsonString starts with an invalid character. trying to recover...");

        for (int i = 0; i < jsonString.length(); i++) {
            if (jsonString.charAt(i) == '{' || jsonString.charAt(i) == '[') {
                jsonString = jsonString.substring(i);
                break;
            }
        }
    }

    try {
        LOG.createAppender().appendBold("JSON String:").appendJSON(prettyPrint(jsonString)).log();
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }

    this.jsonString = jsonString;
}

From source file:org.jspringbot.keyword.selenium.SeleniumHelper.java

public Object executeJavascript(String code) throws IOException {
    HighlightRobotLogger.HtmlAppender appender = LOG.createAppender().appendBold("Execute Javascript:");

    if (StringUtils.startsWith(code, "file:") || StringUtils.startsWith(code, "classpath:")) {
        appender.appendProperty("Resource", code);
        ResourceEditor editor = new ResourceEditor();
        editor.setAsText(code);
        Resource resource = (Resource) editor.getValue();

        code = new String(IOUtils.toCharArray(resource.getInputStream()));
    }//from w  w w.ja v  a 2s.c o  m

    appender.appendJavascript(code);
    appender.log();

    return executor.executeScript(code);
}

From source file:org.jspringbot.keyword.xml.XMLHelper.java

public void setXmlString(String xmlString) throws IOException, SAXException {
    this.xmlString = xmlString;

    if (StringUtils.startsWith(xmlString, "file:") || StringUtils.startsWith(xmlString, "classpath:")) {
        ResourceEditor editor = new ResourceEditor();
        editor.setAsText(xmlString);
        Resource resource = (Resource) editor.getValue();

        xmlString = new String(IOUtils.toCharArray(resource.getInputStream()));
    }/*from www  . j ava  2  s .  c  o m*/

    DOMParser parser = new DOMParser();
    parser.parse(new InputSource(new StringReader(xmlString)));

    LOG.createAppender().appendBold("XML String:").appendXML(XMLFormatter.prettyPrint(xmlString)).log();

    this.document = parser.getDocument();
}

From source file:org.mule.config.spring.jndi.SpringInitialContextFactory.java

public Context getInitialContext(Hashtable environment) throws NamingException {
    if (singleton != null) {
        return singleton;
    }/*from  w ww .j ava2  s.  c o  m*/
    Resource resource = null;
    Object value = environment.get(Context.PROVIDER_URL);
    String key = "jndi.xml";
    if (value == null) {
        resource = new ClassPathResource(key);
    } else {
        if (value instanceof Resource) {
            resource = (Resource) value;
        } else {
            ResourceEditor editor = new ResourceEditor();
            key = value.toString();
            editor.setAsText(key);
            resource = (Resource) editor.getValue();
        }
    }
    BeanFactory context = loadContext(resource, key);
    Context answer = (Context) context.getBean("jndi");
    if (answer == null) {
        log.warn("No JNDI context available in JNDI resource: " + resource);
        answer = new DefaultSpringJndiContext(environment, new ConcurrentHashMap());
    }
    return answer;
}