Example usage for org.springframework.core.io UrlResource UrlResource

List of usage examples for org.springframework.core.io UrlResource UrlResource

Introduction

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

Prototype

public UrlResource(String path) throws MalformedURLException 

Source Link

Document

Create a new UrlResource based on a URL path.

Usage

From source file:org.solmix.runtime.support.spring.ContainerApplicationContext.java

@Override
protected Resource[] getConfigResources() {
    List<Resource> resources = new ArrayList<Resource>();
    if (includeDefault) {
        try {//from  w  w w .ja  v  a  2 s  .com
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                    Thread.currentThread().getContextClassLoader());

            Collections.addAll(resources, resolver.getResources(DEFAULT_CFG_FILE));

            Resource[] exts = resolver.getResources(DEFAULT_EXT_CFG_FILE);
            for (Resource r : exts) {
                InputStream is = r.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line = rd.readLine();
                while (line != null) {
                    if (!"".equals(line)) {
                        resources.add(resolver.getResource(line));
                    }
                    line = rd.readLine();
                }
                is.close();
            }

        } catch (IOException ex) {
            // ignore
        }
    }
    boolean usingDefault = false;
    if (cfgFiles == null) {
        String userConfig = System.getProperty(BeanConfigurer.USER_CFG_FILE_PROPERTY_NAME);
        if (userConfig != null) {
            cfgFiles = new String[] { userConfig };
        }
    }
    if (cfgFiles == null) {
        usingDefault = true;
        cfgFiles = new String[] { BeanConfigurer.USER_CFG_FILE };
    }
    for (String cfgFile : cfgFiles) {
        final Resource f = findResource(cfgFile);
        if (f != null && f.exists()) {
            resources.add(f);
            LOG.info("Used configed file {}", cfgFile);
        } else {
            if (!usingDefault) {
                LOG.warn("Can't find configure file {}", cfgFile);
                throw new ApplicationContextException("Can't find configure file");
            }
        }
    }
    if (cfgURLs != null) {
        for (URL u : cfgURLs) {
            UrlResource ur = new UrlResource(u);
            if (ur.exists()) {
                resources.add(ur);
            } else {
                LOG.warn("Can't find configure file {}", u.getPath());
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating application context with resources " + resources.size());
    }
    if (0 == resources.size()) {
        return null;
    }
    Resource[] res = new Resource[resources.size()];
    res = resources.toArray(res);
    return res;

}

From source file:com.sfs.dao.EmailMessageDAOImpl.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param emailMessage the email message
 *
 * @throws SFSDaoException the SFS dao exception
 *///from   www  .  ja v a 2  s . com
public final void send(final EmailMessageBean emailMessage) throws SFSDaoException {

    // Check to see whether the required fields are set (to, from, message)
    if (StringUtils.isBlank(emailMessage.getTo())) {
        throw new SFSDaoException("Error recording email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(emailMessage.getFrom())) {
        throw new SFSDaoException("Error recording email: Email requires " + "a return address");
    }
    if (StringUtils.isBlank(emailMessage.getMessage())) {
        throw new SFSDaoException("Error recording email: No email " + "message specified");
    }
    if (javaMailSender == null) {
        throw new SFSDaoException("The EmailMessageDAO has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    if (emailMessage.getHtmlMessage()) {
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new SFSDaoException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }
    if (helper == null) {
        throw new SFSDaoException("The MimeMessageHelper cannot be null");
    }
    try {
        if (StringUtils.isNotBlank(emailMessage.getTo())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getTo(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addTo(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getCC())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getCC(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addCc(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getBCC())) {
            StringTokenizer tk = new StringTokenizer(emailMessage.getBCC(), ",");
            while (tk.hasMoreTokens()) {
                String address = tk.nextToken();
                helper.addBcc(address);
            }
        }
        if (StringUtils.isNotBlank(emailMessage.getFrom())) {
            if (StringUtils.isNotBlank(emailMessage.getFromName())) {
                try {
                    helper.setFrom(emailMessage.getFrom(), emailMessage.getFromName());
                } catch (UnsupportedEncodingException uee) {
                    dataLogger.error("Error setting email from", uee);
                }
            } else {
                helper.setFrom(emailMessage.getFrom());
            }
        }
        helper.setSubject(emailMessage.getSubject());
        helper.setPriority(emailMessage.getPriority());
        if (emailMessage.getHtmlMessage()) {
            final String htmlText = emailMessage.getMessage();
            String plainText = htmlText;
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(htmlText);
            } catch (Exception e) {
                dataLogger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, htmlText);
        } else {
            helper.setText(emailMessage.getMessage());
        }
        helper.setSentDate(emailMessage.getSentDate());

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

    // Append any attachments (if an HTML email)
    if (emailMessage.getHtmlMessage()) {
        for (String id : emailMessage.getAttachments().keySet()) {
            final Object reference = emailMessage.getAttachments().get(id);

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

    // If not in debug mode send the email
    if (!debugMode) {
        deliver(emailMessage, message);
    }
}

From source file:org.solmix.runtime.support.spring.ContainerApplicationContext.java

/**
 * @param cfgFile/*from w ww  .j ava  2  s  .  c o  m*/
 * @return
 */
public static Resource findResource(final String cfgFile) {
    try {
        return AccessController.doPrivileged(new PrivilegedAction<Resource>() {

            @Override
            public Resource run() {
                Resource cpr = new ClassPathResource(cfgFile);
                if (cpr.exists()) {
                    return cpr;
                }
                try {
                    // see if it's a URL
                    URL url = new URL(cfgFile);
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        return cpr;
                    }
                } catch (MalformedURLException e) {
                    // ignore
                }
                // try loading it our way
                URL url = ClassLoaderUtils.getResource(cfgFile, ContainerApplicationContext.class);
                if (url != null) {
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        return cpr;
                    }
                }
                cpr = new FileSystemResource(cfgFile);
                if (cpr.exists()) {
                    return cpr;
                }
                return null;
            }
        });
    } catch (AccessControlException ex) {
        // cannot read the user config file
        return null;
    }
}

From source file:org.jtheque.modules.impl.ModuleServiceImpl.java

/**
 * Load the image resources of the module.
 *
 * @param module The module to load the image resources for.
 *///from  w  ww  .ja  v  a 2s  . c o m
private void loadImageResources(Module module) {
    for (ImageResource imageResource : resources.get(module).getImageResources()) {
        String resource = imageResource.getResource();

        if (resource.startsWith("classpath:")) {
            imageService.registerResource(imageResource.getName(),
                    new UrlResource(module.getBundle().getResource(resource.substring(10))));
        }
    }
}

From source file:org.opennms.ng.services.eventconfig.DefaultEventConfDao.java

public void setConfigResource(String configResource) throws IOException {

    m_configResource = new UrlResource(configResource);
    //m_configResource = configResource;
}

From source file:inti.ws.spring.resource.config.ResourceConfigProviderImpl.java

protected void update(String key) throws Exception {
    Resource configFile;//  w  ww  .  ja  va2 s. co  m
    JsonNode configNode;
    InputStream inputStream;

    LOGGER.debug("update - paths for key {}: {}", key, hostToConfigfileMapping.get(key));

    for (String path : hostToConfigfileMapping.get(key)) {

        if (path.startsWith("/")) {
            configFile = new ServletContextResource(ctx, path);
        } else {
            configFile = new UrlResource(path);
        }

        LOGGER.debug("update - updating {} for key {}", path, key);
        if (lastModifies.containsKey(path) && configFile.lastModified() <= lastModifies.get(path)) {
            LOGGER.debug("update - no newer version available for {} for key {}", path, key);
            continue;
        } else {
            lastModifies.put(path, configFile.lastModified());
        }

        inputStream = configFile.getInputStream();
        try {
            configNode = mapper.readTree(inputStream);
        } finally {
            inputStream.close();
        }

        if (configNode != null) {

            configure(key, configNode);

        }

    }

}

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

Resource getConfigurationResource() throws StoreException {
    final File config = getConfigFile();
    final Resource configResource;

    if (config.exists()) {
        configResource = new FileSystemResource(config);
    } else {//from   w  w w.j a va  2s  . com
        eventHandler.reportEvent(new WarningEvent(this, "FileStore.default.config"));
        configResource = new UrlResource(getClass().getResource("default-config.xml"));
    }

    if (!configResource.exists()) {
        throw new StoreException("Resource " + configResource + " does not exist", null);
    }
    return configResource;
}

From source file:it.geosolutions.httpproxy.service.impl.ProxyConfigImpl.java

/**
 * Reload proxy configuration reading {@link ProxyConfigImpl#locations}
 *///from  ww  w  .j a va2 s .  c  om
public void reloadProxyConfig() {
    if (locations != null) {
        for (Resource location : locations) {
            try {
                if (location.exists()) {
                    trackLocation(location);
                } else {
                    // Try to load from file system:
                    String path = null;
                    if (location instanceof ClassPathResource) {
                        // This instance is running without web context
                        path = ((ClassPathResource) location).getPath();
                    } else if (location instanceof ServletContextResource) {
                        // This instance is running in a web context
                        path = ((ServletContextResource) location).getPath();
                    }
                    if (path != null) {
                        Resource alternative = new UrlResource("file:/" + path);
                        if (alternative.exists()) {
                            trackLocation(alternative);
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, "Error overriding the proxy configuration ", e);
            }
        }
    } else {
        LOGGER.log(Level.SEVERE, "Can't observe locations for proxy configuration");
    }
}

From source file:com.epam.ta.reportportal.util.email.EmailService.java

/**
 * Finish launch notification/*from ww w . j a v  a 2  s  .com*/
 *
 * @param recipients List of recipients
 * @param url        ReportPortal URL
 * @param launch     Launch
 */
public void sendLaunchFinishNotification(final String[] recipients, final String url, final Launch launch,
        final Project.Configuration settings) {
    String subject = String.format(FINISH_LAUNCH_EMAIL_SUBJECT, launch.getName(), launch.getNumber());
    MimeMessagePreparator preparator = mimeMessage -> {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");
        message.setSubject(subject);
        message.setTo(recipients);
        setFrom(message);

        Map<String, Object> email = new HashMap<>();
        /* Email fields values */
        email.put("name", launch.getName());
        email.put("number", String.valueOf(launch.getNumber()));
        email.put("description", launch.getDescription());
        email.put("url", url);

        /* Launch execution statistics */
        email.put("total", launch.getStatistics().getExecutionCounter().getTotal().toString());
        email.put("passed", launch.getStatistics().getExecutionCounter().getPassed().toString());
        email.put("failed", launch.getStatistics().getExecutionCounter().getFailed().toString());
        email.put("skipped", launch.getStatistics().getExecutionCounter().getSkipped().toString());

        /* Launch issue statistics global counters */
        email.put("productBugTotal", launch.getStatistics().getIssueCounter().getProductBugTotal().toString());
        email.put("automationBugTotal",
                launch.getStatistics().getIssueCounter().getAutomationBugTotal().toString());
        email.put("systemIssueTotal",
                launch.getStatistics().getIssueCounter().getSystemIssueTotal().toString());
        email.put("noDefectTotal", launch.getStatistics().getIssueCounter().getNoDefectTotal().toString());
        email.put("toInvestigateTotal",
                launch.getStatistics().getIssueCounter().getToInvestigateTotal().toString());

        /* Launch issue statistics custom sub-types */
        if (launch.getStatistics().getIssueCounter().getProductBug().entrySet().size() > 1) {
            Map<StatisticSubType, String> pb = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getProductBug().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    pb.put(settings.getByLocator(k), v.toString());
            });
            email.put("pbInfo", pb);
        }
        if (launch.getStatistics().getIssueCounter().getAutomationBug().entrySet().size() > 1) {
            Map<StatisticSubType, String> ab = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getAutomationBug().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    ab.put(settings.getByLocator(k), v.toString());
            });
            email.put("abInfo", ab);
        }
        if (launch.getStatistics().getIssueCounter().getSystemIssue().entrySet().size() > 1) {
            Map<StatisticSubType, String> si = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getSystemIssue().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    si.put(settings.getByLocator(k), v.toString());
            });
            email.put("siInfo", si);
        }
        if (launch.getStatistics().getIssueCounter().getNoDefect().entrySet().size() > 1) {
            Map<StatisticSubType, String> nd = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getNoDefect().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    nd.put(settings.getByLocator(k), v.toString());
            });
            email.put("ndInfo", nd);
        }
        if (launch.getStatistics().getIssueCounter().getToInvestigate().entrySet().size() > 1) {
            Map<StatisticSubType, String> ti = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getToInvestigate().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    ti.put(settings.getByLocator(k), v.toString());
            });
            email.put("tiInfo", ti);
        }

        String text = templateEngine.merge("finish-launch-template.vm", email);
        message.setText(text, true);
        message.addInline("logoimg", new UrlResource(getClass().getClassLoader().getResource(LOGO)));
    };
    this.send(preparator);
}

From source file:com.liferay.portal.service.impl.ThemeLocalServiceImpl.java

public List<String> init(String servletContextName, ServletContext servletContext, String themesPath,
        boolean loadFromServletContext, String[] xmls, PluginPackage pluginPackage) {

    List<String> themeIdsList = new ArrayList<String>();

    try {//from ww  w . jav a 2  s .  c  om
        for (int i = 0; i < xmls.length; i++) {
            Set<String> themeIds = _readThemes(servletContextName, servletContext, themesPath,
                    loadFromServletContext, xmls[i], pluginPackage);

            for (String themeId : themeIds) {
                if (!themeIdsList.contains(themeId)) {
                    themeIdsList.add(themeId);
                }
            }
        }

        Set<String> themeIds = new HashSet<String>();
        ClassLoader classLoader = getClass().getClassLoader();
        // load xmls
        String resourceName = "WEB-INF/liferay-look-and-feel-ext.xml";
        Enumeration<URL> resources = classLoader.getResources(resourceName);
        if (_log.isDebugEnabled() && !resources.hasMoreElements()) {
            _log.debug("No " + resourceName + " has been found");
        }
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (_log.isDebugEnabled()) {
                _log.debug("Loading " + resourceName + " from: " + resource);
            }

            if (resource == null) {
                continue;
            }

            InputStream is = new UrlResource(resource).getInputStream();
            try {
                String xmlExt = IOUtils.toString(is, "UTF-8");
                themeIds.addAll(_readThemes(servletContextName, servletContext, themesPath,
                        loadFromServletContext, xmlExt, pluginPackage));
            } catch (Exception e) {
                _log.error("Problem while loading file " + resource, e);
            } finally {
                is.close();
            }
        }

        for (String themeId : themeIds) {
            if (!themeIdsList.contains(themeId)) {
                themeIdsList.add(themeId);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    _themesPool.clear();

    return themeIdsList;
}