List of usage examples for java.lang ClassLoader getResourceAsStream
public InputStream getResourceAsStream(String name)
From source file:com.flexive.ejb.beans.configuration.DivisionConfigurationEngineBean.java
private long performPatching() throws FxApplicationException { FxContext.get().runAsSystem();// w ww. j a v a 2 s . co m try { long dbVersion = get(SystemParameters.DB_VERSION); long currentVersion = dbVersion; if (dbVersion == -1) { put(SystemParameters.DB_VERSION, FxSharedUtils.getDBVersion()); return dbVersion; //no need to patch } else if (dbVersion == FxSharedUtils.getDBVersion()) { //nothing to do return dbVersion; } else if (dbVersion > FxSharedUtils.getDBVersion()) { //the database is more current than the EAR! LOG.warn("This [fleXive] build is intended for database schema version #" + FxSharedUtils.getDBVersion() + " but the database reports a higher schema version! (database schema version: " + dbVersion + ")"); return dbVersion; } //lets see if we have a patch we can apply try { final String dbVendor = FxContext.get().getDivisionData().getDbVendor(); final String dir = "resources/patch-" + dbVendor + "/"; String idxFile = dir + "resourceindex.flexive"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); final InputStream scriptIndex = cl.getResourceAsStream(idxFile); if (scriptIndex == null) { LOG.info("No patches available for " + dbVendor); return dbVersion; } String[] files = FxSharedUtils.loadFromInputStream(scriptIndex, -1).replaceAll("\r", "") .split("\n"); Connection con = null; Statement stmt = null; try { con = Database.getNonTXDataSource().getConnection(); stmt = con.createStatement(); List<SQLPatchScript> scripts = new ArrayList<SQLPatchScript>(50); for (String file : files) { String[] f = file.split("\\|"); int size = Integer.parseInt(f[1]); String[] data = f[0].split("_"); if (data.length != 3) { LOG.warn("Expected " + f[0] + " to have format xxx_yyy_zzz.sql"); continue; } if (!"patch".equals(data[0])) { LOG.info("Expected a patch file, but got: " + data[0]); continue; } if (!data[2].endsWith(".sql")) { LOG.info("Expected an sql file, but got: " + data[2]); continue; } long fromVersion = Long.parseLong(data[1]); long toVersion = Long.parseLong(data[2].substring(0, data[2].indexOf('.'))); String code = FxSharedUtils.loadFromInputStream(cl.getResourceAsStream(dir + f[0]), size); scripts.add(new SQLPatchScript(fromVersion, toVersion, code)); // LOG.info("Patch available from version " + fromVersion + " to " + toVersion); } // stmt.executeUpdate(code); boolean patching = true; long maxVersion = currentVersion; while (patching) { patching = false; for (SQLPatchScript ps : scripts) { if (ps.from == currentVersion) { LOG.info("Patching database schema from version [" + ps.from + "] to [" + ps.to + "] ... "); new SQLScriptExecutor(ps.script, stmt).execute(); if (ps.to == 2863) { patchUtils.migrateContentDataGroups(); // remove ISGROUP after the migration was committed try { stmt.execute("ALTER TABLE " + DatabaseConst.TBL_CONTENT_DATA + " DROP COLUMN ISGROUP;"); } catch (SQLException e) { // not critical, column will be ignored in future versions LOG.warn("Failed to remove " + DatabaseConst.TBL_CONTENT_DATA + ".ISGROUP (ignored)", e); } } FxFlatStorageManager.getInstance().patchDatabase(con, ps.from, ps.to); currentVersion = ps.to; patching = true; if (ps.to > maxVersion) ps.to = maxVersion; break; } } } if (currentVersion < maxVersion) { LOG.warn("Failed to patch to maximum available database schema version (" + maxVersion + "). Current database schema version: " + currentVersion); } return currentVersion; } finally { Database.closeObjects(DivisionConfigurationEngineBean.class, con, stmt); } } catch (IOException e) { LOG.fatal(e); return currentVersion; } catch (SQLException e) { LOG.fatal(e); return currentVersion; } } finally { FxContext.get().stopRunAsSystem(); } }
From source file:com.cloudera.director.azure.compute.provider.AzureComputeProviderHelper.java
/** * Creates custom scripts (Azure VM Extensions) to be run when VM is created. * <p>//from w ww .j av a 2 s . co m * NOTE: Testing only. We do not use this feature in the plugin. * * @param context Azure ResourceContext * @return response of the create operation * @throws IOException * @throws ServiceException * @throws URISyntaxException * @throws ExecutionException * @throws InterruptedException */ public synchronized ComputeOperationResponse createCustomizedScript(ResourceContext context) throws IOException, ServiceException, URISyntaxException, ExecutionException, InterruptedException { VirtualMachineExtension vme = new VirtualMachineExtension(); vme.setName("prepare"); // AZURE_SDK ClassLoader classLoader = getClassLoader(); String result; result = IOUtils.toString(classLoader.getResourceAsStream("placeholder.json")); vme.setLocation(context.getLocation()); vme.setPublisher("Microsoft.OSTCExtensions"); vme.setExtensionType("CustomScriptForLinux"); vme.setTypeHandlerVersion("1.2"); vme.setSettings(result); return computeManagementClient.getVirtualMachineExtensionsOperations() .beginCreatingOrUpdating(context.getResourceGroupName(), context.getVMInput().getName(), vme); }
From source file:org.apache.sling.testing.mock.sling.NodeTypeDefinitionScanner.java
/** * Registers only the namespaces found in node type definitions in classpath in JCR repository. * @param session Session/* w w w .j ava 2 s . co m*/ * @param nodeTypeResources List of classpath resource URLs pointing to node type definitions */ private void registerNamespaces(Session session, List<String> nodeTypeResources) throws RepositoryException { ClassLoader classLoader = getClass().getClassLoader(); Workspace workspace = session.getWorkspace(); NamespaceRegistry namespaceRegistry = workspace.getNamespaceRegistry(); ValueFactory valueFactory = session.getValueFactory(); DefinitionBuilderFactory<NodeTypeTemplate, NamespaceRegistry> factory = new TemplateBuilderFactory( new DummyNodeTypeManager(), valueFactory, namespaceRegistry); for (String nodeTypeResource : nodeTypeResources) { InputStream is = classLoader.getResourceAsStream(nodeTypeResource); if (is == null) { continue; } try { Reader reader = new InputStreamReader(is); CompactNodeTypeDefReader<NodeTypeTemplate, NamespaceRegistry> cndReader = new CompactNodeTypeDefReader<NodeTypeTemplate, NamespaceRegistry>( reader, nodeTypeResource, factory); NamespaceRegistry mapping = cndReader.getNamespaceMapping(); for (int i = 0; i < mapping.getURIs().length; i++) { String uri = mapping.getURIs()[i]; String prefix = mapping.getPrefix(uri); try { namespaceRegistry.registerNamespace(prefix, uri); } catch (RepositoryException ex) { // ignore } } } catch (Throwable ex) { log.warn("Unable to parse node type definition: " + nodeTypeResource, ex); } finally { IOUtils.closeQuietly(is); } } }
From source file:com.flexive.ejb.beans.configuration.DivisionConfigurationEngineBean.java
/** * {@inheritDoc}/* w w w. j ava2 s . co m*/ */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void installBinary(long binaryId, String resourceName) throws FxApplicationException { Connection con = null; try { ContentStorage storage = StorageManager.getContentStorage(TypeStorageMode.Hierarchical); String binaryName = resourceName; String subdir = ""; if (binaryName.indexOf('/') > 0) { binaryName = binaryName.substring(binaryName.lastIndexOf('/') + 1); subdir = resourceName.substring(0, resourceName.lastIndexOf('/') + 1); } ClassLoader cl = Thread.currentThread().getContextClassLoader(); con = getConnection(); long length = 0; String[] files = FxSharedUtils .loadFromInputStream( cl.getResourceAsStream("fxresources/binaries/" + subdir + "resourceindex.flexive"), -1) .replaceAll("\r", "").split("\n"); for (String file : files) { if (file.startsWith(binaryName + "|")) { length = Long.parseLong(file.split("\\|")[1]); break; } } if (length == 0) throw new FxApplicationException("ex.scripting.load.resource.failed", resourceName); storage.storeBinary(con, binaryId, 1, 1, binaryName, length, cl.getResourceAsStream("fxresources/binaries/" + resourceName)); } catch (SQLException e) { throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { try { if (con != null) con.close(); } catch (SQLException e) { //ignore } } }
From source file:fll.scheduler.TournamentSchedule.java
/** * Validate the schedule XML document./*from w w w . jav a2 s . c o m*/ * * @throws SAXException on an error */ public static void validateXML(final org.w3c.dom.Document document) throws SAXException { try { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Source schemaFile = new StreamSource( classLoader.getResourceAsStream("fll/resources/schedule.xsd")); final Schema schema = factory.newSchema(schemaFile); final Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } catch (final IOException e) { throw new RuntimeException("Internal error, should never get IOException here", e); } }
From source file:org.apache.axis2.deployment.util.Utils.java
/** * Modules can contain services in some cases. This method will deploy all the services * for a given AxisModule into the current AxisConfiguration. * <p>/*from ww w. j av a 2 s . c o m*/ * The code looks for an "aars/" directory inside the module (either .mar or exploded), * and an "aars.list" file inside that to figure out which services to deploy. Note that all * services deployed this way will have access to the Module's classes. * </p> * * @param module the AxisModule to search for services * @param configCtx ConfigurationContext in which to deploy */ public static void deployModuleServices(AxisModule module, ConfigurationContext configCtx) throws AxisFault { try { AxisConfiguration axisConfig = configCtx.getAxisConfiguration(); ArchiveReader archiveReader = new ArchiveReader(); PhasesInfo phasesInfo = axisConfig.getPhasesInfo(); final ClassLoader moduleClassLoader = module.getModuleClassLoader(); ArrayList services = new ArrayList(); final InputStream in = (InputStream) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return moduleClassLoader.getResourceAsStream("aars/aars.list"); } }); if (in != null) { BufferedReader input; try { input = new BufferedReader((InputStreamReader) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return new InputStreamReader(in); } })); String line; while ((line = input.readLine()) != null) { line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { services.add(line); } } input.close(); } catch (IOException ex) { ex.printStackTrace(); } } if (services.size() > 0) { for (Object service1 : services) { final String servicename = (String) service1; if (servicename == null || "".equals(servicename)) { continue; } InputStream fin = (InputStream) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return moduleClassLoader.getResourceAsStream("aars/" + servicename); } }); if (fin == null) { throw new AxisFault("No service archive found : " + servicename); } File inputFile = Utils.createTempFile(servicename, fin, (File) axisConfig.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR)); DeploymentFileData filedata = new DeploymentFileData(inputFile); filedata.setClassLoader(false, moduleClassLoader, (File) axisConfig.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR), axisConfig.isChildFirstClassLoading()); HashMap wsdlservice = archiveReader.processWSDLs(filedata); if (wsdlservice != null && wsdlservice.size() > 0) { Iterator servicesitr = wsdlservice.values().iterator(); while (servicesitr.hasNext()) { AxisService service = (AxisService) servicesitr.next(); Iterator operations = service.getOperations(); while (operations.hasNext()) { AxisOperation axisOperation = (AxisOperation) operations.next(); phasesInfo.setOperationPhases(axisOperation); } } } AxisServiceGroup serviceGroup = new AxisServiceGroup(axisConfig); serviceGroup.setServiceGroupClassLoader(filedata.getClassLoader()); ArrayList serviceList = archiveReader.processServiceGroup(filedata.getAbsolutePath(), filedata, serviceGroup, false, wsdlservice, configCtx); for (Object aServiceList : serviceList) { AxisService axisService = (AxisService) aServiceList; Parameter moduleService = new Parameter(); moduleService.setValue("true"); moduleService.setName(AxisModule.MODULE_SERVICE); axisService.addParameter(moduleService); serviceGroup.addService(axisService); } axisConfig.addServiceGroup(serviceGroup); fin.close(); } } } catch (IOException e) { throw AxisFault.makeFault(e); } }
From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java
/** * {@inheritDoc}/*from www.j a v a2s . c o m*/ */ public String explainSources() throws RuntimeException { String explainXML = ""; try { String sourcesXmlPath = PropertyReader.getProperty("escidoc.import.sources.xml"); logger.info("SourcesXml-Property: " + sourcesXmlPath); ClassLoader cl = this.getClass().getClassLoader(); InputStream fileIn = cl.getResourceAsStream(sourcesXmlPath); BufferedReader br = new BufferedReader(new InputStreamReader(fileIn, this.enc)); String line = null; while ((line = br.readLine()) != null) { explainXML += line + "\n"; } } catch (IOException e) { this.logger.error("An error occurred while accessing sources.xml.", e); throw new RuntimeException(e); } catch (URISyntaxException e) { this.logger.error("An error occurred while accessing solution.porperties.", e); throw new RuntimeException(e); } return explainXML; }
From source file:au.org.ala.biocache.web.OccurrenceController.java
/** * Custom handler for the welcome view./* www . ja va2 s .co m*/ * <p> * Note that this handler relies on the RequestToViewNameTranslator to * determine the logical view name based on the request URL: "/welcome.do" * -> "welcome". * * @return viewname to render */ @RequestMapping("/") public String homePageHandler(Model model) { model.addAttribute("webservicesRoot", hostUrl); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream("/git.properties"); if (input != null) { try { Properties versionProperties = new Properties(); versionProperties.load(input); model.addAttribute("versionInfo", versionProperties); StringBuffer sb = new StringBuffer(); for (String name : versionProperties.stringPropertyNames()) { sb.append(name + " : " + versionProperties.getProperty(name) + "\n"); } model.addAttribute("versionInfoString", sb.toString()); } catch (Exception e) { logger.error(e.getMessage(), e); } } return HOME; }
From source file:com.flexive.shared.FxSharedUtils.java
/** * Get the named resource from the current thread's classloader * * @param name name of the resource//from w ww.j a v a 2 s. c o m * @return inputstream for the resource */ public static InputStream getResourceStream(String name) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return cl.getResourceAsStream(name); }
From source file:io.github.arven.flare.boot.TomcatContainer.java
public void start() throws Exception { if (base == null || !base.exists()) { setup(configuration);/*from w w w . ja v a 2s . co m*/ } final Properties props = configuration.getProperties(); if (props != null) { StrSubstitutor substitutor = null; for (final String s : props.stringPropertyNames()) { final String v = props.getProperty(s); if (v != null && v.contains("${")) { if (substitutor == null) { final Map<String, String> placeHolders = new HashMap<String, String>(); placeHolders.put("tomee.embedded.http", Integer.toString(configuration.getHttpPort())); placeHolders.put("tomee.embedded.https", Integer.toString(configuration.getHttpsPort())); placeHolders.put("tomee.embedded.stop", Integer.toString(configuration.getStopPort())); substitutor = new StrSubstitutor(placeHolders); } props.put(s, substitutor.replace(v)); } } // inherit from system props final Properties properties = new Properties(System.getProperties()); properties.putAll(configuration.getProperties()); Logger.configure(properties); } else { Logger.configure(); } final File conf = new File(base, "conf"); final File webapps = new File(base, "webapps"); final String catalinaBase = base.getAbsolutePath(); // set the env before calling anoything on tomcat or Catalina!! System.setProperty("catalina.base", catalinaBase); System.setProperty("openejb.deployments.classpath", "false"); System.setProperty("catalina.home", catalinaBase); System.setProperty("catalina.base", catalinaBase); System.setProperty("openejb.home", catalinaBase); System.setProperty("openejb.base", catalinaBase); System.setProperty("openejb.servicemanager.enabled", "false"); copyFileTo(conf, "catalina.policy"); copyTemplateTo(conf, "catalina.properties"); copyFileTo(conf, "context.xml"); copyFileTo(conf, "openejb.xml"); copyFileTo(conf, "tomcat-users.xml"); copyFileTo(conf, "web.xml"); final boolean initialized; if (configuration.hasServerXml()) { final File file = new File(conf, "server.xml"); final FileOutputStream fos = new FileOutputStream(file); try { IO.copy(configuration.getServerXmlFile(), fos); } finally { IO.close(fos); } // respect config (host/port) of the Configuration final QuickServerXmlParser ports = QuickServerXmlParser.parse(file); if (configuration.isKeepServerXmlAsThis()) { // force ports to be able to stop the server and get @ArquillianResource configuration.setHttpPort(Integer.parseInt(ports.http())); configuration.setStopPort(Integer.parseInt(ports.stop())); } else { final Map<String, String> replacements = new HashMap<String, String>(); replacements.put(ports.http(), String.valueOf(configuration.getHttpPort())); replacements.put(ports.https(), String.valueOf(configuration.getHttpsPort())); replacements.put(ports.stop(), String.valueOf(configuration.getStopPort())); IO.copy(IO.slurp(new ReplaceStringsInputStream(IO.read(file), replacements)).getBytes(), file); } tomcat.server(createServer(file.getAbsolutePath())); initialized = true; } else { copyFileTo(conf, "server.xml"); initialized = false; } if (props != null && !props.isEmpty()) { final FileWriter systemProperties = new FileWriter(new File(conf, "system.properties")); try { props.store(systemProperties, ""); } finally { IO.close(systemProperties); } } // Need to use JULI so log messages from the tests are visible // using openejb logging conf in embedded mode /* if we use our config (Logger.configure()) don't override it copyFileTo(conf, "logging.properties"); System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager"); final File logging = new File(conf, "logging.properties"); if (logging.exists()) { System.setProperty("java.util.logging.config.file", logging.getAbsolutePath()); } */ // Trigger loading of catalina.properties CatalinaProperties.getProperty("foo"); tomcat.setBaseDir(base.getAbsolutePath()); tomcat.setHostname(configuration.getHost()); if (!initialized) { tomcat.getHost().setAppBase(webapps.getAbsolutePath()); tomcat.getEngine().setDefaultHost(configuration.getHost()); tomcat.setHostname(configuration.getHost()); } if (tomcat.getRawConnector() == null && !configuration.isSkipHttp()) { final Connector connector = new Connector(Http11Protocol.class.getName()); connector.setPort(configuration.getHttpPort()); connector.setAttribute("connectionTimeout", "3000"); tomcat.getService().addConnector(connector); tomcat.setConnector(connector); } // create https connector if (configuration.isSsl()) { final Connector httpsConnector = new Connector(Http11Protocol.class.getName()); httpsConnector.setPort(configuration.getHttpsPort()); httpsConnector.setSecure(true); httpsConnector.setProperty("SSLEnabled", "true"); httpsConnector.setProperty("sslProtocol", configuration.getSslProtocol()); if (configuration.getKeystoreFile() != null) { httpsConnector.setAttribute("keystoreFile", configuration.getKeystoreFile()); } if (configuration.getKeystorePass() != null) { httpsConnector.setAttribute("keystorePass", configuration.getKeystorePass()); } httpsConnector.setAttribute("keystoreType", configuration.getKeystoreType()); httpsConnector.setAttribute("clientAuth", configuration.getClientAuth()); httpsConnector.setAttribute("keyAlias", configuration.getKeyAlias()); tomcat.getService().addConnector(httpsConnector); if (configuration.isSkipHttp()) { tomcat.setConnector(httpsConnector); } } // Bootstrap Tomcat Logger.getInstance(LogCategory.OPENEJB_STARTUP, TomcatContainer.class) .info("Starting TomEE from: " + base.getAbsolutePath()); // create it after Logger is configured if (configuration.getUsers() != null) { for (final Map.Entry<String, String> user : configuration.getUsers().entrySet()) { tomcat.addUser(user.getKey(), user.getValue()); } } if (configuration.getRoles() != null) { for (final Map.Entry<String, String> user : configuration.getRoles().entrySet()) { for (final String role : user.getValue().split(" *, *")) { tomcat.addRole(user.getKey(), role); } } } if (!initialized) { tomcat.init(); } tomcat.start(); // Bootstrap OpenEJB final Properties properties = new Properties(); properties.setProperty("openejb.deployments.classpath", "false"); properties.setProperty("openejb.loader", "tomcat-system"); properties.setProperty("openejb.home", catalinaBase); properties.setProperty("openejb.base", catalinaBase); properties.setProperty("openejb.servicemanager.enabled", "false"); if (configuration.getProperties() != null) { properties.putAll(configuration.getProperties()); } if (properties.getProperty("openejb.system.apps") == null) { // will make startup faster and it is rarely useful for embedded case properties.setProperty("openejb.system.apps", "false"); } if (configuration.isQuickSession()) { properties.put("openejb.session.manager", QuickSessionManager.class.getName()); } try { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final Properties tomcatServerInfo = IO.readProperties( classLoader.getResourceAsStream("org/apache/catalina/util/ServerInfo.properties"), new Properties()); String serverNumber = tomcatServerInfo.getProperty("server.number"); if (serverNumber == null) { // Tomcat5 only has server.info final String serverInfo = tomcatServerInfo.getProperty("server.info"); if (serverInfo != null) { final int slash = serverInfo.indexOf('/'); serverNumber = serverInfo.substring(slash + 1); } } if (serverNumber != null) { System.setProperty("tomcat.version", serverNumber); } final String serverBuilt = tomcatServerInfo.getProperty("server.built"); if (serverBuilt != null) { System.setProperty("tomcat.built", serverBuilt); } } catch (final Throwable e) { // no-op } final TomcatLoader loader = new TomcatLoader(); loader.initDefaults(properties); // need to add properties after having initialized defaults // to properties passed to SystemInstance otherwise we loose some of them final Properties initProps = new Properties(); initProps.putAll(System.getProperties()); initProps.putAll(properties); if (SystemInstance.isInitialized()) { SystemInstance.get().getProperties().putAll(initProps); } else { SystemInstance.init(initProps); } SystemInstance.get().setComponent(StandardServer.class, (StandardServer) tomcat.getServer()); SystemInstance.get().setComponent(Server.class, tomcat.getServer()); // needed again cause of init() loader.initialize(properties); assembler = SystemInstance.get().getComponent(Assembler.class); configurationFactory = new ConfigurationFactory(); }