private JarFile getCachedJarFile(URL url) { JarFile result = (JarFile) fileCache.get(url); /* if the JAR file is cached, the permission will always be there */ if (result != null) { Permission perm = getPermission(result); if (perm != null) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { sm.checkPermission(perm); } catch (SecurityException se) { // fallback to checkRead/checkConnect for pre 1.2 // security managers if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) { sm.checkRead(perm.getName()); } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) { sm.checkConnect(url.getHost(), url.getPort()); } else { throw se; } } } } } return result; }
public boolean shutdown(int port, boolean ssl) { try { String protocol = "http" + (ssl ? "s" : ""); URL url = new URL(protocol, "127.0.0.1", port, "shutdown"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("servicemanager", "shutdown"); conn.connect(); StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); int n; char[] cbuf = new char[1024]; while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n); br.close(); String message = sb.toString().replace("<br>", "\n"); if (message.contains("Goodbye")) { cp.appendln("Shutting down the server:"); String[] lines = message.split("\n"); for (String line : lines) { cp.append("..."); cp.appendln(line); } return true; } } catch (Exception ex) { } cp.appendln("Unable to shutdown CTP"); return false; }
static { Attributes m = null; final URL loc = Prop.LOCATION; if (loc != null) { final String jar = loc.getFile(); try { final ClassLoader cl = JarManifest.class.getClassLoader(); final Enumeration<URL> list = cl.getResources("META-INF/MANIFEST.MF"); while (list.hasMoreElements()) { final URL url = list.nextElement(); if (!url.getFile().contains(jar)) continue; final InputStream in = url.openStream(); try { m = new Manifest(in).getMainAttributes(); break; } finally { in.close(); } } } catch (final IOException ex) { Util.errln(ex); } } MAP = m; }
public Set<String> listResources(String subdir) { try { Set<String> result = new HashSet<String>(); if (resourceURL != null) { String protocol = resourceURL.getProtocol(); if (protocol.equals("jar")) { String resPath = resourceURL.getPath(); int pling = resPath.lastIndexOf("!"); URL jarURL = new URL(resPath.substring(0, pling)); String resDirInJar = resPath.substring(pling + 2); String prefix = resDirInJar + subdir + "/"; // System.out.printf("BaseMod.listResources: looking for names starting with %s\n", // prefix); JarFile jar = new JarFile(new File(jarURL.toURI())); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(prefix) && !name.endsWith("/") && !name.contains("/.")) { // System.out.printf("BaseMod.listResources: name = %s\n", name); result.add(name.substring(prefix.length())); } } } else throw new RuntimeException("Resource URL protocol " + protocol + " not supported"); } return result; } catch (Exception e) { throw new RuntimeException(e); } }
protected void addPathFile(final File pathComponent) throws IOException { if (!this.pathComponents.contains(pathComponent)) { this.pathComponents.addElement(pathComponent); } if (pathComponent.isDirectory()) { return; } final String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + pathComponent.lastModified() + "-" + pathComponent.length(); String classpath = AntClassLoader.pathMap.get(absPathPlusTimeAndLength); if (classpath == null) { JarFile jarFile = null; try { jarFile = new JarFile(pathComponent); final Manifest manifest = jarFile.getManifest(); if (manifest == null) { return; } classpath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); } finally { if (jarFile != null) { jarFile.close(); } } if (classpath == null) { classpath = ""; } AntClassLoader.pathMap.put(absPathPlusTimeAndLength, classpath); } if (!"".equals(classpath)) { final URL baseURL = AntClassLoader.FILE_UTILS.getFileURL(pathComponent); final StringTokenizer st = new StringTokenizer(classpath); while (st.hasMoreTokens()) { final String classpathElement = st.nextToken(); final URL libraryURL = new URL(baseURL, classpathElement); if (!libraryURL.getProtocol().equals("file")) { this.log( "Skipping jar library " + classpathElement + " since only relative URLs are supported by this" + " loader", 3); } else { final String decodedPath = Locator.decodeUri(libraryURL.getFile()); final File libraryFile = new File(decodedPath); if (!libraryFile.exists() || this.isInPath(libraryFile)) { continue; } this.addPathFile(libraryFile); } } } }
/** * Returns a stream to a pack, depending on the installation kind. * * @param n The pack number. * @return The stream. * @exception Exception Description of the Exception */ private InputStream getPackAsStream(int n) throws Exception { InputStream in = null; if (idata.kind.equalsIgnoreCase("standard") || idata.kind.equalsIgnoreCase("standard-kunststoff")) in = getClass().getResourceAsStream("/packs/pack" + n); else if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) { URL url = new URL("jar:" + jarLocation + "!/packs/pack" + n); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); in = jarConnection.getInputStream(); } return in; }
public AppFrame() { super(); GlobalData.oFrame = this; this.setSize(this.width, this.height); this.toolkit = Toolkit.getDefaultToolkit(); Dimension w = toolkit.getScreenSize(); int fx = (int) w.getWidth(); int fy = (int) w.getHeight(); int wx = (fx - this.width) / 2; int wy = (fy - this.getHeight()) / 2; setLocation(wx, wy); this.tracker = new MediaTracker(this); String sHost = ""; try { localAddr = InetAddress.getLocalHost(); if (localAddr.isLoopbackAddress()) { localAddr = LinuxInetAddress.getLocalHost(); } sHost = localAddr.getHostAddress(); } catch (UnknownHostException ex) { sHost = "你的IP地址错误"; } // this.textLines[0] = "服务器正在运行."; this.textLines[1] = ""; this.textLines[2] = "你的IP地址: " + sHost; this.textLines[3] = ""; this.textLines[4] = "请打开你的手机客户端"; this.textLines[5] = ""; this.textLines[6] = "输入屏幕上显示的IP地址."; // try { URL fileURL = this.getClass().getProtectionDomain().getCodeSource().getLocation(); String sBase = fileURL.toString(); if ("jar".equals(sBase.substring(sBase.length() - 3, sBase.length()))) { jar = new JarFile(new File(fileURL.toURI())); } else { basePath = System.getProperty("user.dir") + "\\res\\"; } } catch (Exception ex) { this.textLines[1] = "exception: " + ex.toString(); } }
/** * Enumerates the resouces in a give package name. This works even if the resources are loaded * from a jar file! * * <p>Adapted from code by mikewse on the java.sun.com message boards. * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984 * * @param packageName The package to enumerate * @return A Set of Strings for each resouce in the package. */ public static Set getResoucesInPackage(String packageName) throws IOException { String localPackageName; if (packageName.endsWith("/")) { localPackageName = packageName; } else { localPackageName = packageName + '/'; } Enumeration dirEnum = ClassLoader.getSystemResources(localPackageName); Set names = new HashSet(); // Loop CLASSPATH directories while (dirEnum.hasMoreElements()) { URL resUrl = (URL) dirEnum.nextElement(); // Pointing to filesystem directory if (resUrl.getProtocol().equals("file")) { File dir = new File(resUrl.getFile()); File[] files = dir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) continue; names.add(localPackageName + file.getName()); } } // Pointing to Jar file } else if (resUrl.getProtocol().equals("jar")) { JarURLConnection jconn = (JarURLConnection) resUrl.openConnection(); JarFile jfile = jconn.getJarFile(); Enumeration entryEnum = jfile.entries(); while (entryEnum.hasMoreElements()) { JarEntry entry = (JarEntry) entryEnum.nextElement(); String entryName = entry.getName(); // Exclude our own directory if (entryName.equals(localPackageName)) continue; String parentDirName = entryName.substring(0, entryName.lastIndexOf('/') + 1); if (!parentDirName.equals(localPackageName)) continue; names.add(entryName); } } else { // Invalid classpath entry } } return names; }
private static String[] findStandardMBeans(URL codeBase) throws Exception { Set<String> names; if (codeBase.getProtocol().equalsIgnoreCase("file") && codeBase.toString().endsWith("/")) names = findStandardMBeansFromDir(codeBase); else names = findStandardMBeansFromJar(codeBase); Set<String> standardMBeanNames = new TreeSet<String>(); for (String name : names) { if (name.endsWith("MBean")) { String prefix = name.substring(0, name.length() - 5); if (names.contains(prefix)) standardMBeanNames.add(prefix); } } return standardMBeanNames.toArray(new String[0]); }
JarFile get(URL url, boolean useCaches) throws IOException { JarFile result = null; JarFile local_result = null; if (useCaches) { synchronized (this) { result = getCachedJarFile(url); } if (result == null) { local_result = URLJarFile.getJarFile(url); synchronized (this) { result = getCachedJarFile(url); if (result == null) { fileCache.put(url, local_result); urlCache.put(local_result, url); result = local_result; } else { if (local_result != null) { local_result.close(); } } } } } else { result = URLJarFile.getJarFile(url); } if (result == null) throw new FileNotFoundException(url.toString()); return result; }
/** * Enables to get the name of an object in the spoken language thanks to the jar file * * @param jarName the file that contains the object classes * @return the object name in the spoken language */ private String getLangName(File jarName) { String name = null; try { URL url = jarName.toURI().toURL(); JarInputStream jarFile = new JarInputStream(url.openStream()); JarEntry jarEntry = jarFile.getNextJarEntry(); while (jarEntry != null) { if (!jarEntry.isDirectory() && jarEntry.getName().contains(Configuration.instance().getLanguage())) { int lang_index = jarEntry.getName().lastIndexOf(Configuration.instance().getLanguage()); name = jarEntry.getName().substring(lang_index + 3, jarEntry.getName().length() - 6); } jarEntry = jarFile.getNextJarEntry(); } } catch (Exception e) { LOG.error("Error getLangName " + jarName + " " + e); } return name; }
private boolean checkServer(int port, boolean ssl) { try { URL url = new URL("http://127.0.0.1:" + port); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); int length = conn.getContentLength(); StringBuffer text = new StringBuffer(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int size = 256; char[] buf = new char[size]; int len; while ((len = isr.read(buf, 0, size)) != -1) text.append(buf, 0, len); isr.close(); if (programName.equals("ISN")) return !shutdown(port, ssl); return true; } catch (Exception ex) { return false; } }
private static Set<String> findStandardMBeansFromJar(URL codeBase) throws Exception { InputStream is = codeBase.openStream(); JarInputStream jis = new JarInputStream(is); Set<String> names = new TreeSet<String>(); JarEntry entry; while ((entry = jis.getNextJarEntry()) != null) { String name = entry.getName(); if (!name.endsWith(".class")) continue; name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); names.add(name); } return names; }
/** Given a URL, retrieves a JAR file, caches it to disk, and creates a cached JAR file object. */ private static JarFile retrieve(final URL url) throws IOException { JarFile result = null; /* get the stream before asserting privileges */ final InputStream in = url.openConnection().getInputStream(); try { result = (JarFile) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws IOException { OutputStream out = null; try { File tmpFile = File.createTempFile("jar_cache", null); tmpFile.deleteOnExit(); out = new FileOutputStream(tmpFile); int read = 0; byte[] buf = new byte[BUF_SIZE]; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); } out.close(); out = null; return new URLJarFile(tmpFile); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }); } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } return result; }
URLConnection getConnection(JarFile jarFile) throws IOException { URL u = (URL) urlCache.get(jarFile); if (u != null) return u.openConnection(); return null; }
public String what(String key, boolean oneliner) throws Exception { byte[] sha; Matcher m = SHA_P.matcher(key); if (m.matches()) { sha = Hex.toByteArray(key); } else { m = URL_P.matcher(key); if (m.matches()) { URL url = new URL(key); sha = SHA1.digest(url.openStream()).digest(); } else { File jarfile = new File(key); if (!jarfile.exists()) { reporter.error("File does not exist: %s", jarfile.getCanonicalPath()); } sha = SHA1.digest(jarfile).digest(); } } reporter.trace("sha %s", Hex.toHexString(sha)); Revision revision = library.getRevision(sha); if (revision == null) { return null; } StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); Justif justif = new Justif(120, 20, 70, 20, 75); DateFormat dateFormat = DateFormat.getDateInstance(); try { if (oneliner) { f.format("%20s %s%n", Hex.toHexString(revision._id), createCoord(revision)); } else { f.format("Artifact: %s%n", revision.artifactId); if (revision.organization != null && revision.organization.name != null) { f.format(" (%s)", revision.organization.name); } f.format("%n"); f.format("Coordinates\t0: %s%n", createCoord(revision)); f.format("Created\t0: %s%n", dateFormat.format(new Date(revision.created))); f.format("Size\t0: %d%n", revision.size); f.format("Sha\t0: %s%n", Hex.toHexString(revision._id)); f.format("URL\t0: %s%n", createJpmLink(revision)); f.format("%n"); f.format("%s%n", revision.description); f.format("%n"); f.format("Dependencies\t0:%n"); boolean flag = false; Iterable<RevisionRef> closure = library.getClosure(revision._id, true); for (RevisionRef dep : closure) { f.format( " - %s \t2- %s \t3- %s%n", dep.name, createCoord(dep), dateFormat.format(new Date(dep.created))); flag = true; } if (!flag) { f.format(" None%n"); } f.format("%n"); } f.flush(); justif.wrap(sb); return sb.toString(); } finally { f.close(); } }
private static Set<String> findStandardMBeansFromDir(URL codeBase) throws Exception { File dir = new File(new URI(codeBase.toString())); Set<String> names = new TreeSet<String>(); scanDir(dir, "", names); return names; }
private static boolean isFileURL(URL url) { return url.getProtocol().equalsIgnoreCase("file"); }
private URLJarFile(URL url) throws IOException { super(ParseUtil.decode(url.getFile())); }