List of usage examples for java.lang ClassLoader getResourceAsStream
public InputStream getResourceAsStream(String name)
From source file:javazoom.jlgui.player.amp.PlayerUI.java
public void loadSkin() { log.info("Load PlayerUI (EDT=" + SwingUtilities.isEventDispatchThread() + ")"); removeAll();//from w ww . j a v a 2s .c o m // Load skin specified in args if (ui.getPath() != null) { log.info("Load default skin from " + ui.getPath()); ui.loadSkin(ui.getPath()); config.setDefaultSkin(ui.getPath()); } // Load skin specified in jlgui.ini else if ((config.getDefaultSkin() != null) && (!config.getDefaultSkin().trim().equals(""))) { log.info("Load default skin from " + config.getDefaultSkin()); ui.loadSkin(config.getDefaultSkin()); } // Default included skin else { ClassLoader cl = getClass().getClassLoader(); InputStream sis = cl.getResourceAsStream("javazoom/jlgui/player/amp/metrix.wsz"); log.info("Load default skin for JAR"); ui.loadSkin(sis); } // Background ImageBorder border = new ImageBorder(); border.setImage(ui.getMainImage()); setBorder(border); // Buttons add(ui.getAcPrevious(), ui.getAcPrevious().getConstraints()); ui.getAcPrevious().removeActionListener(this); ui.getAcPrevious().addActionListener(this); add(ui.getAcPlay(), ui.getAcPlay().getConstraints()); ui.getAcPlay().removeActionListener(this); ui.getAcPlay().addActionListener(this); add(ui.getAcPause(), ui.getAcPause().getConstraints()); ui.getAcPause().removeActionListener(this); ui.getAcPause().addActionListener(this); add(ui.getAcStop(), ui.getAcStop().getConstraints()); ui.getAcStop().removeActionListener(this); ui.getAcStop().addActionListener(this); add(ui.getAcNext(), ui.getAcNext().getConstraints()); ui.getAcNext().removeActionListener(this); ui.getAcNext().addActionListener(this); add(ui.getAcEject(), ui.getAcEject().getConstraints()); ui.getAcEject().removeActionListener(this); ui.getAcEject().addActionListener(this); // EqualizerUI toggle add(ui.getAcEqualizer(), ui.getAcEqualizer().getConstraints()); ui.getAcEqualizer().removeActionListener(this); ui.getAcEqualizer().addActionListener(this); // Playlist toggle add(ui.getAcPlaylist(), ui.getAcPlaylist().getConstraints()); ui.getAcPlaylist().removeActionListener(this); ui.getAcPlaylist().addActionListener(this); // Shuffle toggle add(ui.getAcShuffle(), ui.getAcShuffle().getConstraints()); ui.getAcShuffle().removeActionListener(this); ui.getAcShuffle().addActionListener(this); // Repeat toggle add(ui.getAcRepeat(), ui.getAcRepeat().getConstraints()); ui.getAcRepeat().removeActionListener(this); ui.getAcRepeat().addActionListener(this); // Volume add(ui.getAcVolume(), ui.getAcVolume().getConstraints()); ui.getAcVolume().removeChangeListener(this); ui.getAcVolume().addChangeListener(this); // Balance add(ui.getAcBalance(), ui.getAcBalance().getConstraints()); ui.getAcBalance().removeChangeListener(this); ui.getAcBalance().addChangeListener(this); // Seek bar add(ui.getAcPosBar(), ui.getAcPosBar().getConstraints()); ui.getAcPosBar().removeChangeListener(this); ui.getAcPosBar().addChangeListener(this); // Mono add(ui.getAcMonoIcon(), ui.getAcMonoIcon().getConstraints()); // Stereo add(ui.getAcStereoIcon(), ui.getAcStereoIcon().getConstraints()); // Title label add(ui.getAcTitleLabel(), ui.getAcTitleLabel().getConstraints()); // Sample rate label add(ui.getAcSampleRateLabel(), ui.getAcSampleRateLabel().getConstraints()); // Bit rate label add(ui.getAcBitRateLabel(), ui.getAcBitRateLabel().getConstraints()); // Play icon add(ui.getAcPlayIcon(), ui.getAcPlayIcon().getConstraints()); // Time icon add(ui.getAcTimeIcon(), ui.getAcTimeIcon().getConstraints()); // MinuteH number add(ui.getAcMinuteH(), ui.getAcMinuteH().getConstraints()); // MinuteL number add(ui.getAcMinuteL(), ui.getAcMinuteL().getConstraints()); // SecondH number add(ui.getAcSecondH(), ui.getAcSecondH().getConstraints()); // SecondL number add(ui.getAcSecondL(), ui.getAcSecondL().getConstraints()); // TitleBar add(ui.getAcTitleBar(), ui.getAcTitleBar().getConstraints()); add(ui.getAcMinimize(), ui.getAcMinimize().getConstraints()); ui.getAcMinimize().removeActionListener(this); ui.getAcMinimize().addActionListener(this); add(ui.getAcExit(), ui.getAcExit().getConstraints()); ui.getAcExit().removeActionListener(this); ui.getAcExit().addActionListener(this); // DSP if (ui.getAcAnalyzer() != null) { add(ui.getAcAnalyzer(), ui.getAcAnalyzer().getConstraints()); } // Popup menu mainpopup = new JPopupMenu(ui.getResource("popup.title")); JMenuItem mi = new JMenuItem(Skin.TITLETEXT + "- JavaZOOM"); //mi.removeActionListener(this); //mi.addActionListener(this); mainpopup.add(mi); mainpopup.addSeparator(); JMenu playSubMenu = new JMenu(ui.getResource("popup.play")); miPlayFile = new JMenuItem(ui.getResource("popup.play.file")); miPlayFile.setActionCommand(PlayerActionEvent.MIPLAYFILE); miPlayFile.removeActionListener(this); miPlayFile.addActionListener(this); miPlayLocation = new JMenuItem(ui.getResource("popup.play.location")); miPlayLocation.setActionCommand(PlayerActionEvent.MIPLAYLOCATION); miPlayLocation.removeActionListener(this); miPlayLocation.addActionListener(this); playSubMenu.add(miPlayFile); playSubMenu.add(miPlayLocation); mainpopup.add(playSubMenu); mainpopup.addSeparator(); miPlaylist = new JCheckBoxMenuItem(ui.getResource("popup.playlist")); miPlaylist.setActionCommand(PlayerActionEvent.MIPLAYLIST); if (config.isPlaylistEnabled()) miPlaylist.setState(true); miPlaylist.removeActionListener(this); miPlaylist.addActionListener(this); mainpopup.add(miPlaylist); miEqualizer = new JCheckBoxMenuItem(ui.getResource("popup.equalizer")); miEqualizer.setActionCommand(PlayerActionEvent.MIEQUALIZER); if (config.isEqualizerEnabled()) miEqualizer.setState(true); miEqualizer.removeActionListener(this); miEqualizer.addActionListener(this); mainpopup.add(miEqualizer); mainpopup.addSeparator(); mi = new JMenuItem(ui.getResource("popup.preferences")); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK, false)); mi.setActionCommand(PlayerActionEvent.MIPREFERENCES); mi.removeActionListener(this); mi.addActionListener(this); mainpopup.add(mi); JMenu skinsSubMenu = new JMenu(ui.getResource("popup.skins")); mi = new JMenuItem(ui.getResource("popup.skins.browser")); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK, false)); mi.setActionCommand(PlayerActionEvent.MISKINBROWSER); mi.removeActionListener(this); mi.addActionListener(this); skinsSubMenu.add(mi); mi = new JMenuItem(ui.getResource("popup.skins.load")); mi.setActionCommand(PlayerActionEvent.MILOADSKIN); mi.removeActionListener(this); mi.addActionListener(this); skinsSubMenu.add(mi); mainpopup.add(skinsSubMenu); JMenu playbackSubMenu = new JMenu(ui.getResource("popup.playback")); mi = new JMenuItem(ui.getResource("popup.playback.jump")); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J, 0, false)); mi.setActionCommand(PlayerActionEvent.MIJUMPFILE); mi.removeActionListener(this); mi.addActionListener(this); playbackSubMenu.add(mi); mi = new JMenuItem(ui.getResource("popup.playback.stop")); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, 0, false)); mi.setActionCommand(PlayerActionEvent.MISTOP); mi.removeActionListener(this); mi.addActionListener(this); playbackSubMenu.add(mi); mainpopup.add(playbackSubMenu); mainpopup.addSeparator(); mi = new JMenuItem(ui.getResource("popup.exit")); mi.setActionCommand(PlayerActionEvent.ACEXIT); mi.removeActionListener(this); mi.addActionListener(this); mainpopup.add(mi); // Popup menu on TitleBar ui.getAcTitleBar().removeMouseListener(popupAdapter); popupAdapter = new PopupAdapter(mainpopup); ui.getAcTitleBar().addMouseListener(popupAdapter); // Popup menu on Eject button ejectpopup = new JPopupMenu(); mi = new JMenuItem(ui.getResource("popup.eject.openfile")); mi.setActionCommand(PlayerActionEvent.MIPLAYFILE); mi.removeActionListener(this); mi.addActionListener(this); ejectpopup.add(mi); mi = new JMenuItem(ui.getResource("popup.eject.openlocation")); mi.setActionCommand(PlayerActionEvent.MIPLAYLOCATION); mi.removeActionListener(this); mi.addActionListener(this); ejectpopup.add(mi); ui.getAcEject().removeMouseListener(ejectpopupAdapter); ejectpopupAdapter = new PopupAdapter(ejectpopup); ui.getAcEject().addMouseListener(ejectpopupAdapter); // EqualizerUI if (equalizerUI != null) equalizerUI.loadUI(); if (playlistUI != null) playlistUI.loadUI(); validate(); loader.loaded(); }
From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java
/** * Get the input stream from this classloader */// www . ja va 2s . c o m private InputStream getInputStreamFromClassloader(ClassLoader cl, String filename) { InputStream ddlIS = null; if (cl != null) { ddlIS = cl.getResourceAsStream(filename); } return ddlIS; }
From source file:homenetapp.HomeNetApp.java
/** * Call openStream() without automatic gzip decompression. *///from w w w.java2 s . co m public InputStream createInputRaw(String filename) { InputStream stream = null; if (filename == null) { return null; } if (filename.length() == 0) { // an error will be called by the parent function //System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah // if (filename.indexOf(":") != -1) { // at least smells like URL // try { // URL url = new URL(filename); // stream = url.openStream(); // return stream; // // } catch (MalformedURLException mfue) { // // not a url, that's fine // } catch (FileNotFoundException fnfe) { // // Java 1.5 likes to throw this when URL not available. (fix for 0119) // // http://dev.processing.org/bugs/show_bug.cgi?id=403 // } catch (IOException e) { // // changed for 0117, shouldn't be throwing exception // e.printStackTrace(); // //System.err.println("Error downloading from URL " + filename); // return null; // //throw new RuntimeException("Error downloading from URL " + filename); // } // } // // // Moved this earlier than the getResourceAsStream() checks, because // // calling getResourceAsStream() on a directory lists its contents. // // http://dev.processing.org/bugs/show_bug.cgi?id=716 // try { // // First see if it's in a data folder. This may fail by throwing // // a SecurityException. If so, this whole block will be skipped. // System.err.println("Load file"); // File file = new File(getAppPath(filename)); // // if (file.isDirectory()) { // return null; // } // if (file.exists()) { // try { // // handle case sensitivity check // // String filePath = file.getCanonicalPath(); // System.err.println("file path: Load file"+filePath); // // String filenameActual = new File(filePath).getName(); // // make sure there isn't a subfolder prepended to the name // String filenameShort = new File(filename).getName(); // // if the actual filename is the same, but capitalized // // differently, warn the user. // //if (filenameActual.equalsIgnoreCase(filenameShort) && // //!filenameActual.equals(filenameShort)) { // if (!filenameActual.equals(filenameShort)) { // throw new RuntimeException("This file is named " // + filenameActual + " not " // + filename + ". Rename the file " // + "or change your code."); // } // } catch (IOException e) { // } // } // // // if this file is ok, may as well just load it // stream = new FileInputStream(file); // if (stream != null) { // return stream; // } // // // have to break these out because a general Exception might // // catch the RuntimeException being thrown above // } catch (IOException ioe) { // System.err.println("File IO Error"); // ioe.printStackTrace(); // } catch (SecurityException se) { // System.err.println("File Security Error"); // } // Using getClassLoader() prevents java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) ClassLoader cl = getClass().getClassLoader(); // // // by default, data files are exported to the root path of the jar. // // (not the data folder) so check there first. // stream = cl.getResourceAsStream(filename); // if (stream != null) { // String cn = stream.getClass().getName(); // // this is an irritation of sun's java plug-in, which will return // // a non-null stream for an object that doesn't exist. like all good // // things, this is probably introduced in java 1.5. awesome! // // http://dev.processing.org/bugs/show_bug.cgi?id=359 // if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { // return stream; // } // } // When used with an online script, also need to check without the // data folder, in case it's not in a subfolder called 'data'. // http://dev.processing.org/bugs/show_bug.cgi?id=389 stream = cl.getResourceAsStream(filename); if (stream != null) { String cn = stream.getClass().getName(); if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } try { // attempt to load from a local file, used when running as // an application, or as a signed applet try { // first try to catch any security exceptions try { stream = new FileInputStream(getAppPath(filename)); if (stream != null) { return stream; } } catch (IOException e2) { } try { stream = new FileInputStream(filename); if (stream != null) { return stream; } } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups } catch (Exception e) { //die(e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:org.apache.axis2.deployment.DeploymentEngine.java
protected ArrayList populateService(AxisServiceGroup serviceGroup, URL servicesURL, String serviceName) throws DeploymentException { try {/*from w w w .j a v a 2 s . c om*/ serviceGroup.setServiceGroupName(serviceName); ClassLoader serviceClassLoader = Utils.createClassLoader(new URL[] { servicesURL }, axisConfig.getServiceClassLoader(), true, (File) axisConfig.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR), axisConfig.isChildFirstClassLoading()); String metainf = "meta-inf"; serviceGroup.setServiceGroupClassLoader(serviceClassLoader); //processing wsdl.list InputStream wsdlfilesStream = serviceClassLoader.getResourceAsStream("meta-inf/wsdl.list"); if (wsdlfilesStream == null) { wsdlfilesStream = serviceClassLoader.getResourceAsStream("META-INF/wsdl.list"); if (wsdlfilesStream != null) { metainf = "META-INF"; } } HashMap servicesMap = new HashMap(); if (wsdlfilesStream != null) { ArchiveReader reader = new ArchiveReader(); BufferedReader input = new BufferedReader(new InputStreamReader(wsdlfilesStream)); String line; while ((line = input.readLine()) != null) { line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { line = metainf + "/" + line; try { List services = reader.getAxisServiceFromWsdl( serviceClassLoader.getResourceAsStream(line), serviceClassLoader, line); if (services != null) { for (Object service : services) { AxisService axisService = (AxisService) service; servicesMap.put(axisService.getName(), axisService); } } } catch (Exception e) { throw new DeploymentException(e); } } } } InputStream servicexmlStream = serviceClassLoader.getResourceAsStream("META-INF/services.xml"); if (servicexmlStream == null) { servicexmlStream = serviceClassLoader.getResourceAsStream("meta-inf/services.xml"); } else { metainf = "META-INF"; } if (servicexmlStream == null) { throw new DeploymentException( Messages.getMessage(DeploymentErrorMsgs.SERVICE_XML_NOT_FOUND, servicesURL.toString())); } DescriptionBuilder builder = new DescriptionBuilder(servicexmlStream, configContext); OMElement rootElement = builder.buildOM(); String elementName = rootElement.getLocalName(); if (TAG_SERVICE.equals(elementName)) { AxisService axisService = null; String wsdlLocation = "META-INF/service.wsdl"; InputStream wsdlStream = serviceClassLoader.getResourceAsStream(wsdlLocation); URL wsdlURL = serviceClassLoader.getResource(metainf + "/service.wsdl"); if (wsdlStream == null) { wsdlLocation = "META-INF/" + serviceName + ".wsdl"; wsdlStream = serviceClassLoader.getResourceAsStream(wsdlLocation); wsdlURL = serviceClassLoader.getResource(wsdlLocation); } if (wsdlStream != null) { WSDL11ToAxisServiceBuilder wsdl2AxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlStream, null, null); File file = Utils.toFile(servicesURL); if (file != null && file.exists()) { wsdl2AxisServiceBuilder .setCustomWSDLResolver(new AARBasedWSDLLocator(wsdlLocation, file, wsdlStream)); wsdl2AxisServiceBuilder.setCustomResolver(new AARFileBasedURIResolver(file)); } if (wsdlURL != null) { wsdl2AxisServiceBuilder.setDocumentBaseUri(wsdlURL.toString()); } axisService = wsdl2AxisServiceBuilder.populateService(); axisService.setWsdlFound(true); axisService.setCustomWsdl(true); axisService.setName(serviceName); } if (axisService == null) { axisService = new AxisService(serviceName); } axisService.setParent(serviceGroup); axisService.setClassLoader(serviceClassLoader); ServiceBuilder serviceBuilder = new ServiceBuilder(configContext, axisService); AxisService service = serviceBuilder.populateService(rootElement); ArrayList serviceList = new ArrayList(); serviceList.add(service); return serviceList; } else if (TAG_SERVICE_GROUP.equals(elementName)) { ServiceGroupBuilder groupBuilder = new ServiceGroupBuilder(rootElement, servicesMap, configContext); ArrayList servicList = groupBuilder.populateServiceGroup(serviceGroup); Iterator serviceIterator = servicList.iterator(); while (serviceIterator.hasNext()) { AxisService axisService = (AxisService) serviceIterator.next(); String wsdlLocation = "META-INF/service.wsdl"; InputStream wsdlStream = serviceClassLoader.getResourceAsStream(wsdlLocation); URL wsdlURL = serviceClassLoader.getResource(wsdlLocation); if (wsdlStream == null) { wsdlLocation = "META-INF/" + serviceName + ".wsdl"; wsdlStream = serviceClassLoader.getResourceAsStream(wsdlLocation); wsdlURL = serviceClassLoader.getResource(wsdlLocation); } if (wsdlStream != null) { WSDL11ToAxisServiceBuilder wsdl2AxisServiceBuilder = new WSDL11ToAxisServiceBuilder( wsdlStream, axisService); File file = Utils.toFile(servicesURL); if (file != null && file.exists()) { wsdl2AxisServiceBuilder .setCustomWSDLResolver(new AARBasedWSDLLocator(wsdlLocation, file, wsdlStream)); wsdl2AxisServiceBuilder.setCustomResolver(new AARFileBasedURIResolver(file)); } if (wsdlURL != null) { wsdl2AxisServiceBuilder.setDocumentBaseUri(wsdlURL.toString()); } axisService = wsdl2AxisServiceBuilder.populateService(); axisService.setWsdlFound(true); axisService.setCustomWsdl(true); // Set the default message receiver for the operations that were // not listed in the services.xml Iterator operations = axisService.getOperations(); while (operations.hasNext()) { AxisOperation operation = (AxisOperation) operations.next(); if (operation.getMessageReceiver() == null) { operation.setMessageReceiver(loadDefaultMessageReceiver( operation.getMessageExchangePattern(), axisService)); } } } } return servicList; } } catch (IOException e) { throw new DeploymentException(e); } catch (XMLStreamException e) { throw new DeploymentException(e); } return null; }
From source file:org.alfresco.reporting.script.AlfrescoReporting.java
/** * Mapping of Alfresco property TYPES onto SQL column definitions. * the value of "-" means the Alfresco property will NOT be automatically * mapped into the SQL database. The proeprties file will be read from classpath * There are custom calls for Site, Category, Tags * //from w w w.jav a2s.c o m * @return Properties object * @throws Exception */ private Properties getClassToColumnType() throws Exception { if (datadictionary == null) { try { ClassLoader cl = this.getClass().getClassLoader(); InputStream is = cl.getResourceAsStream(Constants.REPORTING_PROPERTIES); Properties p = new Properties(); p.load(is); datadictionary = p; } catch (IOException e) { e.printStackTrace(); throw new Exception(e); } } return datadictionary; }
From source file:org.alfresco.reporting.script.AlfrescoReporting.java
/** * Reads external properties file. The properties in this file will override * the default mapping of individual Alfresco PROPERTY types into SQL column * definitions ** on a per-property basis** * (One often knows a zip code is d:text, but never more than 8 charaters, so * VARCHAR(8) will do). The total length of the row (sum of the column lengths) * can never be more than 65535 bytes. And i guess UTF-8 makes a reservation of * 4 bytes per character/*from w w w . j av a 2s.co m*/ * * The properties file REPORTING_CUSTOM_PROPERTIES can be named differently using * the method setCustomModelProperties(String newFileName) * * @return Properties object with as content the key/value pairs from the properties file. */ private Properties getReplacementDataType() { if (replacementTypes == null) { try { ClassLoader cl = this.getClass().getClassLoader(); InputStream is = cl.getResourceAsStream(reporting_custom_properties); Properties p = new Properties(); p.load(is); replacementTypes = p; } catch (Exception e) { //e.printStackTrace(); replacementTypes = new Properties(); } } return replacementTypes; }
From source file:org.apache.catalina.loader.WebappClassLoader.java
/** * Find the resource with the given name, and return an input stream * that can be used for reading it. The search order is as described * for <code>getResource()</code>, after checking to see if the resource * data has been previously cached. If the resource cannot be found, * return <code>null</code>. * * @param name Name of the resource to return an input stream for *//*from ww w . j a va 2s .co m*/ public InputStream getResourceAsStream(String name) { if (log.isDebugEnabled()) log.debug("getResourceAsStream(" + name + ")"); InputStream stream = null; // (0) Check for a cached copy of this resource stream = findLoadedResource(name); if (stream != null) { if (log.isDebugEnabled()) log.debug(" --> Returning stream from cache"); return (stream); } // (1) Delegate to parent if requested if (delegate) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader " + parent); ClassLoader loader = parent; if (loader == null) loader = system; stream = loader.getResourceAsStream(name); if (stream != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from parent"); return (stream); } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); URL url = findResource(name); if (url != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from local"); stream = findLoadedResource(name); try { if (hasExternalRepositories && (stream == null)) stream = url.openStream(); } catch (IOException e) { ; // Ignore } if (stream != null) return (stream); } // (3) Delegate to parent unconditionally if (!delegate) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader unconditionally " + parent); ClassLoader loader = parent; if (loader == null) loader = system; stream = loader.getResourceAsStream(name); if (stream != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from parent"); return (stream); } } // (4) Resource was not found if (log.isDebugEnabled()) log.debug(" --> Resource not found, returning null"); return (null); }
From source file:org.apache.click.util.ClickUtils.java
/** * Finds a resource with a given name. This method returns null if no * resource with this name is found.//from w w w .j a v a 2 s . c om * <p> * This method uses the current <tt>Thread</tt> context <tt>ClassLoader</tt> to find * the resource. If the resource is not found the class loader of the given * class is then used to find the resource. * * @param name the name of the resource * @param aClass the class lookup the resource against, if the resource is * not found using the current <tt>Thread</tt> context <tt>ClassLoader</tt>. * @return the input stream of the resource if found or null otherwise */ public static InputStream getResourceAsStream(String name, Class<?> aClass) { Validate.notNull(name, "Parameter name is null"); Validate.notNull(aClass, "Parameter aClass is null"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(name); if (inputStream == null) { inputStream = aClass.getResourceAsStream(name); } return inputStream; }
From source file:org.apache.oozie.service.XLogService.java
/** * Initialize the log service./*from ww w . j a v a 2 s . c o m*/ * * @param services services instance. * @throws ServiceException thrown if the log service could not be initialized. */ public void init(Services services) throws ServiceException { String oozieHome = Services.getOozieHome(); String oozieLogs = System.getProperty(OOZIE_LOG_DIR, oozieHome + "/logs"); System.setProperty(OOZIE_LOG_DIR, oozieLogs); try { LogManager.resetConfiguration(); log4jFileName = System.getProperty(LOG4J_FILE, DEFAULT_LOG4J_PROPERTIES); if (log4jFileName.contains("/")) { throw new ServiceException(ErrorCode.E0011, log4jFileName); } if (!log4jFileName.endsWith(".properties")) { throw new ServiceException(ErrorCode.E0012, log4jFileName); } String configPath = ConfigurationService.getConfigurationDirectory(); File log4jFile = new File(configPath, log4jFileName); if (log4jFile.exists()) { fromClasspath = false; } else { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL log4jUrl = cl.getResource(log4jFileName); if (log4jUrl == null) { throw new ServiceException(ErrorCode.E0013, log4jFileName, configPath); } fromClasspath = true; } if (fromClasspath) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL log4jUrl = cl.getResource(log4jFileName); PropertyConfigurator.configure(log4jUrl); } else { interval = Long.parseLong(System.getProperty(LOG4J_RELOAD, DEFAULT_RELOAD_INTERVAL)); PropertyConfigurator.configureAndWatch(log4jFile.toString(), interval * 1000); } log = new XLog(LogFactory.getLog(getClass())); log.info(XLog.OPS, STARTUP_MESSAGE, BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VERSION), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_USER_NAME), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_TIME), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VC_REVISION), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VC_URL)); String from = (fromClasspath) ? "CLASSPATH" : configPath; String reload = (fromClasspath) ? "disabled" : Long.toString(interval) + " sec"; log.info("Log4j configuration file [{0}]", log4jFileName); log.info("Log4j configuration file loaded from [{0}]", from); log.info("Log4j reload interval [{0}]", reload); XLog.Info.reset(); XLog.Info.defineParameter(USER); XLog.Info.defineParameter(GROUP); XLogFilter.reset(); XLogFilter.defineParameter(USER); XLogFilter.defineParameter(GROUP); // Getting configuration for oozie log via WS ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = (fromClasspath) ? cl.getResourceAsStream(log4jFileName) : new FileInputStream(log4jFile); extractInfoForLogWebService(is); } catch (IOException ex) { throw new ServiceException(ErrorCode.E0010, ex.getMessage(), ex); } }
From source file:com.delphix.session.test.ServiceTest.java
@BeforeClass public void init() throws FileNotFoundException, IOException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Properties testprops = new Properties(); testprops.load(cl.getResourceAsStream("test.properties")); String password = testprops.getProperty("password"); // Initialize key store this.keyStore = cl.getResource(testprops.getProperty("keystore")).getPath(); this.keyPass = password; this.storePass = password; // Initialize throughput tests this.testServer = testprops.getProperty("server"); this.testData = cl.getResource(testprops.getProperty("data")).getPath(); this.testStats = Boolean.parseBoolean(testprops.getProperty("stats")); this.multiSessions = Boolean.parseBoolean(testprops.getProperty("multisess")); this.serverMode = Boolean.parseBoolean(testprops.getProperty("mode")); this.testStreams = Integer.parseInt(testprops.getProperty("streams")); // Comma separated port list String portList = testprops.getProperty("ports"); if (portList != null) { String[] ports = portList.split(","); testPorts = new int[ports.length]; assertEquals(ports.length, testStreams); for (int i = 0; i < ports.length; i++) { testPorts[i] = Integer.parseInt(ports[i]); }//from w ww. j ava2s . co m } // Initialize trust store this.trustStore = cl.getResource(testprops.getProperty("truststore")).getPath(); this.trustPass = password; // Initialize service types helloService = new ServiceType(HELLO_UUID, HELLO_NAME, HELLO_DESC); delayService = new ServiceType(DELAY_UUID, DELAY_NAME, DELAY_DESC); try { localhost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { fail("failed to get local host", e); } clientManager.start(); serverManager.start(); executor = Executors.newCachedThreadPool(); }