List of usage examples for org.springframework.core.io UrlResource UrlResource
public UrlResource(String path) throws MalformedURLException
From source file:com.enonic.cms.core.plugin.container.OsgiContainer.java
private void copyFrameworkJar(final File targetFile) throws Exception { URL location = FrameworkProperties.class.getProtectionDomain().getCodeSource().getLocation(); final String locationFile = location.getFile(); LOG.info("Location of framework.jar : " + locationFile); if (locationFile.endsWith(".jar!/")) // for IBM Websphere 8.5 Liberty Profile {// www. j a va 2 s . c o m String absolutePath = locationFile.substring(0, locationFile.length() - 2); location = new URL(absolutePath); } else if (ResourceUtils.URL_PROTOCOL_VFS.equals(location.getProtocol())) // JBOSS 7.1.1 VFS { final URI uri = ResourceUtils.toURI(location); final UrlResource urlResource = new UrlResource(uri); final File file = urlResource.getFile(); String absolutePath = file.getAbsolutePath(); if (!absolutePath.endsWith(urlResource.getFilename())) { // removing /contents folder from path and adding unpacked jar to path. absolutePath = absolutePath.substring(0, absolutePath.length() - VFS_CONTENTS_FOLDER.length()) + urlResource.getFilename(); } final StringBuilder stringBuilder = new StringBuilder("file:/"); if (!SystemUtils.IS_OS_WINDOWS) // windows already has one slash in path like /c:/Program Files/.... { stringBuilder.append('/'); } stringBuilder.append(absolutePath); location = new URL(stringBuilder.toString()); } LOG.info("Copying " + location.toString() + " to " + targetFile.toString()); Files.copy(Resources.newInputStreamSupplier(location), targetFile); }
From source file:org.codehaus.griffon.commons.GriffonResourceUtils.java
public static Resource getAppDir(Resource resource) { if (resource == null) return null; try {//from w w w . java 2s . c o m String url = resource.getURL().toString(); int i = url.lastIndexOf(GRIFFON_APP_DIR); if (i > -1) { url = url.substring(0, i + 10); return new UrlResource(url); } return null; } catch (MalformedURLException e) { return null; } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Error reading URL whilst resolving app dir from [" + resource + "]: " + e.getMessage(), e); } return null; } }
From source file:com.baomidou.mybatisplus.spring.MybatisMapperRefresh.java
public void run() { final GlobalConfiguration mybatisGlobalCache = GlobalConfiguration.GlobalConfig(configuration); /*/*from w ww. j a va 2 s . co m*/ * ? XML */ if (enabled) { beforeTime = SystemClock.now(); final MybatisMapperRefresh runnable = this; new Thread(new Runnable() { public void run() { if (fileSet == null) { fileSet = new HashSet<String>(); for (Resource mapperLocation : mapperLocations) { try { if (ResourceUtils.isJarURL(mapperLocation.getURL())) { String key = new UrlResource( ResourceUtils.extractJarFileURL(mapperLocation.getURL())).getFile() .getPath(); fileSet.add(key); if (jarMapper.get(key) != null) { jarMapper.get(key).add(mapperLocation); } else { List<Resource> resourcesList = new ArrayList<Resource>(); resourcesList.add(mapperLocation); jarMapper.put(key, resourcesList); } } else { fileSet.add(mapperLocation.getFile().getPath()); } } catch (IOException ioException) { ioException.printStackTrace(); } } } try { Thread.sleep(delaySeconds * 1000); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } while (true) { try { for (String filePath : fileSet) { File file = new File(filePath); if (file != null && file.isFile() && file.lastModified() > beforeTime) { mybatisGlobalCache.setRefresh(true); List<Resource> removeList = jarMapper.get(filePath); if (removeList != null && !removeList.isEmpty()) {// jarxmljarxml??jar?xml for (Resource resource : removeList) { runnable.refresh(resource); } } else { runnable.refresh(new FileSystemResource(file)); } } } if (mybatisGlobalCache.isRefresh()) { beforeTime = SystemClock.now(); } mybatisGlobalCache.setRefresh(true); } catch (Exception exception) { exception.printStackTrace(); } try { Thread.sleep(sleepSeconds * 1000); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } } } }, "mybatis-plus MapperRefresh").start(); } }
From source file:net.sf.juffrou.reflect.spring.BeanWrapperGenericsTests.java
@Test public void testGenericListElement() throws MalformedURLException { GenericBean<?> gb = new GenericBean<Object>(); gb.setResourceList(new ArrayList<Resource>()); BeanWrapper bw = new JuffrouSpringBeanWrapper(gb); bw.setPropertyValue("resourceList[0]", "http://localhost:8080"); assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); }
From source file:com.francetelecom.clara.cloud.commons.JndiAwarePropertyPlaceholderConfigurer.java
/** * Takes an array or Resources and for any of type UrlResource, resolves any * properties in the URL. Note that as we haven't loaded the property fiels * at this stage we are resolving properties against the system and jndi * sets (if any)/*from www . ja va2 s .c o m*/ * * @param locations */ @SuppressWarnings("unchecked") private void processLocationValues(Resource[] locations) { if (locations != null) { Properties props = new Properties(); HashSet visitedPlaceholders = new HashSet(); for (int i = 0; i < locations.length; i++) { if (locations[i] instanceof UrlResource) { UrlResource file = (UrlResource) locations[i]; String path; try { path = file.getURL().toString(); } catch (IOException e) { throw new RuntimeException(e); } String value = parseStringValue(path, props, visitedPlaceholders); if (!StringUtils.equals(path, value)) { UrlResource newFile; try { newFile = new UrlResource(value); } catch (MalformedURLException e) { throw new RuntimeException(e); } locations[i] = newFile; } } } } }
From source file:com.liferay.portal.spring.hibernate.PortalHibernateConfiguration.java
protected void readResource(Configuration configuration, String resource) throws Exception { ClassLoader classLoader = getConfigurationClassLoader(); if (!resource.startsWith("classpath*:")) { InputStream is = classLoader.getResourceAsStream(resource); readResource(configuration, resource, is); } else {//www.ja v a2 s . co m String resourceName = resource.substring("classpath*:".length()); try { Enumeration<URL> resources = classLoader.getResources(resourceName); if (_log.isDebugEnabled() && !resources.hasMoreElements()) { _log.debug("No " + resourceName + " has been found"); } while (resources.hasMoreElements()) { URL resourceFullName = resources.nextElement(); try { InputStream is = new UrlResource(resourceFullName).getInputStream(); readResource(configuration, resource, is); } catch (Exception e2) { if (_log.isWarnEnabled()) { _log.warn("Problem while loading " + resource, e2); } } } } catch (Exception e2) { if (_log.isWarnEnabled()) { _log.warn("Problem while loading classLoader resources: " + resourceName, e2); } } } }
From source file:org.biopax.validator.ws.ValidatorController.java
/** * JSP pages and RESTful web services controller, the main one that checks BioPAX data. * All parameter names are important, i.e., these are part of public API (for clients) * //www.ja v a 2 s . c o m * Framework's built-in parameters: * @param request the web request object (may contain multi-part data, i.e., multiple files uploaded) * @param response * @param mvcModel Spring MVC Model * @param writer HTTP response writer * * BioPAX Validator/Normalizer query parameters: * @param url * @param retDesired * @param autofix * @param filter * @param maxErrors * @param profile * @param normalizer binds to three boolean options: normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource * @return * @throws IOException */ @RequestMapping(value = "/check", method = RequestMethod.POST) public String check(HttpServletRequest request, HttpServletResponse response, Model mvcModel, Writer writer, @RequestParam(required = false) String url, @RequestParam(required = false) String retDesired, @RequestParam(required = false) Boolean autofix, @RequestParam(required = false) Behavior filter, @RequestParam(required = false) Integer maxErrors, @RequestParam(required = false) String profile, //normalizer!=null when called from the JSP; //but it's usually null when from the validator-client or a web script @ModelAttribute("normalizer") Normalizer normalizer) throws IOException { Resource resource = null; // a resource to validate // create the response container ValidatorResponse validatorResponse = new ValidatorResponse(); if (url != null && url.length() > 0) { if (url != null) log.info("url : " + url); try { resource = new UrlResource(url); } catch (MalformedURLException e) { mvcModel.addAttribute("error", e.toString()); return "check"; } try { Validation v = execute(resource, resource.getDescription(), maxErrors, autofix, filter, profile, normalizer); validatorResponse.addValidationResult(v); } catch (Exception e) { return errorResponse(mvcModel, "check", "Exception: " + e); } } else if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Map files = multiRequest.getFileMap(); Assert.state(!files.isEmpty(), "No files to validate"); for (Object o : files.values()) { MultipartFile file = (MultipartFile) o; String filename = file.getOriginalFilename(); // a workaround (for some reason there is always a no-name-file; // this might be a javascript isue) if (file.getBytes().length == 0 || filename == null || "".equals(filename)) continue; log.info("check : " + filename); resource = new ByteArrayResource(file.getBytes()); try { Validation v = execute(resource, filename, maxErrors, autofix, filter, profile, normalizer); validatorResponse.addValidationResult(v); } catch (Exception e) { return errorResponse(mvcModel, "check", "Exception: " + e); } } } else { return errorResponse(mvcModel, "check", "No BioPAX input source provided!"); } if ("xml".equalsIgnoreCase(retDesired)) { response.setContentType("application/xml"); ValidatorUtils.write(validatorResponse, writer, null); } else if ("html".equalsIgnoreCase(retDesired)) { /* could also use ValidatorUtils.write with a xml-to-html xslt source but using JSP here makes it easier to keep the same style, header, footer*/ mvcModel.addAttribute("response", validatorResponse); return "groupByCodeResponse"; } else { // owl only response.setContentType("text/plain"); // write all the OWL results one after another TODO any better solution? for (Validation result : validatorResponse.getValidationResult()) { if (result.getModelData() != null) writer.write(result.getModelData() + NEWLINE); else // empty result writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<rdf:RDF></rdf:RDF>" + NEWLINE); } } return null; // (Writer is used instead) }
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 ww w . jav 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:com.gzj.tulip.load.ResourceRef.java
public Resource getInnerResource(String subPath) throws IOException { Assert.isTrue(!subPath.startsWith("/")); String rootPath = resource.getURI().getPath(); if (getProtocol().equals("jar")) { return new UrlResource("jar:file:" + rootPath + "!/" + subPath); } else {//from www .j a va2s .c o m return new FileSystemResource(rootPath + subPath); // FileSystemResource?file: } }
From source file:org.solmix.runtime.support.spring.ContainerXmlBeanDefinitionReader.java
private int fastInfosetLoadBeanDefinitions(EncodedResource encodedResource) throws IOException, StaleFastinfosetException, ParserConfigurationException, XMLStreamException { URL resUrl = encodedResource.getResource().getURL(); // There are XML files scampering around that don't end in .xml. // We don't apply the optimization to them. if (!resUrl.getPath().endsWith(".xml")) { throw new StaleFastinfosetException(); }//from w w w.j a v a 2 s . co m String fixmlPath = resUrl.getPath().replaceFirst("\\.xml$", ".fixml"); String protocol = resUrl.getProtocol(); // beware of the relative URL rules for jar:, which are surprising. if ("jar".equals(protocol)) { fixmlPath = fixmlPath.replaceFirst("^.*!", ""); } URL fixmlUrl = new URL(resUrl, fixmlPath); // if we are in unpacked files, we take some extra time // to ensure that we aren't using a stale Fastinfoset file. if ("file".equals(protocol)) { URLConnection resCon = null; URLConnection fixCon = null; resCon = resUrl.openConnection(); fixCon = fixmlUrl.openConnection(); if (resCon.getLastModified() > fixCon.getLastModified()) { throw new StaleFastinfosetException(); } } Resource newResource = new UrlResource(fixmlUrl); Document doc = TunedDocumentLoader.loadFastinfosetDocument(fixmlUrl); if (doc == null) { //something caused FastinfoSet to not be able to read the doc throw new StaleFastinfosetException(); } return registerBeanDefinitions(doc, newResource); }