/** INTERNAL: Return the create table statement. */ public Writer buildCreationWriter(AbstractSession session, Writer writer) throws ValidationException { try { DatabasePlatform platform = session.getPlatform(); writer.write("CREATE PACKAGE " + getFullName()); writer.write(" AS"); writer.write("\n"); for (Enumeration statementsEnum = getStatements().elements(); statementsEnum.hasMoreElements(); ) { writer.write((String) statementsEnum.nextElement()); writer.write(platform.getBatchDelimiterString()); writer.write("\n"); } for (Enumeration proceduresEnum = getProcedures().elements(); proceduresEnum.hasMoreElements(); ) { writer.write("\n"); String procedureString = ((StoredProcedureDefinition) proceduresEnum.nextElement()) .buildCreationWriter(session, writer) .toString(); writer.write(procedureString.substring(7, procedureString.length())); writer.write("\n"); } writer.write(platform.getBatchEndString()); writer.write("\n" + session.getPlatform().getStoredProcedureTerminationToken()); } catch (IOException ioException) { throw ValidationException.fileError(ioException); } return writer; }
private void exportAcl(Acl acl) { if (acl != null) { ArrayList<String> propval = new ArrayList<String>(); for (Enumeration<AclEntry> ee = acl.entries(); ee.hasMoreElements(); ) { AclEntry ae = ee.nextElement(); StringBuilder sb = new StringBuilder(); sb.append("ALLOW \""); sb.append(ae.getPrincipal().getName()); sb.append("\" "); for (Enumeration<Permission> permissions = ae.permissions(); permissions.hasMoreElements(); ) { Permission perm = permissions.nextElement(); sb.append(perm.getActions()); sb.append(","); } propval.add(sb.toString()); } exportProperty("wiki:acl", propval.toArray(new String[propval.size()]), STRING); } }
///////////////////////////////////////////////////////// Crear un archivo de un grafo // /////////////////////////////////////////////// public void guardar(Grafo g, String n) throws IOException { File archivo = new File( "C:/Documents and Settings/Administrator/Desktop/Proyecto1 06-40476,06-40273/bin/doc/Guardado.txt"); int count; int tamL; int tamV; FileWriter txt = new FileWriter(archivo); PrintWriter out = new PrintWriter(txt); tamL = CjtoLados.size(); tamV = CjtoVertice.size(); out.println("Grafo g\n"); out.println("Numero de Vertices: " + tamV); out.println("Numeros de Lados: " + tamL); out.println("Vértices:"); for (Enumeration e = CjtoVertice.keys(); e.hasMoreElements(); ) { String X = (String) e.nextElement(); Vertice y = (Vertice) CjtoVertice.get(X); out.println(X); } out.println("Lados:"); for (Enumeration e = CjtoLados.keys(); e.hasMoreElements(); ) { String v = (String) e.nextElement(); Lado w = (Lado) CjtoLados.get(v); out.println(v); } out.close(); };
// Write <Cluster>.ini file // Given Hashtable mapping cluster name to Vector of plugin names // <Cluster>.ini File format: // [ Cluster ] // uic = <Agentname> // cloned = false // [ Plugins ] // plugin = <pluginname> // ... // private void dumpClusterInfo(Hashtable all_clusters, String path) throws IOException { // Dump hashtable of clusters for (Enumeration e = all_clusters.keys(); e.hasMoreElements(); ) { String cluster_name = (String) e.nextElement(); PrintWriter cluster_file; try { if (path != null) { cluster_file = createPrintWriter(path + File.separator + cluster_name + ".ini"); } else { cluster_file = createPrintWriter(cluster_name + ".ini"); } cluster_file.println("[ Cluster ]"); cluster_file.println("uic = " + cluster_name); cluster_file.println("cloned = false\n"); cluster_file.println("[ Plugins ]"); Vector plugins = (Vector) (all_clusters.get(cluster_name)); for (Enumeration p = plugins.elements(); p.hasMoreElements(); ) { String plugin = (String) (p.nextElement()); cluster_file.println("plugin = " + plugin); } cluster_file.close(); } catch (IOException exc) { System.out.println("IOException: " + exc); System.exit(-1); } } }
/** * Provede prihlaseni uzivatele Odesle mu seznam aktualnich uzivatelu a r ozesle informaci o * prihlaseni ostatnim uzivatelum * * @param serverThread Vlakno serveru */ public synchronized boolean login(ServerThread serverThread) { if (clients.containsKey(serverThread.getLogin().toLowerCase())) { return false; } // Send login info to other clients Enumeration<ServerThread> e = getClients().elements(); while (e.hasMoreElements()) { e.nextElement().userLogin(serverThread.getLogin()); } // Send users list to client Enumeration<ServerThread> e2 = getClients().elements(); while (e2.hasMoreElements()) { ServerThread serverThread2 = e2.nextElement(); serverThread.userLogin(serverThread2.getLogin()); if (serverThread2.getServerGame() != null) { serverThread.userInGame(serverThread2.getLogin()); } } // Append client to list clients.put(serverThread.getLogin().toLowerCase(), serverThread); return true; }
// function to do the join use case public static void share() throws Exception { HttpPost method = new HttpPost(url + "/share"); String ipAddress = null; Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) en.nextElement(); if (ni.getName().equals("eth0")) { Enumeration<InetAddress> en2 = ni.getInetAddresses(); while (en2.hasMoreElements()) { InetAddress ip = (InetAddress) en2.nextElement(); if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } break; } } method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } // get present time date = new Date(); long start = date.getTime(); // Execute the vishwa share process Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp); String ch = "alive"; System.out.println("Type kill to unjoin from the grid"); while (!ch.equals("kill")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ch = in.readLine(); } p.destroy(); date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/shareAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
/** * @param props * @exception IllegalArgumentException */ public synchronized void copyFrom(Dictionary props) throws IllegalArgumentException { Enumeration keys = props.keys(); Enumeration values = props.elements(); while (keys.hasMoreElements()) { put(keys.nextElement(), values.nextElement()); } }
/** * ********************************************************************** Prints the iniFile. * * @param ps The <code>PrintStream</code> to which to print. */ public void printProps(PrintStream ps) { Enumeration se = getSectionList(); if (se == null) { ps.println(errMsg); } else { while (se.hasMoreElements()) { String sname = (String) se.nextElement(); setSection(sname); ps.println("[" + sname + "]"); Enumeration pe = getPropList(sname); while (pe.hasMoreElements()) { String pair[] = (String[]) pe.nextElement(); String prop = pair[0]; String valu = getProperty(prop); ps.println(" \"" + prop + "\" = \"" + valu + "\""); } } } }
private Core() { boolean f = false; try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = (NetworkInterface) en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { String ipAddress = inetAddress.getHostAddress().toString(); this.ip = inetAddress; f = true; break; } } if (f) break; } } catch (SocketException ex) { ex.printStackTrace(); System.exit(1); } this.teams = new HashMap<String, Team>(); this.judges = new HashMap<String, Judge>(); this.problems = new HashMap<String, ProblemInfo>(); this.scheduler = new Scheduler(); this.timer = new ContestTimer(300 * 60); try { readConfigure(); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort); }
// Generate files for given node // Given Hashtable mapping node_name to Vector of cluster names // <Node>.ini File format: // [ Clusters ] // cluster = <clustername> // ... private void dumpNodeInfo(Hashtable all_nodes, String path) throws IOException { PrintWriter node_file; // Iterate over hashtable of nodes and write <Node>.ini file for each for (Enumeration e = all_nodes.keys(); e.hasMoreElements(); ) { String node_name = (String) (e.nextElement()); try { if (path != null) { node_file = createPrintWriter(path + File.separator + node_name + ".ini"); } else { node_file = createPrintWriter(node_name + ".ini"); } node_file.println("[ Clusters ]"); Vector clusters = (Vector) all_nodes.get(node_name); for (Enumeration c = clusters.elements(); c.hasMoreElements(); ) { String cluster_name = (String) (c.nextElement()); node_file.println("cluster = " + cluster_name); } node_file.close(); } catch (IOException exc) { System.out.println("IOException: " + exc); System.exit(-1); } } }
public String toString() { String roles_image = ""; for (Enumeration e = myRoles.elements(); e.hasMoreElements(); ) { roles_image = roles_image + "/" + (String) e.nextElement(); } String relations_image = ""; for (Enumeration e = mySupportRelations.elements(); e.hasMoreElements(); ) { relations_image = relations_image + "/" + (SupportRelation) e.nextElement(); } return "#<Organization " + myName + " " + myUIC + " " + myUTC + " " + mySRC + " " + mySuperior + " " + myEchelon + " " + myAgency + " " + myService + " " + myNomenclature + " " + myPrototype + " " + roles_image + " " + relations_image + ">"; }
/** * Update the layouts tree. * * @param current The name of the current layout or <CODE>null</CODE> if none. */ public void updateLayouts(Path current) throws PipelineException { DefaultMutableTreeNode root = null; { root = new DefaultMutableTreeNode(new TreeData(), true); { Path path = new Path(PackageInfo.getSettingsPath(), "layouts"); rebuildTreeModel(path, new Path("/"), root); } DefaultTreeModel model = (DefaultTreeModel) pTree.getModel(); model.setRoot(root); { Enumeration e = root.depthFirstEnumeration(); if (e != null) { while (e.hasMoreElements()) { DefaultMutableTreeNode tnode = (DefaultMutableTreeNode) e.nextElement(); pTree.expandPath(new TreePath(tnode.getPath())); } } } } pTree.clearSelection(); if (current != null) { TreePath tpath = null; DefaultMutableTreeNode tnode = root; for (String comp : current.getComponents()) { DefaultMutableTreeNode next = null; Enumeration e = tnode.children(); if (e != null) { while (e.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) e.nextElement(); TreeData data = (TreeData) child.getUserObject(); if (data.toString().equals(comp)) { tpath = new TreePath(child.getPath()); next = child; break; } } } if (next == null) break; tnode = next; } if (tpath != null) { pTree.setSelectionPath(tpath); pTree.makeVisible(tpath); } } }
/** * Writes this object to the stream passed. The object can be loaded again via its readObject * method. * * @param os strream to write data to. * @exception Exception if error of any kind occurs */ public synchronized void writeObject(OutputStream os) throws Exception { Enumeration keys = keys(); Enumeration values = elements(); PDataStream.writeInt(size(), os); // dictionary is never empty: // it either has elements or is null while (keys.hasMoreElements()) { PDataStream.writeUTF((String) keys.nextElement(), os); writeValue(values.nextElement(), os); } }
/** * find a level by its type in a scheme. This involves iterating through the list of levels. The * main reason for doing it this way is to avoid being dependent on the order in which the levels * are coded in the xml, which is not explicitly constrained. */ private Level findLevel(Scheme scheme, LevelTypeList levelType) { Level level = null; for (Enumeration e = scheme.enumerateLevel(); e.hasMoreElements(); ) { Level lev = (Level) e.nextElement(); if (lev.getType() == levelType) { level = lev; break; } } if (level == null) throw new Error("Couldn't find type " + levelType + " in scheme " + scheme); return level; }
/** * INTERNAL: Return the value for in memory comparison. This is only valid for valueable * expressions. */ public Object valueFromObject( Object object, AbstractSession session, AbstractRecord translationRow, int valueHolderPolicy, boolean isObjectUnregistered) { // The expression may be across a relationship, in which case it must be traversed. if ((!getBaseExpression().isExpressionBuilder()) && getBaseExpression().isQueryKeyExpression()) { object = getBaseExpression() .valueFromObject( object, session, translationRow, valueHolderPolicy, isObjectUnregistered); // toDo: Null means the join filters out the row, returning null is not correct if an inner // join, // outer/inner joins need to be fixed to filter correctly. if (object == null) { return null; } // If from an anyof the object will be a collection of values, // A new vector must union the object values and the values extracted from it. if (object instanceof Vector) { Vector comparisonVector = new Vector(((Vector) object).size() + 2); for (Enumeration valuesToIterate = ((Vector) object).elements(); valuesToIterate.hasMoreElements(); ) { Object vectorObject = valuesToIterate.nextElement(); if (vectorObject == null) { comparisonVector.addElement(vectorObject); } else { Object valueOrValues = valuesFromCollection( vectorObject, session, valueHolderPolicy, isObjectUnregistered); // If a collection of values were extracted union them. if (valueOrValues instanceof Vector) { for (Enumeration nestedValuesToIterate = ((Vector) valueOrValues).elements(); nestedValuesToIterate.hasMoreElements(); ) { comparisonVector.addElement(nestedValuesToIterate.nextElement()); } } else { comparisonVector.addElement(valueOrValues); } } } return comparisonVector; } } return valuesFromCollection(object, session, valueHolderPolicy, isObjectUnregistered); }
private void headers(HttpServletRequest req, PrintWriter out) { out.println("headers"); final Enumeration<String> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); out.print(name + ": "); final Enumeration<String> headers = req.getHeaders(name); while (headers.hasMoreElements()) { out.print("'" + headers.nextElement() + "', "); } out.println(); } out.println(); }
private Map<String, Object> headers(HttpServletRequest req) { final Map<String, Object> map = new HashMap<>(); final Enumeration<String> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final List<String> values = new ArrayList<>(); final Enumeration<String> headers = req.getHeaders(name); while (headers.hasMoreElements()) { values.add(headers.nextElement()); } map.put(name, values); } return map; }
/** * 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; }
/** * find a option by its type in a scheme. This involves iterating through the list of options. The * main reason for doing it this way is to avoid being dependent on the order in which the options * are coded in the xml, which is not explicitly constrained. */ private Option findOption(Level level, String optionKey) { Option option = null; for (Enumeration e = level.enumerateOption(); e.hasMoreElements(); ) { Option opt = (Option) e.nextElement(); if (opt.getOptionKey().equals(optionKey)) { option = opt; break; } } if (option == null) throw new Error("Couldn't find option for " + optionKey + " in level " + level); return option; }
/** * Displays the tree, starting with the given root node. * * @param root the Node that is the root of the tree to be displayed * @param offset the String */ public static void displayTree(Node root, String offset) { if (root.children.size() == 0) { DecisionTree.appendText("\n" + offset + " THEN (" + root.label + ") (Leaf node)"); return; } else { Enumeration enum1 = root.children.elements(); Enumeration enum2 = root.linkLabels.elements(); DecisionTree.appendText("\n" + offset + " " + root.label + " (Interior node)"); while (enum1.hasMoreElements()) { DecisionTree.appendText("\n" + offset + " IF (" + (String) enum2.nextElement() + ")"); displayTree((Node) enum1.nextElement(), offset + " "); } } }
public static String headersToString(HttpServletRequest request) { final StringBuffer sb = new StringBuffer(); for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) { final String name = (String) e.nextElement(); sb.append(name); sb.append("="); for (Enumeration f = request.getHeaders(name); f.hasMoreElements(); ) { final String value = (String) f.nextElement(); sb.append(value); if (f.hasMoreElements()) sb.append(","); } if (e.hasMoreElements()) sb.append("|"); } return sb.toString(); }
protected void unpackComponents() throws IOException, FileNotFoundException { File applicationPackage = new File(getApplication().getPackageResourcePath()); File componentsDir = new File(sGREDir, "components"); if (componentsDir.lastModified() == applicationPackage.lastModified()) return; componentsDir.mkdir(); componentsDir.setLastModified(applicationPackage.lastModified()); GeckoAppShell.killAnyZombies(); ZipFile zip = new ZipFile(applicationPackage); byte[] buf = new byte[32768]; try { if (unpackFile(zip, buf, null, "removed-files")) removeFiles(); } catch (Exception ex) { // This file may not be there, so just log any errors and move on Log.w(LOG_FILE_NAME, "error removing files", ex); } // copy any .xpi file into an extensions/ directory Enumeration<? extends ZipEntry> zipEntries = zip.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); if (entry.getName().startsWith("extensions/") && entry.getName().endsWith(".xpi")) { Log.i("GeckoAppJava", "installing extension : " + entry.getName()); unpackFile(zip, buf, entry, entry.getName()); } } }
/** * Looks up providers, and returns the property (and its associated provider) mapping the key, if * any. The order in which the providers are looked up is the provider-preference order, as * specificed in the security properties file. */ private static ProviderProperty getProviderProperty(String key) { ProviderProperty entry = null; List providers = Providers.getProviderList().providers(); for (int i = 0; i < providers.size(); i++) { String matchKey = null; Provider prov = (Provider) providers.get(i); String prop = prov.getProperty(key); if (prop == null) { // Is there a match if we do a case-insensitive property name // comparison? Let's try ... for (Enumeration e = prov.keys(); e.hasMoreElements() && prop == null; ) { matchKey = (String) e.nextElement(); if (key.equalsIgnoreCase(matchKey)) { prop = prov.getProperty(matchKey); break; } } } if (prop != null) { ProviderProperty newEntry = new ProviderProperty(); newEntry.className = prop; newEntry.provider = prov; return newEntry; } } return entry; }
protected void finished() { logger.log(LogService.LOG_DEBUG, "Here is OcdHandler():finished()"); // $NON-NLS-1$ if (!_isParsedDataValid) return; if (_ad_vector.size() == 0) { // Schema defines at least one AD is required. _isParsedDataValid = false; logger.log( LogService.LOG_ERROR, NLS.bind( MetaTypeMsg.MISSING_ELEMENT, new Object[] { AD, OCD, elementId, _dp_url, _dp_bundle.getBundleId(), _dp_bundle.getSymbolicName() })); return; } // OCD gets all parsed ADs. Enumeration<AttributeDefinitionImpl> adKey = _ad_vector.elements(); while (adKey.hasMoreElements()) { AttributeDefinitionImpl ad = adKey.nextElement(); _ocd.addAttributeDefinition(ad, ad._isRequired); } _ocd.setIcons(icons); _parent_OCDs_hashtable.put(_refID, _ocd); }
/** @see java.lang.ClassLoader#findResources(java.lang.String) */ @Override public Enumeration<URL> findResources(String resourceName) throws IOException { String webInfResourceName = "WEB-INF/classes/" + resourceName; List<URL> urlList = new ArrayList<URL>(); int jarFileListSize = jarFileList.size(); for (int i = 0; i < jarFileListSize; i++) { JarFile jarFile = jarFileList.get(i); JarEntry jarEntry = jarFile.getJarEntry(resourceName); // to better support war format, look for the resourceName in the WEB-INF/classes directory if (loadWebInf && jarEntry == null) jarEntry = jarFile.getJarEntry(webInfResourceName); if (jarEntry != null) { try { String jarFileName = jarFile.getName(); if (jarFileName.contains("\\")) jarFileName = jarFileName.replace('\\', '/'); urlList.add(new URL("jar:file:" + jarFileName + "!/" + jarEntry)); } catch (MalformedURLException e) { System.out.println( "Error making URL for [" + resourceName + "] in jar [" + jarFile + "] in war file [" + outerFile + "]: " + e.toString()); } } } // add all resources found in parent loader too Enumeration<URL> superResources = super.findResources(resourceName); while (superResources.hasMoreElements()) urlList.add(superResources.nextElement()); return Collections.enumeration(urlList); }
public MoquiStart(ClassLoader parent, boolean loadWebInf) { super(parent); this.loadWebInf = loadWebInf; URL wrapperWarUrl = null; try { // get outer file (the war file) pd = getClass().getProtectionDomain(); CodeSource cs = pd.getCodeSource(); wrapperWarUrl = cs.getLocation(); outerFile = new JarFile(new File(wrapperWarUrl.toURI())); // allow for classes in the outerFile as well jarFileList.add(outerFile); Enumeration<JarEntry> jarEntries = outerFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry je = jarEntries.nextElement(); if (je.isDirectory()) continue; // if we aren't loading the WEB-INF files and it is one, skip it if (!loadWebInf && je.getName().startsWith("WEB-INF")) continue; // get jars, can be anywhere in the file String jeName = je.getName().toLowerCase(); if (jeName.lastIndexOf(".jar") == jeName.length() - 4) { File file = createTempFile(je); jarFileList.add(new JarFile(file)); } } } catch (Exception e) { System.out.println("Error loading jars in war file [" + wrapperWarUrl + "]: " + e.toString()); } }
/** * Returns a Set of Strings containing the names of all available algorithms or types for the * specified Java cryptographic service (e.g., Signature, MessageDigest, Cipher, Mac, KeyStore). * Returns an empty Set if there is no provider that supports the specified service or if * serviceName is null. For a complete list of Java cryptographic services, please see the <a * href="../../../guide/security/CryptoSpec.html">Java Cryptography Architecture API Specification * & Reference</a>. Note: the returned set is immutable. * * @param serviceName the name of the Java cryptographic service (e.g., Signature, MessageDigest, * Cipher, Mac, KeyStore). Note: this parameter is case-insensitive. * @return a Set of Strings containing the names of all available algorithms or types for the * specified Java cryptographic service or an empty set if no provider supports the specified * service. * @since 1.4 */ public static Set<String> getAlgorithms(String serviceName) { if ((serviceName == null) || (serviceName.length() == 0) || (serviceName.endsWith("."))) { return Collections.EMPTY_SET; } HashSet result = new HashSet(); Provider[] providers = Security.getProviders(); for (int i = 0; i < providers.length; i++) { // Check the keys for each provider. for (Enumeration e = providers[i].keys(); e.hasMoreElements(); ) { String currentKey = ((String) e.nextElement()).toUpperCase(); if (currentKey.startsWith(serviceName.toUpperCase())) { // We should skip the currentKey if it contains a // whitespace. The reason is: such an entry in the // provider property contains attributes for the // implementation of an algorithm. We are only interested // in entries which lead to the implementation // classes. if (currentKey.indexOf(" ") < 0) { result.add(currentKey.substring(serviceName.length() + 1)); } } } } return Collections.unmodifiableSet(result); }
protected PermissionCollection getPermissions(CodeSource codeSource) { PermissionCollection perms; try { try { perms = super.getPermissions(codeSource); } catch (SecurityException e) { // We lied about our CodeSource and that makes URLClassLoader unhappy. perms = new Permissions(); } ProtectionDomain myDomain = AccessController.doPrivileged( new PrivilegedAction<ProtectionDomain>() { public ProtectionDomain run() { return getClass().getProtectionDomain(); } }); PermissionCollection myPerms = myDomain.getPermissions(); if (myPerms != null) { for (Enumeration<Permission> elements = myPerms.elements(); elements.hasMoreElements(); ) { perms.add(elements.nextElement()); } } } catch (Throwable e) { // We lied about our CodeSource and that makes URLClassLoader unhappy. perms = new Permissions(); } perms.setReadOnly(); return perms; }
public static Map<String, String> readProperties(InputStream inputStream) { Map<String, String> propertiesMap = null; try { propertiesMap = new LinkedHashMap<String, String>(); Properties properties = new Properties(); properties.load(inputStream); Enumeration<?> enumeration = properties.propertyNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); String value = (String) properties.get(key); propertiesMap.put(key, value); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return propertiesMap; }
/** * Processes a packet read from either the multicast or unicast socket. Needs to be synchronized * because mcast or unicast socket reads can be concurrent */ void handleIncomingUdpPacket(byte[] data) { ByteArrayInputStream inp_stream; ObjectInputStream inp; Message msg = null; List l; // used if bundling is enabled try { // skip the first n bytes (default: 4), this is the version info inp_stream = new ByteArrayInputStream(data, VERSION_LENGTH, data.length - VERSION_LENGTH); inp = new ObjectInputStream(inp_stream); if (enable_bundling) { l = new List(); l.readExternal(inp); for (Enumeration en = l.elements(); en.hasMoreElements(); ) { msg = (Message) en.nextElement(); try { handleMessage(msg); } catch (Throwable t) { Trace.error("UDP.handleIncomingUdpPacket()", "failure: " + t.toString()); } } } else { msg = new Message(); msg.readExternal(inp); handleMessage(msg); } } catch (Throwable e) { Trace.error("UDP.handleIncomingUdpPacket()", "exception=" + Trace.getStackTrace(e)); } }