List of usage examples for java.lang ClassLoader getResourceAsStream
public InputStream getResourceAsStream(String name)
From source file:Resource.java
/** * @param args/*from w w w . ja v a 2 s. c o m*/ */ public static void main(String[] args) { // TODO Auto-generated method stub ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl.getResourceAsStream("com/sap/ca/aspose/license/Aspose.Total.Java.lic"); //InputStream is = cl.getResourceAsStream("com/sap/ca/aspose/license/a.txt"); if (is == null) { System.err.println("Error is is null"); System.exit(1); } String s; try { s = IOUtils.toString(is); System.out.println(s); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.openx.oauthdemo.Demo.java
/** * Main class. OX3 with OAuth demo/* w ww. ja va 2 s .c o m*/ * @param args */ public static void main(String[] args) { String apiKey, apiSecret, loginUrl, username, password, domain, path, requestTokenUrl, accessTokenUrl, realm, authorizeUrl; String propertiesFile = "default.properties"; // load params from the properties file Properties defaultProps = new Properties(); InputStream in = null; try { ClassLoader cl = ClassLoader.getSystemClassLoader(); in = cl.getResourceAsStream(propertiesFile); if (in != null) { defaultProps.load(in); } } catch (IOException ex) { System.out.println("The properties file was not found!"); return; } finally { if (in != null) { try { in.close(); } catch (IOException ex) { System.out.println("IO Error closing the properties file"); return; } } } if (defaultProps.isEmpty()) { System.out.println("The properties file was not loaded!"); return; } apiKey = defaultProps.getProperty("apiKey"); apiSecret = defaultProps.getProperty("apiSecret"); loginUrl = defaultProps.getProperty("loginUrl"); username = defaultProps.getProperty("username"); password = defaultProps.getProperty("password"); domain = defaultProps.getProperty("domain"); path = defaultProps.getProperty("path"); requestTokenUrl = defaultProps.getProperty("requestTokenUrl"); accessTokenUrl = defaultProps.getProperty("accessTokenUrl"); realm = defaultProps.getProperty("realm"); authorizeUrl = defaultProps.getProperty("authorizeUrl"); // log in to the server Client cl = new Client(apiKey, apiSecret, loginUrl, username, password, domain, path, requestTokenUrl, accessTokenUrl, realm, authorizeUrl); try { // connect to the server cl.OX3OAuth(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "UTF-8 support needed for OAuth", ex); } catch (IOException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "IO file reading error", ex); } catch (Exception ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "API issue", ex); } // now lets make a call to the api to check String json; try { json = cl.getHelper().callOX3Api(domain, path, "account"); } catch (IOException ex) { System.out.println("There was an error calling the API"); return; } System.out.println("JSON response: " + json); Gson gson = new Gson(); int[] accounts = gson.fromJson(json, int[].class); if (accounts.length > 0) { // let's get a single account try { json = cl.getHelper().callOX3Api(domain, path, "account", accounts[0]); } catch (IOException ex) { System.out.println("There was an error calling the API"); return; } System.out.println("JSON response: " + json); OX3Account account = gson.fromJson(json, OX3Account.class); System.out.println("Account id: " + account.getId() + " name: " + account.getName()); } }
From source file:org.brnvrn.Main.java
public static void main(String[] args) { Document doc = null; // the HTML tool page Document docObsolete = null;//from ww w . jav a2s .c o m try { //Document doc = Jsoup.connect("http://taskwarrior.org/tools/").get(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream input = classloader.getResourceAsStream("Taskwarrior-Tools.html"); doc = Jsoup.parse(input, "UTF-8", "http://taskwarrior.org/"); input = classloader.getResourceAsStream("Taskwarrior-Tools-Obsolete.html"); docObsolete = Jsoup.parse(input, "UTF-8", "http://taskwarrior.org/"); } catch (IOException e) { e.printStackTrace(); } List<Tool> tools = new ArrayList<Tool>(100); ObjectMapper objectMapper = parseDocument(tools, doc, false); objectMapper = parseDocument(tools, docObsolete, true); try { objectMapper.writeValue(new FileOutputStream("data-tools.json"), tools); } catch (IOException e) { e.printStackTrace(); } }
From source file:eu.databata.engine.util.PropagatorRecreateDatabaseTool.java
public static void main(String[] args) { ClassLoader classLoader = PropagatorRecreateDatabaseTool.class.getClassLoader(); InputStream resourceAsStream = classLoader.getResourceAsStream("databata.properties"); Properties propagatorProperties = new Properties(); try {//from w w w .j a v a2 s .c o m propagatorProperties.load(resourceAsStream); } catch (FileNotFoundException e) { LOG.error("Sepecified file 'databata.properties' not found"); } catch (IOException e) { LOG.error("Sepecified file 'databata.properties' cannot be loaded"); } SingleConnectionDataSource dataSource = new SingleConnectionDataSource(); dataSource.setDriverClassName(propagatorProperties.getProperty("db.propagation.driver")); dataSource.setUrl(propagatorProperties.getProperty("db.propagation.dba.connection-url")); dataSource.setUsername(propagatorProperties.getProperty("db.propagation.dba.user")); dataSource.setPassword(propagatorProperties.getProperty("db.propagation.dba.password")); dataSource.setSuppressClose(true); String databaseName = "undefined"; try { databaseName = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { LOG.error("Cannot get connection by specified url", e); } String databaseCode = PropagationUtils.getDatabaseCode(databaseName); LOG.info("Database with code '" + databaseCode + "' is identified."); String submitFileName = "META-INF/databata/" + databaseCode + "_recreate_database.sql"; String fileContent = ""; try { fileContent = getFileContent(classLoader, submitFileName); } catch (IOException e) { LOG.info("File with name '" + submitFileName + "' cannot be read from classpath. Trying to load default submit file."); } if (fileContent == null || "".equals(fileContent)) { String defaultSubmitFileName = "META-INF/databata/" + databaseCode + "_recreate_database.default.sql"; try { fileContent = getFileContent(classLoader, defaultSubmitFileName); } catch (IOException e) { LOG.info("File with name '" + defaultSubmitFileName + "' cannot be read from classpath. Trying to load default submit file."); } } if (fileContent == null) { LOG.info("File content is empty. Stopping process."); return; } fileContent = replacePlaceholders(fileContent, propagatorProperties); SqlFile sqlFile = null; try { sqlFile = new SqlFile(fileContent, null, submitFileName, new SqlExecutionCallback() { @Override public void handleExecuteSuccess(String sql, int arg1, double arg2) { LOG.info("Sql is sucessfully executed \n ======== \n" + sql + "\n ======== \n"); } @Override public void handleException(SQLException arg0, String sql) throws SQLException { LOG.info("Sql returned error \n ======== \n" + sql + "\n ======== \n"); } }, null); } catch (IOException e) { LOG.error("Error when initializing SqlTool", e); } try { sqlFile.setConnection(dataSource.getConnection()); } catch (SQLException e) { LOG.error("Error is occured when setting connection", e); } try { sqlFile.execute(); } catch (SqlToolError e) { LOG.error("Error when creating user", e); } catch (SQLException e) { LOG.error("Error when creating user", e); } }
From source file:eu.databata.engine.util.PropagatorRecreateUserTool.java
public static void main(String[] args) { if (args.length == 0) { printMessage();//from www. j a v a2s. c om return; } String scriptName = getScriptName(args[0]); if (scriptName == null) { printMessage(); return; } ClassLoader classLoader = PropagatorRecreateUserTool.class.getClassLoader(); InputStream resourceAsStream = classLoader.getResourceAsStream("databata.properties"); Properties propagatorProperties = new Properties(); try { propagatorProperties.load(resourceAsStream); } catch (FileNotFoundException e) { LOG.error("Sepecified file 'databata.properties' not found"); } catch (IOException e) { LOG.error("Sepecified file 'databata.properties' cannot be loaded"); } SingleConnectionDataSource dataSource = new SingleConnectionDataSource(); dataSource.setDriverClassName(propagatorProperties.getProperty("db.propagation.driver")); if ("-idb".equals(args[0])) { dataSource.setUrl(propagatorProperties.getProperty("db.propagation.dba.connection-url")); dataSource.setUsername(propagatorProperties.getProperty("db.propagation.dba.user")); dataSource.setPassword(propagatorProperties.getProperty("db.propagation.dba.password")); } else { dataSource.setUrl(propagatorProperties.getProperty("db.propagation.sa.connection-url")); dataSource.setUsername(propagatorProperties.getProperty("db.propagation.sa.user")); dataSource.setPassword(propagatorProperties.getProperty("db.propagation.sa.password")); } dataSource.setSuppressClose(true); String databaseName = "undefined"; try { databaseName = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { LOG.error("Cannot get connection by specified url", e); return; } String databaseCode = PropagationUtils.getDatabaseCode(databaseName); LOG.info("Database with code '" + databaseCode + "' is identified. for database '" + databaseName + "'"); String submitFileName = "META-INF/databata/" + databaseCode + "_" + scriptName + ".sql"; String fileContent = ""; try { fileContent = getFileContent(classLoader, submitFileName); } catch (IOException e) { LOG.info("File with name '" + submitFileName + "' cannot be read from classpath. Trying to load default submit file."); } if (fileContent == null || "".equals(fileContent)) { String defaultSubmitFileName = "META-INF/databata/" + databaseCode + "_" + scriptName + ".default.sql"; try { fileContent = getFileContent(classLoader, defaultSubmitFileName); } catch (IOException e) { LOG.info("File with name '" + defaultSubmitFileName + "' cannot be read from classpath. Trying to load default submit file."); } } if (fileContent == null) { LOG.info("File content is empty. Stopping process."); return; } fileContent = replacePlaceholders(fileContent, propagatorProperties); SqlFile sqlFile = null; try { sqlFile = new SqlFile(fileContent, null, submitFileName, new SqlExecutionCallback() { @Override public void handleExecuteSuccess(String sql, int arg1, double arg2) { LOG.info("Sql is sucessfully executed \n ======== \n" + sql + "\n ======== \n"); } @Override public void handleException(SQLException arg0, String sql) throws SQLException { LOG.info("Sql returned error \n ======== \n" + sql + "\n ======== \n"); } }, null); } catch (IOException e) { LOG.error("Error when initializing SqlTool", e); } try { sqlFile.setConnection(dataSource.getConnection()); } catch (SQLException e) { LOG.error("Error is occured when setting connection", e); } try { sqlFile.execute(); } catch (SqlToolError e) { LOG.error("Error when creating user", e); } catch (SQLException e) { LOG.error("Error when creating user", e); } }
From source file:org.atomserver.utils.jetty.StandAloneAtomServer.java
public static void main(String[] args) throws Exception { // the System Property "atomserver.home" defines the home directory for the standalone app String atomserverHome = System.getProperty("atomserver.home"); if (StringUtils.isEmpty(atomserverHome)) { log.error("The variable \"atomserver.home\" must be defined"); System.exit(-1);/*www .j a v a 2 s . co m*/ } File atomserverHomeDir = new File(atomserverHome); if (!atomserverHomeDir.exists() && !atomserverHomeDir.isDirectory()) { log.error("The variable \"atomserver.home\" (" + atomserverHome + ") must point to a directory that exists"); } // instantiate the Jetty Server Server server = new Server(); // create a new connector on the declared port, and set it onto the server log.debug("atomserver.port = " + System.getProperty("atomserver.port")); Connector connector = new SelectChannelConnector(); connector.setPort(Integer.getInteger("atomserver.port", DEFAULT_PORT)); server.setConnectors(new Connector[] { connector }); // create a ClassLoader that points at the conf directories log.debug("atomserver.conf.dir = " + System.getProperty("atomserver.conf.dir")); log.debug("atomserver.ops.conf.dir = " + System.getProperty("atomserver.ops.conf.dir")); ClassLoader classLoader = new ConfigurationAwareClassLoader(StandAloneAtomServer.class.getClassLoader()); // load the version from the version.properties file Properties versionProps = new Properties(); versionProps.load(classLoader.getResourceAsStream(DEFAULT_VERSIONS_FILE)); String version = versionProps.getProperty("atomserver.version"); // create a new webapp, rooted at webapps/atomserver-${version}, with the configured // context name String servletContextName = System.getProperty("atomserver.servlet.context"); log.debug("atomserver.servlet.context = " + servletContextName); WebAppContext webapp = new WebAppContext(atomserverHome + "/webapps/atomserver-" + version, "/" + servletContextName); // set the webapp's ClassLoader to be the one that loaded THIS class. the REASON that // this needs to be set is so that when we extract the web application context below we can // cast it to WebApplicationContext here webapp.setClassLoader(StandAloneAtomServer.class.getClassLoader()); // set the Jetty server's webapp and start it server.setHandler(webapp); server.start(); // if the seed system property was set, use the DBSeeder to populate the server String seedDB = System.getProperty("seed.database.with.pets"); log.debug("seed.database.with.pets = " + seedDB); if (!StringUtils.isEmpty(seedDB)) { if (Boolean.valueOf(seedDB)) { Thread.sleep(2000); WebApplicationContext webappContext = WebApplicationContextUtils .getWebApplicationContext(webapp.getServletContext()); DBSeeder.getInstance(webappContext).seedPets(); } } server.join(); }
From source file:net.ontopia.topicmaps.cmdlineutils.rdbms.RDBMSIndexTool.java
public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging();/* w ww . ja va 2s .co m*/ // Register logging options CmdlineOptions options = new CmdlineOptions("RDBMSIndexTool", argv); CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length != 1) { usage(); System.exit(3); } // load database schema project ClassLoader cloader = RDBMSIndexTool.class.getClassLoader(); InputStream istream = cloader.getResourceAsStream("net/ontopia/topicmaps/impl/rdbms/config/schema.xml"); Project dbp = DatabaseProjectReader.loadProject(istream); // open database connection String propfile = args[0]; ConnectionFactoryIF cf = new DefaultConnectionFactory(PropertyUtils.loadProperties(new File(propfile)), true); Connection conn = cf.requestConnection(); try { DatabaseMetaData dbm = conn.getMetaData(); boolean downcase = dbm.storesLowerCaseIdentifiers(); Map extra_indexes = new TreeMap(); Map missing_indexes = new TreeMap(); Iterator tables = dbp.getTables().iterator(); while (tables.hasNext()) { Table table = (Table) tables.next(); String table_name = (downcase ? table.getName().toLowerCase() : table.getName()); //! System.out.println("T :" + table_name); // get primary keys from database Map pkeys = getPrimaryKeys(table_name, dbm); // get indexes from database Map indexes = getIndexes(table_name, dbm); Map dindexes = new HashMap(); if (table.getPrimaryKeys() != null) { String pkey = table_name + '(' + StringUtils.join(table.getPrimaryKeys(), ',') + ')'; if (!pkeys.containsKey(pkey)) System.out.println("PKM: " + pkey); } Iterator iter = table.getIndexes().iterator(); while (iter.hasNext()) { Index index = (Index) iter.next(); String i = table_name + '(' + StringUtils.join(index.getColumns(), ',') + ')'; String index_name = (downcase ? index.getName().toLowerCase() : index.getName()); dindexes.put(i, index_name); } Set extra = new HashSet(indexes.keySet()); extra.removeAll(dindexes.keySet()); extra.removeAll(pkeys.keySet()); if (!extra.isEmpty()) { Iterator i = extra.iterator(); while (i.hasNext()) { Object k = i.next(); extra_indexes.put(k, indexes.get(k)); } } Set missing = new HashSet(dindexes.keySet()); missing.addAll(pkeys.keySet()); missing.removeAll(indexes.keySet()); if (!missing.isEmpty()) { Iterator i = missing.iterator(); while (i.hasNext()) { Object k = i.next(); missing_indexes.put(k, dindexes.get(k)); } } } if (!extra_indexes.isEmpty()) System.out.println("/* --- Extra indexes ----------------------------------------- */"); Iterator eiter = extra_indexes.keySet().iterator(); while (eiter.hasNext()) { Object k = eiter.next(); System.out.println("drop index " + extra_indexes.get(k) + "; /* " + k + " */"); } if (!missing_indexes.isEmpty()) System.out.println("/* --- Missing indexes---------------------------------------- */"); Iterator miter = missing_indexes.keySet().iterator(); while (miter.hasNext()) { Object k = miter.next(); System.out.println("create index " + missing_indexes.get(k) + " on " + k + ";"); } } finally { conn.rollback(); conn.close(); } }
From source file:com.github.ukase.TestHelper.java
private static String getFileContent(String fileName, ClassLoader loader) throws IOException { InputStream stream = loader.getResourceAsStream(fileName); return StreamUtils.copyToString(stream, Charset.forName("UTF-8")); }
From source file:com.cognifide.aet.communication.api.metadata.SuiteReaderHelper.java
static Suite readSuiteFromFile(String resource, ClassLoader classLoader) throws IOException { String json = IOUtils.toString(classLoader.getResourceAsStream(resource)); return GSON.fromJson(json, new TypeToken<Suite>() { }.getType());/*from w w w.j a v a 2s .c om*/ }
From source file:Main.java
private static InputStream loadResourceInputStream(String file) throws FileNotFoundException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(file); if (inputStream == null) { throw new FileNotFoundException("File: '" + file + "', not found."); }/*from w w w . j a va 2 s . c om*/ return inputStream; }