List of usage examples for java.lang ClassLoader getSystemResource
public static URL getSystemResource(String name)
From source file:com.izforge.izpack.util.SelfModifier.java
/** * Retrieve the jar file the specified class was loaded from. * * @return null if file was not loaded from a jar file * @throws SecurityException if access to is denied by SecurityManager *///from w ww .jav a 2s . c o m public static File findJarFile(Class<?> clazz) { String resource = clazz.getName().replace('.', '/') + ".class"; URL url = ClassLoader.getSystemResource(resource); if (!"jar".equals(url.getProtocol())) { return null; } String path = url.getFile(); // starts at "file:..." (use getPath() as of 1.3) path = path.substring(0, path.lastIndexOf('!')); File file; // getSystemResource() returns a valid URL (eg. spaces are %20), but a // file // Constructed w/ it will expect "%20" in path. URI and File(URI) // properly file = new File(URI.create(path)); return file; }
From source file:com.navient.portal.portal.Settings.java
/** * Load the settings from the properties file *///from w w w . j av a 2 s .c o m public Settings() { FileReader reader = null; try { //reader = new FileReader(new File(System.getProperty("user.home") + "/portal_location.txt")); File pl = new File(System.getProperty("user.home") + "/portal_location.txt"); if (!pl.exists()) { pl.createNewFile(); } //portal_location = new Scanner(pl) // .useDelimiter("\\A").next().replaceAll("\\n", ""); user_prop_file = portal_location + "files/user.properties"; } catch (FileNotFoundException ex) { Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex); } try { String host = java.net.InetAddress.getLocalHost().getHostName(); if (host.contains(".")) { hostname = host.substring(0, host.indexOf(".")); } else { hostname = host; } } catch (UnknownHostException ex) { Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex); } prop = new Properties(); userprop = new Properties(); InputStream input = null; InputStream input2 = null; try { // Load the user properties file input = new FileInputStream(user_prop_file); userprop.load(input); // Load the portal properties file input2 = Portal.class.getClassLoader() .getResourceAsStream("com/navient/portal/resources/portal.properties"); if (input2 == null) { System.out.println("portal.properties not found."); System.out.println("input: " + input2); return; } prop.load(input2); // MISC //portal_location = userprop.getProperty("portal_location"); name = userprop.getProperty("name"); password = getPass(); //userprop.getProperty("password"); email_address = userprop.getProperty("email_address"); sop_file = userprop.getProperty("sop_file"); ldap_server = userprop.getProperty("ldap_server"); ssh_server = userprop.getProperty("ssh_server"); use_autocomplete = Boolean.parseBoolean(userprop.getProperty("use_autocomplete")); default_method = userprop.getProperty("default_method"); terminal_type = userprop.getProperty("terminal_cmd").split(" ")[0]; if (terminal_type.isEmpty()) { terminal_type = "gnome-terminal"; } opsware_server = userprop.getProperty("opsware_server"); releaseNotesFile = portal_location + "release_notes.txt"; aboutReleaseFile = portal_location + "files/about_release_notes.txt"; IconRedX = "com/navient/portal/resources/redx.png"; IconBlueCheck = "com/navient/portal/resources/bluecheck.png"; defaultSOP = userprop.getProperty("defaultSOP"); selectedTicketMasterInitial = userprop.getProperty("ticketmaster_initial"); // Terminal Settings selectedTerminalCmd = userprop.getProperty("selectedTerminalCmd"); terminal_cmd = userprop.getProperty("terminal_cmd"); termWidth = userprop.getProperty("termWidth"); termHeight = userprop.getProperty("termHeight"); termOptions = userprop.getProperty("termOptions"); // KEYWORDS keyword_ack = userprop.getProperty("keyword_ack"); keyword_close = userprop.getProperty("keyword_close"); keyword_ackclose = userprop.getProperty("keyword_ackclose"); keyword_translation = userprop.getProperty("keyword_translation"); keyword_rosh = userprop.getProperty("keyword_rosh"); keyword_gs = userprop.getProperty("keyword_gs"); keyword_silence = userprop.getProperty("keyword_silence"); keyword_update = userprop.getProperty("keyword_update"); keyword_ldap = userprop.getProperty("keyword_ldap"); keyword_ssh = userprop.getProperty("keyword_ssh"); keyword_faillog = userprop.getProperty("keyword_faillog"); keyword_notify = userprop.getProperty("keyword_notify"); keyword_completeco = userprop.getProperty("keyword_completeco"); keyword_createco = userprop.getProperty("keyword_createco"); keyword_mass = userprop.getProperty("keyword_mass"); keyword_help = userprop.getProperty("keyword_help"); keyword_updatepass = userprop.getProperty("keyword_updatepass"); keyword_settings = userprop.getProperty("keyword_settings"); keyword_lookup = userprop.getProperty("keyword_lookup"); keyword_term = userprop.getProperty("keyword_term"); keyword_decom = userprop.getProperty("keyword_decom"); keyword_tickets = userprop.getProperty("keyword_tickets"); keyword_oncall = userprop.getProperty("keyword_oncall"); keyword_patching = userprop.getProperty("keyword_patching"); keyword_widget = userprop.getProperty("keyword_widget"); keyword_monitoring = userprop.getProperty("keyword_monitoring"); keyword_systray = userprop.getProperty("keyword_systray"); gs_exp = portal_location + prop.getProperty("gs_exp"); rh_exp = portal_location + prop.getProperty("rh_exp"); gs_cmd_exp = portal_location + prop.getProperty("gs_cmd_exp"); gs_cmd_sh = portal_location + prop.getProperty("gs_cmd_sh"); silence_exp = portal_location + prop.getProperty("silence_exp"); silence_sh = portal_location + prop.getProperty("silence_sh"); launch_co_wiz_exp = portal_location + prop.getProperty("launch_co_wiz_exp"); push_sop_exp = portal_location + prop.getProperty("push_sop_exp"); get_sop_folder_list_exp = portal_location + prop.getProperty("get_sop_folder_list_exp"); fetch_all_exp = portal_location + prop.getProperty("fetch_all_exp"); fetch_one_exp = portal_location + prop.getProperty("fetch_one_exp"); fetch_mass_exp = portal_location + prop.getProperty("fetch_mass_exp"); ssh_ldap_exp = portal_location + prop.getProperty("ssh_ldap_exp"); term_users_exp = portal_location + prop.getProperty("term_users_exp"); fetch_co_tasks_exp = portal_location + prop.getProperty("fetch_co_tasks_exp"); decom_exp = portal_location + prop.getProperty("decom_exp"); fetch_ticket_info_exp = portal_location + prop.getProperty("fetch_ticket_info_exp"); ssh_exp = portal_location + prop.getProperty("ssh_exp"); envTest_exp = portal_location + prop.getProperty("envTest_exp"); // FILES translation_file = portal_location + prop.getProperty("translation_file"); ssh_config_file = portal_location + "files/server_list_file"; termlist_file = portal_location + prop.getProperty("termlist_file"); sop_location = portal_location + "SOP"; patching_html = prop.getProperty("patching_html"); patching_url = prop.getProperty("patching_url"); unx100_html_file = prop.getProperty("unx100_html_file"); //GlobalShell scripts ack_script = prop.getProperty("ack_script"); close_script = prop.getProperty("close_script"); silence_script = prop.getProperty("silence_script"); command_low = prop.getProperty("command_low"); command_std = prop.getProperty("command_std"); command_med = prop.getProperty("command_med"); command_task = prop.getProperty("command_task"); command_task_skip = prop.getProperty("command_task_skip"); command_owner = prop.getProperty("command_owner"); command_approve = prop.getProperty("command_approve"); listnonclosedtickets_script = prop.getProperty("listnonclosedtickets_script"); listopentickets_script = prop.getProperty("listopentickets_script"); listunassignedtickets_script = prop.getProperty("listunassignedtickets_script"); list_co_tasks_script = prop.getProperty("list_co_tasks_script"); co_wiz_script = prop.getProperty("co_wiz_script"); listticketinfo_script = prop.getProperty("listticketinfo_script"); listmytickets_script = prop.getProperty("listmytickets_script"); listcoproperties_script = prop.getProperty("listcoproperties_script"); setoncall_script = prop.getProperty("setoncall_script"); } catch (IOException e) { //e.printStackTrace(); MessageDialogs dialogs = new MessageDialogsImpl(); dialogs.showError("Can't load user.properties file.\n\nNo such file or directory."); System.out.println("Error: " + e.getMessage()); System.exit(1); } finally { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } // Splash Screens InputStream in; try { in = ClassLoader.getSystemResourceAsStream("com/navient/portal/resources/mass_loading.gif"); mass_splash = Toolkit.getDefaultToolkit().createImage(IOUtils.toByteArray(in)); imageURL = ClassLoader.getSystemResource("com/navient/portal/resources/nomatchfound.png"); splash_nomatch = new ImageIcon(imageURL); imageURL = ClassLoader.getSystemResource("com/navient/portal/resources/hold-your-horses.png"); splash_update = new ImageIcon(imageURL); in = ClassLoader.getSystemResourceAsStream("com/navient/portal/resources/tasks_loading.gif"); tasks_loading = Toolkit.getDefaultToolkit().createImage(IOUtils.toByteArray(in)); java.net.URL imageUrlStandby = ClassLoader.getSystemResource("com/navient/portal/resources/portal.png"); standbyIcon = new ImageIcon(imageUrlStandby).getImage(); in = ClassLoader.getSystemResourceAsStream("com/navient/portal/resources/systray_circle_loading.gif"); workingIcon = Toolkit.getDefaultToolkit().createImage(IOUtils.toByteArray(in)); //in = ClassLoader.getSystemResourceAsStream("resources/hold-your-horses.png"); //splash_nomatch = Toolkit.getDefaultToolkit().createImage(IOUtils.toByteArray(in)); //in = ClassLoader.getSystemResourceAsStream("resources/hold-your-horses.png"); //splash_update = Toolkit.getDefaultToolkit().createImage(IOUtils.toByteArray(in)); } catch (FileNotFoundException ex) { Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.apache.ambari.server.stack.StackDirectory.java
private void parseServicePort() { Map<String, Map<String, List<String>>> result = null; ObjectMapper mapper = new ObjectMapper(); try {//from www . jav a 2 s . co m TypeReference<Map<String, Map<String, List<String>>>> spElementTypeReference = new TypeReference<Map<String, Map<String, List<String>>>>() { }; if (spFilePath != null) { File file = new File(spFilePath); result = mapper.readValue(file, spElementTypeReference); LOG.info("Service port info was loaded from file: {}", file.getAbsolutePath()); } else { InputStream spInputStream = ClassLoader.getSystemResourceAsStream(AmbariMetaInfo.SP_FILE_NAME); if (spInputStream != null) { result = mapper.readValue(spInputStream, spElementTypeReference); LOG.info("Service port info was loaded from classpath: " + ClassLoader.getSystemResource(AmbariMetaInfo.SP_FILE_NAME)); } } servicePort = new StackServicePort(result); } catch (IOException e) { LOG.error(String.format("Can not read service port info %s", spFilePath), e); } }
From source file:org.apache.tajo.engine.planner.TestPlannerUtil.java
@Test public void testGetNonZeroLengthDataFiles() throws Exception { String queryFiles = ClassLoader.getSystemResource("queries").toString() + "/TestSelectQuery"; Path path = new Path(queryFiles); TableDesc tableDesc = new TableDesc(); tableDesc.setName("Test"); tableDesc.setPath(path);/* w w w . j a v a2 s. com*/ FileSystem fs = path.getFileSystem(util.getConfiguration()); List<Path> expectedFiles = new ArrayList<Path>(); RemoteIterator<LocatedFileStatus> files = fs.listFiles(path, true); while (files.hasNext()) { LocatedFileStatus file = files.next(); if (file.isFile() && file.getLen() > 0) { expectedFiles.add(file.getPath()); } } int fileNum = expectedFiles.size() / 5; int numResultFiles = 0; for (int i = 0; i <= 5; i++) { int start = i * fileNum; FragmentProto[] fragments = PlannerUtil.getNonZeroLengthDataFiles(util.getConfiguration(), tableDesc, start, fileNum); assertNotNull(fragments); numResultFiles += fragments.length; int expectedSize = fileNum; if (i == 5) { //last expectedSize = expectedFiles.size() - (fileNum * 5); } comparePath(expectedFiles, fragments, start, expectedSize); } assertEquals(expectedFiles.size(), numResultFiles); }
From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java
protected String[] listResources() throws IOException, URISyntaxException { String[] files = new String[0]; URL dirURL = ClassLoader.getSystemResource(schemaPath); FilenameFilter fileFilter = new FilenameFilter() { @Override/*from w w w . ja va 2s. co m*/ public boolean accept(File dir, String name) { return ((name.lastIndexOf('.') > -1) && (".xml".equalsIgnoreCase(name.substring(name.lastIndexOf('.'))))); } }; if (dirURL == null) { throw new FileNotFoundException(schemaPath); } if (dirURL.getProtocol().equals("file")) { files = listFileResources(dirURL, schemaPath, fileFilter); } if (dirURL.getProtocol().equals("jar")) { files = listJarResources(dirURL, fileFilter); } return files; }
From source file:org.apache.james.mailbox.elasticsearch.json.MessageToElasticSearchJsonTest.java
@Test public void spamEmailShouldBeWellConvertedToJsonWithApacheTika() throws IOException { MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson( new TikaTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES); MailboxMessage spamMail = new SimpleMailboxMessage(MESSAGE_ID, date, SIZE, BODY_START_OCTET, new SharedByteArrayInputStream( IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/nonTextual.eml"))), new Flags(), propertyBuilder, MAILBOX_ID); spamMail.setUid(UID);//from w w w . ja va2 s . co m spamMail.setModSeq(MOD_SEQ); assertThatJson(messageToElasticSearchJson.convertToJson(spamMail, ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER) .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/nonTextual.json"), CHARSET)); }
From source file:gui.GW2EventerGui.java
/** * Creates new form GW2EventerGui/*from ww w .j a v a2s . c om*/ */ public GW2EventerGui() { this.guiIcon = new ImageIcon(ClassLoader.getSystemResource("media/icon.png")).getImage(); if (System.getProperty("os.name").startsWith("Windows")) { this.OS = "Windows"; this.isWindows = true; } else { this.OS = "Other"; this.isWindows = false; } if (this.isWindows == true) { this.checkIniDir(); } initComponents(); this.speakQueue = new LinkedList(); this.speakRunnable = new Runnable() { @Override public void run() { String path = System.getProperty("user.home") + "\\.gw2eventer"; File f; String sentence; while (!speakQueue.isEmpty()) { f = new File(path + "\\tts.vbs"); if (!f.exists() && !f.isDirectory()) { sentence = (String) speakQueue.poll(); try { Writer writer = new OutputStreamWriter( new FileOutputStream( System.getProperty("user.home") + "\\.gw2eventer\\tts.vbs"), "ISO-8859-15"); BufferedWriter fout = new BufferedWriter(writer); fout.write("Dim Speak"); fout.newLine(); fout.write("Set Speak=CreateObject(\"sapi.spvoice\")"); fout.newLine(); fout.write("Speak.Speak \"" + sentence + "\""); fout.close(); Runtime rt = Runtime.getRuntime(); try { if (sentence.length() > 0) { Process p = rt.exec(System.getProperty("user.home") + "\\.gw2eventer\\tts.bat"); } } catch (IOException ex) { Logger.getLogger(GW2EventerGui.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { Logger.getLogger(GW2EventerGui.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GW2EventerGui.class.getName()).log(Level.SEVERE, null, ex); } try { Thread.sleep(3000); } catch (InterruptedException ex) { Logger.getLogger(GW2EventerGui.class.getName()).log(Level.SEVERE, null, ex); } } else { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(GW2EventerGui.class.getName()).log(Level.SEVERE, null, ex); } } } } }; this.matchIds = new HashMap(); this.matchId = "2-6"; this.matchIdColor = "green"; this.jLabelNewVersion.setVisible(false); this.updateInformed = false; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(screenSize.width / 2 - this.getSize().width / 2, (screenSize.height / 2 - this.getSize().height / 2) - 20); double width = screenSize.getWidth(); double height = screenSize.getHeight(); if ((width == 1280) && (height == 720 || height == 768 || height == 800)) { this.setExtendedState(this.MAXIMIZED_BOTH); //this.setLocation(0, 0); } JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) this.jSpinnerRefreshTime.getEditor(); DefaultFormatter formatter = (DefaultFormatter) jsEditor.getTextField().getFormatter(); formatter.setAllowsInvalid(false); /* jsEditor = (JSpinner.NumberEditor)this.jSpinnerOverlayX.getEditor(); formatter = (DefaultFormatter) jsEditor.getTextField().getFormatter(); formatter.setAllowsInvalid(false); jsEditor = (JSpinner.NumberEditor)this.jSpinnerOverlayY.getEditor(); formatter = (DefaultFormatter) jsEditor.getTextField().getFormatter(); formatter.setAllowsInvalid(false); */ this.workingButton = this.jButtonRefresh; this.refreshSelector = this.jCheckBoxAutoRefresh; this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { apiManager.saveSettingstoFile(); System.exit(0); } }); this.pushGui = new PushGui(this, true, "", ""); this.pushGui.setIconImage(guiIcon); this.donateGui = new DonateGui(this, true); this.donateGui.setIconImage(guiIcon); this.infoGui = new InfoGui(this, true); this.infoGui.setIconImage(guiIcon); this.feedbackGui = new FeedbackGui(this, true); this.feedbackGui.setIconImage(guiIcon); this.overlayGui = new OverlayGui(this); this.initOverlayGui(); this.settingsOverlayGui = new SettingsOverlayGui(this); this.initSettingsOverlayGui(); this.wvwOverlayGui = new WvWOverlayGui(this); this.initWvwOverlayGui(); this.language = "en"; this.worldID = "2206"; //Millersund [DE] this.setTranslations(); this.eventLabels = new ArrayList(); this.eventLabelsTimer = new ArrayList(); this.homeWorlds = new HashMap(); this.preventSystemSleep = true; for (int i = 1; i <= EVENT_COUNT; i++) { try { Field f = getClass().getDeclaredField("labelEvent" + i); JLabel l = (JLabel) f.get(this); l.setPreferredSize(new Dimension(70, 28)); //l.setToolTipText(""); //int width2 = l.getX(); //int height2 = l.getY(); //System.out.println("$coords .= \"{\\\"x\\\": \\\""+ width2 + "\\\", \\\"y\\\": \\\""+ height2 + "\\\"},\\n\";"); this.eventLabels.add(l); final int ii = i; l.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { showSoundSelector(ii); } }); f = getClass().getDeclaredField("labelTimer" + i); l = (JLabel) f.get(this); l.setEnabled(true); l.setVisible(false); l.setForeground(Color.green); //int width2 = l.getX(); //int height2 = l.getY(); //System.out.println("$coords2 .= \"{\\\"x\\\": \\\""+ width2 + "\\\", \\\"y\\\": \\\""+ height2 + "\\\"},\\n\";"); this.eventLabelsTimer.add(l); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(GW2EventerGui.class.getName()).log(Level.SEVERE, null, ex); } } int[] disabledEvents = { 6, 8, 11, 12, 17, 18, 19, 20, 21, 22 }; for (int i = 0; i < disabledEvents.length; i++) { Field f; JLabel l; try { f = getClass().getDeclaredField("labelEvent" + disabledEvents[i]); l = (JLabel) f.get(this); l.setEnabled(false); l.setVisible(false); f = getClass().getDeclaredField("labelTimer" + disabledEvents[i]); l = (JLabel) f.get(this); l.setEnabled(false); l.setVisible(false); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(GW2EventerGui.class.getName()).log(Level.SEVERE, null, ex); } } this.lastPush = new Date(); if (this.apiManager == null) { this.apiManager = new ApiManager(this, this.jSpinnerRefreshTime, this.jCheckBoxAutoRefresh.isSelected(), this.eventLabels, this.language, this.worldID, this.homeWorlds, this.jComboBoxHomeWorld, this.jLabelServer, this.jLabelWorking, this.jCheckBoxPlaySounds.isSelected(), this.workingButton, this.refreshSelector, this.eventLabelsTimer, this.jComboBoxLanguage, this.overlayGui, this.jCheckBoxWvWOverlay); } //this.wvwMatchReader = new WvWMatchReader(this.matchIds, this.jCheckBoxWvW); //this.wvwMatchReader.start(); this.preventSleepMode(); this.runUpdateService(); this.runPushService(); this.runTips(); //this.runTest(); }
From source file:org.openadaptor.util.FileUtils.java
/** * Searches the classpath for a named file * /*from w w w .j a v a 2s .c o m*/ * @param name * the name of the file to search for * * @return pointer to the named file or null if it doesn't exist */ public static File searchClasspath(String name) { log.debug("Searching classpath for: " + name); // just on the offchange that the file is in the working directory or we // were supplied a correct path to the file File f = new File(name); if (f.exists()) { log.debug("Found file: " + f.getPath()); return f; } // try the classpath URL url = ClassLoader.getSystemResource(name); if (url != null) { log.debug("Found file: " + url.getPath()); return new File(url.getPath()); } log.warn("File not found"); return null; }
From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.InMemoryDatasourceServiceImpl.java
private String getUploadFilePath() throws DatasourceServiceException { try {//from ww w.j ava2 s .co m URL url = ClassLoader.getSystemResource(DEFAULT_UPLOAD_FILEPATH_FILE_NAME); URI uri = url.toURI(); File file = new File(uri); FileInputStream fis = new FileInputStream(file); try { Properties properties = new Properties(); properties.load(fis); return (String) properties.get(UPLOAD_FILE_PATH); } finally { fis.close(); } } catch (Exception e) { throw new DatasourceServiceException(e); } }
From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java
protected void loadFromXmlFiles() throws IOException, XMLStreamException, URISyntaxException { XMLInputFactory xmlIf = XMLInputFactory.newInstance(); final List<StoreObject> storeObjects = new ArrayList<>(); xmlIf.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); for (String resname : listResources()) { URL filePath = ClassLoader.getSystemResource(resname); if (filePath == null) { throw new FileNotFoundException(resname); }//from ww w. ja v a 2 s .c o m loadFromXmlFile(xmlIf, filePath, storeObjects); } mergeXmlSchemas(storeObjects); }