List of usage examples for java.lang ClassLoader getResourceAsStream
public InputStream getResourceAsStream(String name)
From source file:com.augmentum.common.util.EntityResolver.java
public InputSource resolveEntity(String publicId, String systemId) { ClassLoader classLoader = getClass().getClassLoader(); if (_log.isDebugEnabled()) { _log.debug("Resolving entity " + publicId + " " + systemId); }//w w w. ja v a2s .c o m if (publicId != null) { for (int i = 0; i < _PUBLIC_IDS.length; i++) { KeyValuePair kvp = _PUBLIC_IDS[i]; if (publicId.equals(kvp.getKey())) { InputStream is = classLoader.getResourceAsStream(_DEFINITIONS_PATH + kvp.getValue()); if (_log.isDebugEnabled()) { _log.debug("Entity found for public id " + systemId); } return new InputSource(is); } } } else if (systemId != null) { for (int i = 0; i < _SYSTEM_IDS.length; i++) { KeyValuePair kvp = _SYSTEM_IDS[i]; if (systemId.equals(kvp.getKey())) { InputStream is = classLoader.getResourceAsStream(_DEFINITIONS_PATH + kvp.getValue()); if (_log.isDebugEnabled()) { _log.debug("Entity found for system id " + systemId); } return new InputSource(is); } } } if (_log.isDebugEnabled()) { _log.debug("No entity found for " + publicId + " " + systemId); } return null; }
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
private void initializeLdap() { log.debug("ldap initializeLdap"); // all ldap config from the ldap properties file log.debug("reading properties file " + propertiesFile); final ClassLoader cl = getClass().getClassLoader(); final InputStream is = cl.getResourceAsStream(propertiesFile); if (is == null) { log.error("Error loading (from classpath) " + propertiesFile); }/*from w w w . java 2 s. com*/ LdapConfig ldapConfig = LdapConfig.createFromProperties(is); log.debug("from properties file " + propertiesFile + " got " + ldapConfig); // including config for the pem cert mode Map<String, Object> props = ldapConfig.getEnvironmentProperties(); Set<String> ps = props.keySet(); for (Iterator it = ps.iterator(); it.hasNext(); log.debug(".. key = " + it.next())) ; String cafile = (String) props.get("pemCaFile"); String certfile = (String) props.get("pemCertFile"); String keyfile = (String) props.get("pemKeyFile"); if (cafile != null && certfile != null && keyfile != null) { log.debug("using the PEM socketfactory: ca=" + cafile + ", cert=" + certfile + ", key=" + keyfile); LdapPEMSocketFactory sf = new LdapPEMSocketFactory(cafile, certfile, keyfile); SSLSocketFactory ldapSocketFactory = sf.getSocketFactory(); ldapConfig.setSslSocketFactory(ldapSocketFactory); } else { log.debug("using the default socketfactory"); } DefaultLdapFactory factory = new DefaultLdapFactory(ldapConfig); LdapPoolConfig poolConfig = new LdapPoolConfig(); try { ldapPool = new SoftLimitLdapPool(factory); ldapPool.initialize(); initialized = true; } catch (Exception e) { log.debug("ldappool error = " + e); } log.debug("ldap initialize done"); }
From source file:org.alfresco.repo.node.integrity.IntegrityTest.java
public void setUp() throws Exception { DictionaryDAO dictionaryDao = (DictionaryDAO) ctx.getBean("dictionaryDAO"); ClassLoader cl = BaseNodeServiceTest.class.getClassLoader(); // load the test model InputStream modelStream = cl .getResourceAsStream("org/alfresco/repo/node/integrity/IntegrityTest_model.xml"); assertNotNull(modelStream);/* ww w . j a v a2 s. c o m*/ M2Model model = M2Model.createModel(modelStream); dictionaryDao.putModel(model); integrityChecker = (IntegrityChecker) ctx.getBean("integrityChecker"); integrityChecker.setEnabled(true); integrityChecker.setFailOnViolation(true); integrityChecker.setTraceOn(true); integrityChecker.setMaxErrorsPerTransaction(100); // we want to count the correct number of errors MetadataEncryptor encryptor = (MetadataEncryptor) ctx.getBean("metadataEncryptor"); serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY); nodeService = serviceRegistry.getNodeService(); this.authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent"); this.authenticationComponent.setSystemUserAsCurrentUser(); // begin a transaction TransactionService transactionService = serviceRegistry.getTransactionService(); txn = transactionService.getUserTransaction(); txn.begin(); StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, getName()); if (!nodeService.exists(storeRef)) { nodeService.createStore(storeRef.getProtocol(), storeRef.getIdentifier()); } rootNodeRef = nodeService.getRootNode(storeRef); allProperties = new PropertyMap(); allProperties.put(TEST_PROP_TEXT_A, "ABC"); allProperties.put(TEST_PROP_TEXT_B, "DEF"); allProperties.put(TEST_PROP_INT_A, "123"); allProperties.put(TEST_PROP_INT_B, "456"); allProperties.put(TEST_PROP_ENCRYPTED_A, "ABC"); allProperties.put(TEST_PROP_ENCRYPTED_B, "DEF"); allProperties = encryptor.encrypt(allProperties); }
From source file:com.compomics.colims.client.controller.admin.FastaDbSaveUpdateController.java
@Override @PostConstruct/* w ww . j a v a2 s. c o m*/ public void init() { //register to event bus eventBus.register(this); fastaDbSaveUpdatePanel = fastaDbManagementController.getFastaDbManagementDialog() .getFastaDbSaveUpdatePanel(); headerParseRuleAdditionDialog = new HeaderParseRuleAdditionDialog( fastaDbManagementController.getFastaDbManagementDialog(), true); taxonomyBindingList = ObservableCollections.observableList(new ArrayList<>()); taxonomyBindingList.add(TAXONOMY_CV_PARAM_NONE); taxonomyBindingList.addAll(cvParamService.findByCvParamByClass(TaxonomyCvParam.class)); //init binding bindingGroup = new BindingGroup(); JComboBoxBinding taxonomyComboBoxBinding = SwingBindings.createJComboBoxBinding( AutoBinding.UpdateStrategy.READ_WRITE, taxonomyBindingList, fastaDbSaveUpdatePanel.getTaxomomyComboBox()); bindingGroup.addBinding(taxonomyComboBoxBinding); headerParseRuleBindingList = ObservableCollections.observableList(new ArrayList<>()); try { config = PropertiesUtil.parsePropertiesFile("config/header-parse-rule.properties"); } catch (IOException | ConfigurationException ex) { java.util.logging.Logger.getLogger(FastaDbSaveUpdateController.class.getName()).log(Level.SEVERE, null, ex); } fillHeaderParseRuleComboBox(); JComboBoxBinding parseRuleComboBoxBinding = SwingBindings.createJComboBoxBinding( AutoBinding.UpdateStrategy.READ_WRITE, headerParseRuleBindingList, fastaDbSaveUpdatePanel.getHeaderParseRuleComboBox()); bindingGroup.addBinding(parseRuleComboBoxBinding); databaseBindingList = ObservableCollections.observableList(new ArrayList<>()); Properties allProperties = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { allProperties.load(loader.getResourceAsStream("config/embl-ebi-database.properties")); databaseSet = new TreeSet(allProperties.keySet()); } catch (IOException ex) { java.util.logging.Logger.getLogger(FastaDbSaveUpdateController.class.getName()).log(Level.SEVERE, null, ex); } fillDatabaseComboBox(); JComboBoxBinding databaseComboBoxBinding = SwingBindings.createJComboBoxBinding( AutoBinding.UpdateStrategy.READ_WRITE, databaseBindingList, fastaDbSaveUpdatePanel.getDatabaseComboBox()); bindingGroup.addBinding(databaseComboBoxBinding); bindingGroup.bind(); //init FASTA file selection //disable select multiple files fastaDbSaveUpdatePanel.getFastaFileChooser().setMultiSelectionEnabled(false); //set FASTA file filter fastaDbSaveUpdatePanel.getFastaFileChooser().setFileFilter(new FastaFileFilter()); //add listeners fastaDbSaveUpdatePanel.getBrowseTaxonomyButton().addActionListener(e -> { List<CvParam> cvParams = cvParamService.findByCvParamByClass(TaxonomyCvParam.class); //update the CV param list cvParamManagementController.updateDialog("FASTA DB taxonomy", TaxonomyCvParam.class, PRESELECTED_ONTOLOGY_NAMESPACES, cvParams); cvParamManagementController.showView(); }); fastaDbSaveUpdatePanel.getBrowseHeaderParseRuleButtton().addActionListener(l -> { headerParseRuleAdditionDialog.getParseRuleTextField().setText(""); headerParseRuleAdditionDialog.getDescriptionTextField().setText(""); GuiUtils.centerDialogOnComponent(fastaDbSaveUpdatePanel, headerParseRuleAdditionDialog); headerParseRuleAdditionDialog.setVisible(true); }); headerParseRuleAdditionDialog.getSaveParseRuleButton().addActionListener(l -> { try { config = PropertiesUtil.addProperty(config, headerParseRuleAdditionDialog.getDescriptionTextField().getText(), headerParseRuleAdditionDialog.getParseRuleTextField().getText()); } catch (ConfigurationException | IOException ex) { java.util.logging.Logger.getLogger(FastaDbSaveUpdateController.class.getName()).log(Level.SEVERE, null, ex); } fillHeaderParseRuleComboBox(); headerParseRuleAdditionDialog.dispose(); }); fastaDbSaveUpdatePanel.getBrowseFastaButton().addActionListener(e -> { //in response to the button click, show open dialog int returnVal = fastaDbSaveUpdatePanel.getFastaFileChooser().showOpenDialog(fastaDbSaveUpdatePanel); if (returnVal == JFileChooser.APPROVE_OPTION) { File fastaFile = fastaDbSaveUpdatePanel.getFastaFileChooser().getSelectedFile(); //show FASTA file name and path in textfields fastaDbSaveUpdatePanel.getFileNameTextField().setText(fastaFile.getName()); fastaDbSaveUpdatePanel.getFilePathTextField().setText(fastaFile.getAbsolutePath()); } }); fastaDbSaveUpdatePanel.getSaveOrUpdateButton().addActionListener(e -> { //validate FASTA DB updateFastaToEdit(); List<String> validationMessages = GuiUtils.validateEntity(fastaDbToEdit); if (validationMessages.isEmpty()) { if (fastaDbToEdit.getId() != null) { fastaDbToEdit = fastaDbService.merge(fastaDbToEdit); fastaDbManagementController.updateFastaDb(); } else { fastaDbService.persist(fastaDbToEdit); fastaDbManagementController.addFastaDb(fastaDbToEdit); } fastaDbSaveUpdatePanel.getNameTextField().setEnabled(false); fastaDbSaveUpdatePanel.getSaveOrUpdateButton().setText("update"); fastaDbSaveUpdatePanel.getFastaDbStateInfoLabel().setText(""); saveUpdate = true; MessageEvent messageEvent = new MessageEvent("Fasta DB store confirmation", "Fasta DB " + fastaDbToEdit.getName() + " was stored successfully!", JOptionPane.INFORMATION_MESSAGE); eventBus.post(messageEvent); fastaDbManagementController.showOverviewPanel(); } else { MessageEvent messageEvent = new MessageEvent("Validation failure", validationMessages, JOptionPane.WARNING_MESSAGE); eventBus.post(messageEvent); } }); fastaDbSaveUpdatePanel.getBackButton().addActionListener(e -> { if (!saveUpdate) { fastaDbManagementController.setSelectedFasta(-1); } saveUpdate = false; fastaDbManagementController.showOverviewPanel(); }); }
From source file:com.adaptris.core.QuartzCronPoller.java
private InputStream find(String... resources) throws IOException { ClassLoader cl = getClass().getClassLoader(); InputStream in = null;//w w w . ja va 2 s .c o m for (String res : resources) { in = cl.getResourceAsStream(res); if (in != null) { log.trace("Using quartz properties from classpath : {}", res); break; } } // It may just return null; ultimately it's user error, do we care, an NPE would be OK here. // but possibly not informative return in; }
From source file:org.apache.flex.forks.velocity.texen.ant.TexenTask.java
/** * Set the context properties that will be * fed into the initial context be the/*from w w w .j ava2s . c o m*/ * generating process starts. */ public void setContextProperties(String file) { String[] sources = StringUtils.split(file, ","); contextProperties = new ExtendedProperties(); // Always try to get the context properties resource // from a file first. Templates may be taken from a JAR // file but the context properties resource may be a // resource in the filesystem. If this fails than attempt // to get the context properties resource from the // classpath. for (int i = 0; i < sources.length; i++) { ExtendedProperties source = new ExtendedProperties(); try { // resolve relative path from basedir and leave // absolute path untouched. File fullPath = project.resolveFile(sources[i]); log("Using contextProperties file: " + fullPath); source.load(new FileInputStream(fullPath)); } catch (Exception e) { ClassLoader classLoader = this.getClass().getClassLoader(); try { InputStream inputStream = classLoader.getResourceAsStream(sources[i]); if (inputStream == null) { throw new BuildException("Context properties file " + sources[i] + " could not be found in the file system or on the classpath!"); } else { source.load(inputStream); } } catch (IOException ioe) { source = null; } } Iterator j = source.getKeys(); while (j.hasNext()) { String name = (String) j.next(); String value = source.getString(name); contextProperties.setProperty(name, value); } } }
From source file:net.riezebos.thoth.configuration.PropertyBasedConfiguration.java
@Override protected void loadDefaults() { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); InputStream is = contextClassLoader.getResourceAsStream(BUILT_PROPERTIES); if (is == null) LOG.error("Somebody misplaced " + BUILT_PROPERTIES + " so there will be no defaults for the Configuration!"); else//w w w . j av a 2 s . co m readInputStream(is); }
From source file:org.apache.hadoop.minikdc.MiniKdc.java
private void initKDCServer() throws Exception { String orgName = conf.getProperty(ORG_NAME); String orgDomain = conf.getProperty(ORG_DOMAIN); String bindAddress = conf.getProperty(KDC_BIND_ADDRESS); final Map<String, String> map = new HashMap<String, String>(); map.put("0", orgName.toLowerCase(Locale.ENGLISH)); map.put("1", orgDomain.toLowerCase(Locale.ENGLISH)); map.put("2", orgName.toUpperCase(Locale.ENGLISH)); map.put("3", orgDomain.toUpperCase(Locale.ENGLISH)); map.put("4", bindAddress); ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is1 = cl.getResourceAsStream("minikdc.ldiff"); SchemaManager schemaManager = ds.getSchemaManager(); LdifReader reader = null;/* ww w . j av a 2s .c o m*/ try { final String content = StrSubstitutor.replace(IOUtils.toString(is1), map); reader = new LdifReader(new StringReader(content)); for (LdifEntry ldifEntry : reader) { ds.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry())); } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(is1); } KerberosConfig kerberosConfig = new KerberosConfig(); kerberosConfig.setMaximumRenewableLifetime(Long.parseLong(conf.getProperty(MAX_RENEWABLE_LIFETIME))); kerberosConfig.setMaximumTicketLifetime(Long.parseLong(conf.getProperty(MAX_TICKET_LIFETIME))); kerberosConfig.setSearchBaseDn(String.format("dc=%s,dc=%s", orgName, orgDomain)); kerberosConfig.setPaEncTimestampRequired(false); kdc = new KdcServer(kerberosConfig); kdc.setDirectoryService(ds); // transport String transport = conf.getProperty(TRANSPORT); AbstractTransport absTransport; if (transport.trim().equals("TCP")) { absTransport = new TcpTransport(bindAddress, port, 3, 50); } else if (transport.trim().equals("UDP")) { absTransport = new UdpTransport(port); } else { throw new IllegalArgumentException("Invalid transport: " + transport); } kdc.addTransports(absTransport); kdc.setServiceName(conf.getProperty(INSTANCE)); kdc.start(); // if using ephemeral port, update port number for binding if (port == 0) { InetSocketAddress addr = (InetSocketAddress) absTransport.getAcceptor().getLocalAddress(); port = addr.getPort(); } StringBuilder sb = new StringBuilder(); InputStream is2 = cl.getResourceAsStream("minikdc-krb5.conf"); BufferedReader r = null; try { r = new BufferedReader(new InputStreamReader(is2, StandardCharsets.UTF_8)); String line = r.readLine(); while (line != null) { sb.append(line).append("{3}"); line = r.readLine(); } } finally { IOUtils.closeQuietly(r); IOUtils.closeQuietly(is2); } krb5conf = new File(workDir, "krb5.conf").getAbsoluteFile(); FileUtils.writeStringToFile(krb5conf, MessageFormat.format(sb.toString(), getRealm(), getHost(), Integer.toString(getPort()), System.getProperty("line.separator"))); System.setProperty(JAVA_SECURITY_KRB5_CONF, krb5conf.getAbsolutePath()); System.setProperty(SUN_SECURITY_KRB5_DEBUG, conf.getProperty(DEBUG, "false")); // refresh the config Class<?> classRef; if (System.getProperty("java.vendor").contains("IBM")) { classRef = Class.forName("com.ibm.security.krb5.internal.Config"); } else { classRef = Class.forName("sun.security.krb5.Config"); } Method refreshMethod = classRef.getMethod("refresh", new Class[0]); refreshMethod.invoke(classRef, new Object[0]); LOG.info("MiniKdc listening at port: {}", getPort()); LOG.info("MiniKdc setting JVM krb5.conf to: {}", krb5conf.getAbsolutePath()); }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.service.servlets.PdfaConverterServlet.java
@Override public void init() throws ServletException { // Set the projects properties. // First look for a system property pointing to a project properties file. // This value can be either a file path, file protocol (e.g. - file:/path/to/file), // or a URL (http://some/server/file). // If this value either does not exist or is not valid, the default // file that comes with this application will be used for initialization. String environmentProjectPropsFile = System.getProperty(ENV_PROJECT_PROPS); logger.info("Value of environment property: [{}] for finding external properties file in location: {}", ENV_PROJECT_PROPS, environmentProjectPropsFile); if (environmentProjectPropsFile != null) { logger.info("Will look for properties file from environment in location: {}", environmentProjectPropsFile); try {/*from ww w . j a v a2 s . c o m*/ File projectProperties = new File(environmentProjectPropsFile); if (projectProperties.exists() && projectProperties.isFile() && projectProperties.canRead()) { InputStream is = new FileInputStream(projectProperties); applicationProps = new Properties(); applicationProps.load(is); } } catch (IOException e) { // fall back to default file logger.error("Unable to load properties file: {} -- reason: {}", environmentProjectPropsFile, e.getMessage()); logger.error("Falling back to default project.properties file: {}", PROPERTIES_FILE_NAME); applicationProps = null; } } if (applicationProps == null) { // did not load from environment variable location try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream resourceStream = classLoader.getResourceAsStream(PROPERTIES_FILE_NAME); if (resourceStream != null) { applicationProps = new Properties(); applicationProps.load(resourceStream); logger.info("loaded default applicationProps"); } else { logger.warn("project.properties not found!!!"); } } catch (IOException e) { logger.error("Could not load properties file: {}", PROPERTIES_FILE_NAME, e); // couldn't load default properties so bail... throw new ServletException("Couldn't load an applications properties file.", e); } } int maxPoolSize = Integer .valueOf(applicationProps.getProperty("max.objects.in.pool", DEFAULT_MAX_OBJECTS_IN_POOL)); long maxFileUploadSizeMb = Long .valueOf(applicationProps.getProperty("max.upload.file.size.MB", DEFAULT_MAX_UPLOAD_SIZE)); long maxRequestSizeMb = Long .valueOf(applicationProps.getProperty("max.request.size.MB", DEFAULT_MAX_REQUEST_SIZE)); maxInMemoryFileSizeMb = Integer .valueOf(applicationProps.getProperty("max.in.memory.file.size.MB", DEFAULT_IN_MEMORY_FILE_SIZE)); logger.info( "Max objects in object pool: {} -- Max file upload size: {}MB -- Max request object size: {}MB -- Max in-memory file size: {}MB", maxPoolSize, maxFileUploadSizeMb, maxRequestSizeMb, maxInMemoryFileSizeMb); logger.debug("Initializing PdfaConverter pool"); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMinIdle(MIN_IDLE_OBJECTS_IN_POOL); poolConfig.setMaxTotal(maxPoolSize); poolConfig.setTestOnBorrow(true); poolConfig.setBlockWhenExhausted(true); pdfaConverterWrapperPool = new PdfaConverterWrapperPool(new PdfaConverterWrapperFactory(), poolConfig); // configures upload settings factory = new DiskFileItemFactory(); factory.setSizeThreshold((maxInMemoryFileSizeMb * (int) MB_MULTIPLIER)); File tempUploadDir = new File(System.getProperty(UPLOAD_DIRECTORY)); if (!tempUploadDir.exists()) { tempUploadDir.mkdir(); } factory.setRepository(tempUploadDir); upload = new ServletFileUpload(factory); upload.setFileSizeMax(maxFileUploadSizeMb * MB_MULTIPLIER); // convert from MB to bytes upload.setSizeMax(maxRequestSizeMb * MB_MULTIPLIER); // convert from MB to bytes logger.debug("PdfaConverter pool finished Initializing"); }
From source file:abfab3d.shapejs.ScriptManager.java
/** * Export a resource embedded into a Jar file to the local file path. * * @param resourceFile ie.: "/SmartLibrary.dll" * @return The path to the exported resource * @throws Exception/*w w w .j a v a 2s. c o m*/ */ public void exportResource(String resourceFile, File destFile) throws Exception { InputStream is = null; try { is = ScriptManager.class.getResourceAsStream(resourceFile); if (is == null) { File file = new File("classes/" + resourceFile); if (!file.exists()) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); is = classLoader.getResourceAsStream(resourceFile); } else { is = new FileInputStream(file); } } if (is == null) { throw new Exception("Cannot load resource: " + resourceFile); } FileUtils.copyInputStreamToFile(is, destFile); } finally { if (is != null) is.close(); } }