List of usage examples for org.springframework.core.io UrlResource UrlResource
public UrlResource(String path) throws MalformedURLException
From source file:org.jahia.services.modulemanager.util.ModuleUtils.java
/** * Load the bundle .jar resource./*from w ww .j a v a2s. c o m*/ * * @param bundle the bundle to be loaded * @return the bundle resource * @throws java.net.MalformedURLException */ public static Resource loadBundleResource(Bundle bundle) throws MalformedURLException { try { Resource bundleResource = null; File bundleFile = getBundleFile(bundle); if (bundleFile != null) { bundleResource = new FileSystemResource(bundleFile); } else { bundleResource = new UrlResource(bundle.getLocation()); } return bundleResource; } catch (Exception e) { if (e instanceof ModuleManagementException) { // re-throw throw (ModuleManagementException) e; } String msg = "Unable to load bundle resource using location " + bundle.getLocation() + ". Cause: " + e.getMessage(); logger.error(msg, e); throw new ModuleManagementException(msg, e); } }
From source file:org.josso.tooling.gshell.core.spring.GShellApplicationContext.java
@Override protected Resource[] getConfigResources() { List<Resource> resources = new ArrayList<Resource>(); try {//w w w . j av a2 s .c o m PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( Thread.currentThread().getContextClassLoader()); Collections.addAll(resources, resolver.getResources(DEFAULT_JOSSO_GSHELL_CFG_FILE)); } catch (IOException ex) { // ignore } if (null == cfgFiles) { cfgFiles = new String[] { "josso-gshell.xml" }; } for (String cfgFile : cfgFiles) { boolean found = false; Resource cpr = new ClassPathResource(cfgFile); if (!cpr.exists()) { try { //see if it's a URL URL url = new URL(cfgFile); cpr = new UrlResource(url); if (cpr.exists()) { resources.add(cpr); found = true; } } catch (MalformedURLException e) { //ignore } if (!found) { //try loading it our way URL url = getResource(cfgFile, this.getClass()); if (url != null) { cpr = new UrlResource(url); if (cpr.exists()) { resources.add(cpr); found = true; } } } } else { resources.add(cpr); found = true; } if (!found) { logger.warn("No Process Descriptor found: " + cfgFile); } } if (null != cfgFileURLs) { for (URL cfgFileURL : cfgFileURLs) { UrlResource ur = new UrlResource(cfgFileURL); if (ur.exists()) { resources.add(ur); } else { logger.warn("No Process Descriptor found: " + cfgFileURL); } } } logger.info("Creating application context with resources: " + resources); if (0 == resources.size()) { return null; } Resource[] res = new Resource[resources.size()]; res = resources.toArray(res); return res; }
From source file:org.kuali.kfs.module.tem.batch.PerDiemXmlInputFileType.java
/** * @see org.kuali.kfs.sys.batch.XmlBatchInputFileTypeBase#validateContentsAgainstSchema(java.lang.String, java.io.InputStream) *//*w w w. j a v a 2s.c o m*/ @Override protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents) throws ParseException { try { // get schemaFile UrlResource schemaResource = new UrlResource(schemaLocation); // load a WXS schema, represented by a Schema instance Source schemaSource = new StreamSource(schemaResource.getInputStream()); // create a SchemaFactory capable of understanding WXS schemas SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(schemaSource); // create a validator instance, which can be used to validate an instance document Validator validator = schema.newValidator(); validator.setErrorHandler(new XmlErrorHandler()); Source source = this.transform(fileContents); validator.validate(source); } catch (MalformedURLException e2) { LOG.error("error getting schema url: " + e2.getMessage()); throw new RuntimeException("error getting schema url: " + e2.getMessage(), e2); } catch (SAXException e) { LOG.error("error encountered while parsing xml " + e.getMessage()); throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e); } catch (IOException e1) { LOG.error("error occured while validating file contents: " + e1.getMessage()); throw new RuntimeException("error occurred while validating file contents: " + e1.getMessage(), e1); } }
From source file:org.kuali.ole.sys.batch.XmlBatchInputFileTypeBase.java
/** * Validates the xml contents against the batch input type schema using the java 1.5 validation package. * //from w w w.j av a2 s . c o m * @param schemaLocation - location of the schema file * @param fileContents - xml contents to validate against the schema */ protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents) throws ParseException { // create a SchemaFactory capable of understanding WXS schemas SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // get schemaFile UrlResource schemaResource = null; try { schemaResource = new UrlResource(schemaLocation); } catch (MalformedURLException e2) { LOG.error("error getting schema url: " + e2.getMessage()); throw new RuntimeException("error getting schema url: " + e2.getMessage(), e2); } // load a WXS schema, represented by a Schema instance Source schemaSource = null; try { schemaSource = new StreamSource(schemaResource.getInputStream()); } catch (IOException e2) { LOG.error("error getting schema stream from url: " + e2.getMessage()); throw new RuntimeException("error getting schema stream from url: " + e2.getMessage(), e2); } Schema schema = null; try { schema = factory.newSchema(schemaSource); } catch (SAXException e) { LOG.error("error occured while setting schema file: " + e.getMessage()); throw new RuntimeException("error occured while setting schema file: " + e.getMessage(), e); } // create a Validator instance, which can be used to validate an instance document Validator validator = schema.newValidator(); validator.setErrorHandler(new XmlErrorHandler()); // validate try { validator.validate(new StreamSource(fileContents)); } catch (SAXException e) { LOG.error("error encountered while parsing xml " + e.getMessage()); throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e); } catch (IOException e1) { LOG.error("error occured while validating file contents: " + e1.getMessage()); throw new RuntimeException("error occured while validating file contents: " + e1.getMessage(), e1); } }
From source file:org.ldp4j.server.utils.spring.MonitorizedPropertyPlaceholderConfigurerTest.java
@Before public void setUp() throws Exception { Properties property = new Properties(); property.setProperty("finalProperty", "other value"); File tmpFile = folder.newFile("dynamicValues.cfg"); OutputStream out = null;/*from ww w .jav a 2s .c o m*/ try { out = new FileOutputStream(tmpFile); property.store(out, "Test values"); } finally { out.close(); } File otherFile = folder.newFile("otherValues.cfg"); property.setProperty("finalProperty", "my value"); try { out = new FileOutputStream(otherFile); property.store(out, "Other test values"); } finally { out.close(); } this.customResource = CustomInputStreamResource.create(otherFile); this.locations = new Resource[] { new FileSystemResource(tmpFile), new ClassPathResource("resource.properties"), new ClassPathResource("nonExistingResource.properties"), this.customResource, new UrlResource(this.getClass().getResource("/otherResource.cfg")), new OsgiBundleResource(new CustomBundle(BUNDLE_ID, BUNDLE_SYMBOLIC_NAME), "/path") }; }
From source file:org.openadaptor.spring.SpringAdaptor.java
private void loadBeanDefinitionsFromUrl(String url, GenericApplicationContext context) { BeanDefinitionReader reader = null;/*from w w w . j a v a 2 s . c o m*/ if (url.endsWith(".xml")) { reader = new XmlBeanDefinitionReader(context); } else if (url.endsWith(".properties")) { reader = new PropertiesBeanDefinitionReader(context); } if (reader != null) { try { reader.loadBeanDefinitions(new UrlResource(url)); } catch (BeansException e) { log.error("error", e); throw new RuntimeException("BeansException : " + e.getMessage()); } catch (MalformedURLException e) { log.error("error", e); throw new RuntimeException("MalformedUrlException : " + e.getMessage()); } } else { throw new RuntimeException("No BeanDefinitionReader associated with " + url); } }
From source file:org.openadaptor.util.SystemTestUtil.java
/** * Runs adaptor using a given Spring config file. * //from w ww . j a va 2 s .c o m * @param caller calling object * @param resourceLocation path to the config file. * @param configFile adaptor's Spring config file * @return an instance of adaptor that was executed * @throws Exception */ public static SpringAdaptor runAdaptor(Object caller, String resourceLocation, String configFile) throws Exception { SpringAdaptor adaptor = new SpringAdaptor(); UrlResource urlResource = new UrlResource( "file:" + ResourceUtil.getResourcePath(caller, resourceLocation, configFile)); String configPath = urlResource.getFile().getAbsolutePath(); adaptor.addConfigUrl(configPath); adaptorRun(adaptor); return adaptor; }
From source file:org.openmrs.test.StartModuleExecutionListener.java
/** * called before @BeforeTransaction methods * // w w w. ja v a 2 s .c o m * @see org.springframework.test.context.support.AbstractTestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext) */ @Override public void prepareTestInstance(TestContext testContext) throws Exception { StartModule startModuleAnnotation = testContext.getTestClass().getAnnotation(StartModule.class); // if the developer listed some modules with the @StartModule annotation on the class if (startModuleAnnotation != null) { if (!lastClassRun.equals(testContext.getTestClass().getSimpleName())) { // mark this with our class so that the services are only restarted once lastClassRun = testContext.getTestClass().getSimpleName(); if (!Context.isSessionOpen()) Context.openSession(); ModuleUtil.shutdown(); // load the omods that the dev defined for this class String modulesToLoad = StringUtils.join(startModuleAnnotation.value(), " "); Properties props = BaseContextSensitiveTest.runtimeProperties; props.setProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD, modulesToLoad); try { ModuleUtil.startup(props); } catch (Exception e) { System.out.println("Error while starting modules: "); e.printStackTrace(System.out); throw e; } Assert.assertTrue( "Some of the modules did not start successfully for " + testContext.getTestClass().getSimpleName() + ". Only " + ModuleFactory.getStartedModules().size() + " modules started instead of " + startModuleAnnotation.value().length, startModuleAnnotation.value().length <= ModuleFactory.getStartedModules().size()); /* * Refresh spring so the Services are recreated (aka serializer gets put into the SerializationService) * To do this, wrap the applicationContext from the testContext into a GenericApplicationContext, allowing * loading beans from moduleApplicationContext into it and then calling ctx.refresh() * This approach ensures that the application context remains consistent */ GenericApplicationContext ctx = new GenericApplicationContext(testContext.getApplicationContext()); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); Enumeration<URL> list = OpenmrsClassLoader.getInstance() .getResources("moduleApplicationContext.xml"); while (list.hasMoreElements()) { xmlReader.loadBeanDefinitions(new UrlResource(list.nextElement())); } //ensure that when refreshing, we use the openmrs class loader for the started modules. boolean useSystemClassLoader = Context.isUseSystemClassLoader(); Context.setUseSystemClassLoader(false); try { ctx.refresh(); } finally { Context.setUseSystemClassLoader(useSystemClassLoader); } // session is closed by the test framework //Context.closeSession(); } } }
From source file:org.opennms.netmgt.provision.persist.FusedForeignSourceRepositoryTest.java
@Test public void integrationTest() { /*//from w ww . j av a 2 s . c o m * First, the user creates a requisition in the UI, or RESTful * interface. */ Requisition pendingReq = new Requisition("test"); pendingReq.putNode(createNode("1")); m_pending.save(pendingReq); m_pending.flush(); /* * Then, the user makes a foreign source configuration to go along * with that requisition. */ ForeignSource pendingSource = m_repository.getForeignSource("test"); assertTrue(pendingSource.isDefault()); pendingSource.setDetectors(new ArrayList<PluginConfig>()); m_pending.save(pendingSource); m_pending.flush(); /* * Now we got an import event, so we import that requisition file, * and save it. The ForeignSource in the pending repository should * match the one in the active one, now. */ Requisition activeReq = m_repository .importResourceRequisition(new UrlResource(m_pending.getRequisitionURL("test"))); ForeignSource activeSource = m_active.getForeignSource("test"); // and the foreign source should be the same as the one we made earlier, only this time it's active assertEquals(activeSource.getName(), pendingSource.getName()); assertEquals(activeSource.getDetectorNames(), pendingSource.getDetectorNames()); assertEquals(activeSource.getScanInterval(), pendingSource.getScanInterval()); assertRequisitionsMatch("active and pending requisitions should match", activeReq, pendingReq); /* * Since it's been officially deployed, the requisition and foreign * source should no longer be in the pending repo. */ assertNull("the requisition should be null in the pending repo", m_pending.getRequisition("test")); assertTrue("the foreign source should be default since there's no specific in the pending repo", m_pending.getForeignSource("test").isDefault()); }
From source file:org.opennms.netmgt.provision.persist.FusedForeignSourceRepositoryTest.java
@Test public void testSpc674RaceCondition() throws Exception { final String foreignSource = "spc674"; System.err.println("=== create a requisition like the ReST service does, import it immediately ==="); final Requisition initial = new Requisition(foreignSource); initial.putNode(createNode("1")); initial.updateDateStamp();/* w w w. j a v a 2 s .co m*/ m_pending.save(initial); final URL node1Snapshot = createSnapshot(foreignSource); Resource resource = new UrlResource(node1Snapshot); doImport(resource); Thread.sleep(5); List<String> files = getImports(foreignSource); assertEquals(1, files.size()); System.err.println("=== create another snapshot, but don't import it yet ==="); initial.putNode(createNode("2")); initial.updateDateStamp(); m_pending.save(initial); final URL node2Snapshot = createSnapshot(foreignSource); Thread.sleep(5); files = getImports(foreignSource); assertEquals(3, files.size()); System.err.println("=== create yet another snapshot, and don't import it yet ==="); initial.putNode(createNode("3")); initial.updateDateStamp(); m_pending.save(initial); final URL node3Snapshot = createSnapshot(foreignSource); Thread.sleep(5); files = getImports(foreignSource); assertEquals(4, files.size()); System.err.println("=== import of the second file finishes ==="); doImport(new UrlResource(node2Snapshot)); Thread.sleep(5); files = getImports(foreignSource); assertEquals(2, files.size()); System.err.println("=== fourth node is sent to the ReST interface ==="); final Requisition currentPending = RequisitionFileUtils.getLatestPendingOrSnapshotRequisition(m_pending, foreignSource); assertNotNull(currentPending); assertEquals(initial.getDate(), currentPending.getDate()); currentPending.putNode(createNode("4")); currentPending.updateDateStamp(); m_pending.save(currentPending); final URL node4Snapshot = createSnapshot(foreignSource); Thread.sleep(5); files = getImports(foreignSource); assertEquals(4, files.size()); System.err.println("=== import of the third file finishes ==="); doImport(new UrlResource(node3Snapshot)); Thread.sleep(5); files = getImports(foreignSource); assertEquals(2, files.size()); System.err.println("=== import of the fourth file finishes ==="); doImport(new UrlResource(node4Snapshot)); Thread.sleep(5); files = getImports(foreignSource); assertEquals(1, files.size()); }