List of usage examples for javax.naming NameClassPair getName
public String getName()
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Return an InputStream to an HTML representation of the contents * of this directory./* ww w. j a va 2 s. c om*/ * * @param contextPath Context path to which our internal paths are * relative * @param resourceInfo Description of the Parameter * @return Description of the Return Value */ protected InputStream renderHtml(String contextPath, ResourceInfo resourceInfo) { String name = resourceInfo.path; // Number of characters to trim from the beginnings of filenames int trim = name.length(); if (!name.endsWith("/")) { trim += 1; } if (name.equals("/")) { trim = 1; } // Prepare a writer to a buffered area ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter osWriter = null; try { osWriter = new OutputStreamWriter(stream, "UTF8"); } catch (Exception e) { // Should never happen osWriter = new OutputStreamWriter(stream); } PrintWriter writer = new PrintWriter(osWriter); StringBuffer sb = new StringBuffer(); // Render the page header sb.append("<html>\r\n"); sb.append("<head>\r\n"); sb.append("<title>"); sb.append(sm.getString("directory.title", name)); sb.append("</title>\r\n"); sb.append("<STYLE><!--"); sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS); sb.append("--></STYLE> "); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); sb.append(sm.getString("directory.title", name)); // Render the link to our parent (if required) String parentDirectory = name; if (parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { String parent = name.substring(0, slash); sb.append(" - <a href=\""); sb.append(rewriteUrl(contextPath)); if (parent.equals("")) { parent = "/"; } sb.append(rewriteUrl(parent)); if (!parent.endsWith("/")) { sb.append("/"); } sb.append("\">"); sb.append("<b>"); sb.append(sm.getString("directory.parent", parent)); sb.append("</b>"); sb.append("</a>"); } sb.append("</h1>"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<td align=\"left\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.filename")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"center\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.size")); sb.append("</strong></font></td>\r\n"); sb.append("<td align=\"right\"><font size=\"+1\"><strong>"); sb.append(sm.getString("directory.lastModified")); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); try { // Render the directory entries within this directory DirContext directory = resourceInfo.directory; NamingEnumeration enum1 = resourceInfo.resources.list(resourceInfo.path); boolean shade = false; while (enum1.hasMoreElements()) { NameClassPair ncPair = (NameClassPair) enum1.nextElement(); String resourceName = ncPair.getName(); ResourceInfo childResourceInfo = new ResourceInfo(resourceName, directory); String trimmed = resourceName; if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")) { continue; } sb.append("<tr"); if (shade) { sb.append(" bgcolor=\"#eeeeee\""); } sb.append(">\r\n"); shade = !shade; sb.append("<td align=\"left\"> \r\n"); sb.append("<a href=\""); sb.append(rewriteUrl(contextPath)); resourceName = rewriteUrl(name + resourceName); sb.append(resourceName); if (childResourceInfo.collection) { sb.append("/"); } sb.append("\"><tt>"); sb.append(trimmed); if (childResourceInfo.collection) { sb.append("/"); } sb.append("</tt></a></td>\r\n"); sb.append("<td align=\"right\"><tt>"); if (childResourceInfo.collection) { sb.append(" "); } else { sb.append(renderSize(childResourceInfo.length)); } sb.append("</tt></td>\r\n"); sb.append("<td align=\"right\"><tt>"); sb.append(childResourceInfo.httpDate); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } } catch (NamingException e) { // Something went wrong e.printStackTrace(); } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); String readme = getReadme(resourceInfo.directory); if (readme != null) { sb.append(readme); sb.append("<HR size=\"1\" noshade=\"noshade\">"); } sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); sb.append("</body>\r\n"); sb.append("</html>\r\n"); // Return an input stream to the underlying bytes writer.write(sb.toString()); writer.flush(); return (new ByteArrayInputStream(stream.toByteArray())); }
From source file:org.apache.catalina.startup.TldConfig.java
private void tldScanResourcePathsWebInf(DirContext resources, String rootPath, Set tldPaths) throws IOException { if (log.isTraceEnabled()) { log.trace(" Scanning TLDs in " + rootPath + " subdirectory"); }/*from w w w . j a v a 2s . co m*/ try { NamingEnumeration items = resources.list(rootPath); while (items.hasMoreElements()) { NameClassPair item = (NameClassPair) items.nextElement(); String resourcePath = rootPath + "/" + item.getName(); if (!resourcePath.endsWith(".tld") && (resourcePath.startsWith("/WEB-INF/classes") || resourcePath.startsWith("/WEB-INF/lib"))) { continue; } if (resourcePath.endsWith(".tld")) { if (log.isTraceEnabled()) { log.trace(" Adding path '" + resourcePath + "'"); } tldPaths.add(resourcePath); } else { tldScanResourcePathsWebInf(resources, resourcePath, tldPaths); } } } catch (NamingException e) { ; // Silent catch: it's valid that no /WEB-INF directory exists } }
From source file:org.efaps.db.store.VFSStoreResource.java
/** * Method called to initialize this StoreResource. * @param _instance Instance of the object this StoreResource is wanted * for/* w w w . j a v a 2s. c o m*/ * @param _store Store this resource belongs to * @throws EFapsException on error * @see Resource#initialize(Instance, Map, Compress) */ @Override public void initialize(final Instance _instance, final Store _store) throws EFapsException { super.initialize(_instance, _store); final StringBuilder fileNameTmp = new StringBuilder(); final String useTypeIdStr = getStore().getResourceProperties().get(VFSStoreResource.PROPERTY_USE_TYPE); if ("true".equalsIgnoreCase(useTypeIdStr)) { fileNameTmp.append(getInstance().getType().getId()).append("/"); } final String numberSubDirsStr = getStore().getResourceProperties() .get(VFSStoreResource.PROPERTY_NUMBER_SUBDIRS); if (numberSubDirsStr != null) { final long numberSubDirs = Long.parseLong(numberSubDirsStr); final String pathFormat = "%0" + Math.round(Math.log10(numberSubDirs) + 0.5d) + "d"; fileNameTmp.append(String.format(pathFormat, getInstance().getId() % numberSubDirs)).append("/"); } fileNameTmp.append(getInstance().getType().getId()).append(".").append(getInstance().getId()); this.storeFileName = fileNameTmp.toString(); final String numberBackupStr = getStore().getResourceProperties() .get(VFSStoreResource.PROPERTY_NUMBER_BACKUP); if (numberBackupStr != null) { this.numberBackup = Integer.parseInt(numberBackupStr); } if (this.manager == null) { try { DefaultFileSystemManager tmpMan = null; if (getStore().getResourceProperties().containsKey(Store.PROPERTY_JNDINAME)) { final InitialContext initialContext = new InitialContext(); final Context context = (Context) initialContext.lookup("java:comp/env"); final NamingEnumeration<NameClassPair> nameEnum = context.list(""); while (nameEnum.hasMoreElements()) { final NameClassPair namePair = nameEnum.next(); if (namePair.getName() .equals(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME))) { tmpMan = (DefaultFileSystemManager) context .lookup(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME)); break; } } } if (tmpMan == null && this.manager == null) { this.manager = evaluateFileSystemManager(); } } catch (final NamingException e) { throw new EFapsException(VFSStoreResource.class, "initialize.NamingException", e); } } }
From source file:org.jboss.web.tomcat.tc4.SingleSignOnContextConfig.java
/** * Accumulate and return a Set of resource paths to be analyzed for * tag library descriptors. Each element of the returned set will be * the context-relative path to either a tag library descriptor file, * or to a JAR file that may contain tag library descriptors in its * <code>META-INF</code> subdirectory. * * @exception IOException if an input/output error occurs while * accumulating the list of resource paths *//* w w w . ja v a 2 s.co m*/ private Set tldScanResourcePaths() throws IOException { if (debug >= 1) { log(" Accumulating TLD resource paths"); } Set resourcePaths = new HashSet(); // Accumulate resource paths explicitly listed in the web application // deployment descriptor if (debug >= 2) { log(" Scanning <taglib> elements in web.xml"); } String taglibs[] = context.findTaglibs(); for (int i = 0; i < taglibs.length; i++) { String resourcePath = context.findTaglib(taglibs[i]); // FIXME - Servlet 2.3 DTD implies that the location MUST be // a context-relative path starting with '/'? if (!resourcePath.startsWith("/")) { resourcePath = "/WEB-INF/" + resourcePath; } if (debug >= 3) { log(" Adding path '" + resourcePath + "' for URI '" + taglibs[i] + "'"); } resourcePaths.add(resourcePath); } // Scan TLDs in the /WEB-INF subdirectory of the web application if (debug >= 2) { log(" Scanning TLDs in /WEB-INF subdirectory"); } DirContext resources = context.getResources(); try { NamingEnumeration items = resources.list("/WEB-INF"); while (items.hasMoreElements()) { NameClassPair item = (NameClassPair) items.nextElement(); String resourcePath = "/WEB-INF/" + item.getName(); // FIXME - JSP 1.2 is not explicit about whether we should // scan subdirectories of /WEB-INF for TLDs also if (!resourcePath.endsWith(".tld")) { continue; } if (debug >= 3) { log(" Adding path '" + resourcePath + "'"); } resourcePaths.add(resourcePath); } } catch (NamingException e) { ; // Silent catch: it's valid that no /WEB-INF directory exists } // Scan JARs in the /WEB-INF/lib subdirectory of the web application if (debug >= 2) { log(" Scanning JARs in /WEB-INF/lib subdirectory"); } try { NamingEnumeration items = resources.list("/WEB-INF/lib"); while (items.hasMoreElements()) { NameClassPair item = (NameClassPair) items.nextElement(); String resourcePath = "/WEB-INF/lib/" + item.getName(); if (!resourcePath.endsWith(".jar")) { continue; } if (debug >= 3) { log(" Adding path '" + resourcePath + "'"); } resourcePaths.add(resourcePath); } } catch (NamingException e) { ; // Silent catch: it's valid that no /WEB-INF/lib directory exists } // Return the completed set return (resourcePaths); }
From source file:org.netoprise.neo4j.ConnectorTest.java
@Test @Ignore/*from w w w. j a v a 2 s . c o m*/ @OperateOnDeployment("test") public void listJNDI() { try { Context context = new InitialContext(); System.out.println("Context namespace: " + context.getNameInNamespace()); NamingEnumeration<NameClassPair> content = context.list("comp"); while (content.hasMoreElements()) { NameClassPair nameClassPair = (NameClassPair) content.nextElement(); System.out .println("Name :" + nameClassPair.getName() + " with type:" + nameClassPair.getClassName()); } } catch (NamingException e) { throw new RuntimeException(e); } }
From source file:org.nuxeo.runtime.datasource.DataSourceHelper.java
public static Map<String, DataSource> getDatasources() throws NamingException { String prefix = getDataSourceJNDIPrefix(); Context naming = new InitialContext(); Context jdbc = (Context) naming.lookup(prefix); Enumeration<NameClassPair> namesPair = jdbc.list(""); Map<String, DataSource> datasourcesByName = new HashMap<String, DataSource>(); while (namesPair.hasMoreElements()) { NameClassPair pair = namesPair.nextElement(); String name = pair.getName(); if (pair.isRelative()) { name = prefix + "/" + name; }/*from w w w.j a v a 2s . c o m*/ Object ds = naming.lookup(name); if (ds instanceof DataSource) { datasourcesByName.put(name, (DataSource) ds); } } return datasourcesByName; }
From source file:org.pepstock.jem.jppf.ExecuteManager.java
/** * Create a JPPF job that can be submitted for execution. * //from w ww . jav a 2s. co m * @param runnable Class name of Runnable or JPPFTask to execute * @param parallelTaskNumber Number of parallel task to submit * @param xmlContext InitialContext, serialized in XML string * @return an instance of the {@link org.jppf.client.JPPFJob JPPFJob} class. * @throws NamingException * @throws IOException * @throws JPPFException * @throws JPFFException * if an error occurs while creating the job or adding tasks. */ private static JPPFJob createJob(String xmlContext) throws JPPFMessageException, NamingException, IOException, JPPFException { XStream xstream = new XStream(); // reads all properties String jobName = JPPFConfiguration.getProperties().getProperty(Keys.JEM_JOB_NAME); String taskName = JPPFConfiguration.getProperties().getProperty(Keys.JEM_TASK_NAME); String runnable = JPPFConfiguration.getProperties().getProperty(Keys.JEM_RUNNABLE); int parallelTaskNumber = JPPFConfiguration.getProperties().getInt(Keys.JEM_TASK_NUMBER); // creates a data provider to pass initial context and number of parallel task MemoryMapDataProvider provider = new MemoryMapDataProvider(); provider.setValue(Keys.JEM_CONTEXT, xmlContext); provider.setValue(Keys.JEM_TASK_NUMBER, String.valueOf(parallelTaskNumber)); // checks if CHUNK is set if (JPPFConfiguration.getProperties().containsKey(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION)) { // gets data description String dataDescription = JPPFConfiguration.getProperties() .getProperty(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION); File file = null; InitialContext ic = ContextUtils.getContext(); // lookup for JNDI reference // needs file name because chunk is based on RandomFileAccess // that wants a FILE and not inputstream // so gets data description implementation object // to get REAL FILE NamingEnumeration<NameClassPair> list = ic.list(dataDescription); while (list.hasMore()) { NameClassPair pair = list.next(); // checks if is datastream // only datastreams are searched if (pair.getName().equalsIgnoreCase(dataDescription) && pair instanceof DataStreamNameClassPair) { DataStreamNameClassPair dsPair = (DataStreamNameClassPair) pair; DataStreamReference prevReference = (DataStreamReference) dsPair.getObject(); // gets data description XML definition StringRefAddr sra = (StringRefAddr) prevReference.get(StringRefAddrKeys.DATASTREAMS_KEY); // creates datadescription implementatio to get file DataDescriptionImpl ddImpl = (DataDescriptionImpl) xstream.fromXML(sra.getContent().toString()); file = ddImpl.getDatasets().iterator().next().getRealFile(); // leaves while break; } } // if file is null // data description is not found if (file == null) { throw new JPPFMessageException(JPPFMessage.JEMJ019E, dataDescription); } // calculated buffersize long bufferSize = file.length() / parallelTaskNumber; // using delimiter, creates chunk list List<ChunkDefinition> chunks = null; String delimiter = JPPFConfiguration.getProperties().getProperty(Keys.JEM_DELIMITER); String delimiterString = JPPFConfiguration.getProperties().getProperty(Keys.JEM_DELIMITER_STRING); if (delimiter != null) { // delimiter default LF char splitter = CharUtils.LF; // if delimiter is defined in BYTE mode // calculate char if (delimiter.toLowerCase().startsWith("0x")) { delimiter = StringUtils.substringAfter(delimiter.toLowerCase(), "0x"); splitter = (char) Integer.parseInt(delimiter, 16); } else { // if uses a escape java char splitter = StringEscapeUtils.unescapeJava(delimiter).charAt(0); } String displayDelimiter = Integer.toHexString((byte) splitter) + "(" + splitter + ")"; LogAppl.getInstance().emit(JPPFMessage.JEMJ020I, displayDelimiter); // calculates chunks chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize, splitter); provider.setValue(Keys.JEM_DELIMITER, splitter); } else if (delimiterString != null) { LogAppl.getInstance().emit(JPPFMessage.JEMJ020I, delimiterString); // calculates chunks chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize, delimiterString); provider.setValue(Keys.JEM_DELIMITER, delimiterString); } else { // if delimiter and delimiterString are missing, uses default delimiter (System.getProperty("line.separator") chunks = ChunksFactory.getChunksByDelimiter(file, bufferSize); } // changes parallel task // because chunk calculation tries to maintain the same // number of task but usually there are less after // chunk list creation parallelTaskNumber = chunks.size(); LogAppl.getInstance().emit(JPPFMessage.JEMJ021I, chunks); // serializes and saves on data provider all necessary data provider.setValue(Keys.JEM_TASK_NUMBER, String.valueOf(parallelTaskNumber)); provider.setValue(Keys.JEM_CHUNKABLE_DATA_DESCRIPTION, dataDescription); provider.setValue(Keys.JEM_CHUNKS, xstream.toXML(chunks)); } LogAppl.getInstance().emit(JPPFMessage.JEMJ023I, parallelTaskNumber); // checks if merged data decritpion is an argument if (JPPFConfiguration.getProperties().containsKey(Keys.JEM_MERGED_DATA_DESCRIPTION)) { // loads a list with all temporary files for tasks // to use to write partial output for (int i = 0; i < parallelTaskNumber; i++) { File temp = File.createTempFile("task[" + i + "]-merge", ".jemjppf"); temp.deleteOnExit(); TEMPORARY_FILES.add(temp); LogAppl.getInstance().emit(JPPFMessage.JEMJ022I, temp.getAbsolutePath(), i); } // sets data provider provider.setValue(Keys.JEM_MERGED_DATA_DESCRIPTION, JPPFConfiguration.getProperties().getProperty(Keys.JEM_MERGED_DATA_DESCRIPTION)); provider.setValue(Keys.JEM_TEMPORARY_FILES, xstream.toXML(TEMPORARY_FILES)); } // create a JPPF job JPPFJob job = new JPPFJob(provider); // give this job a readable unique id that we can use to monitor and // manage it. job.setName(jobName + "." + taskName); // Checks what instance has been past to distribute on grid try { Object clazz = Class.forName(runnable).newInstance(); if (clazz instanceof JPPFTask) { for (int i = 0; i < parallelTaskNumber; i++) { JPPFTask t = new WrapperJPPFTask((JPPFTask) clazz); // add a task to the job. job.addTask(t); } } else if (clazz instanceof Runnable) { for (int i = 0; i < parallelTaskNumber; i++) { JPPFTask t = new RunnableTask((Runnable) clazz); // add a task to the job. job.addTask(t); } } else { throw new JPPFMessageException(JPPFMessage.JEMJ002E, runnable, Runnable.class.getName(), JPPFTask.class.getName()); } } catch (InstantiationException e) { throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(), JPPFTask.class.getName()); } catch (IllegalAccessException e) { throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(), JPPFTask.class.getName()); } catch (ClassNotFoundException e) { throw new JPPFMessageException(JPPFMessage.JEMJ002E, e, runnable, Runnable.class.getName(), JPPFTask.class.getName()); } // there is no guarantee on the order of execution of the tasks, // however the results are guaranteed to be returned in the same order // as the tasks. return job; }
From source file:org.saiku.reporting.backend.server.SaikuJndiDatasourceConnectionProvider.java
public void showJndiContext(Context ctx, String name, String space) { if (null == name) name = ""; if (null == space) space = ""; try {//w ww. j av a2s . c o m NamingEnumeration<NameClassPair> en = ctx.list(name); while (en != null && en.hasMoreElements()) { String delim = (name.length() > 0) ? "/" : ""; NameClassPair ncp = en.next(); log.debug(space + name + delim + ncp); if (space.length() < 40) showJndiContext(ctx, ncp.getName(), " " + space); } } catch (javax.naming.NamingException ex) { // Normalerweise zu ignorieren } }
From source file:org.viafirma.cliente.util.ConfigUtil.java
/** * Recupera el conjunto de propiedades que utiliza la aplicacin. * @param context// w ww . j a v a 2 s . c om * @return */ public Properties readConfigPropertes() { Properties properties = new Properties(); Context initCtx; try { // carcamos la configuracin por defecto properties.load(getClass().getResourceAsStream("/viafirmaConfig.properties")); // recuperamos la configuracin almacenada en el contexto de aplicacin initCtx = new InitialContext(); Context contextInit = (Context) initCtx.lookup("java:comp/env"); // recuperamos ahora todos los parametros JNDI que estan en el raiz de la aplicacin NamingEnumeration<NameClassPair> propiedadesJDNI = contextInit.list(""); while (propiedadesJDNI.hasMoreElements()) { NameClassPair propiedad = propiedadesJDNI.nextElement(); Object temp = contextInit.lookup(propiedad.getName()); if (temp instanceof String) { if (propiedad.getName().startsWith("SYSTEM_")) { String valor = (String) temp; String nombre = StringUtils.substringAfter(propiedad.getName(), "SYSTEM_"); System.getProperties().put(nombre, valor); properties.put(nombre, valor); } else { String valor = (String) temp; properties.put(propiedad.getName(), valor); } } } for (Object key : properties.keySet()) { if (((String) key).contains("PASSWORD")) { System.out.println("\t\t\t" + key + "=***"); } else { System.out.println("\t\t\t" + key + "=" + properties.get(key)); } } } catch (Exception e) { log.error("No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible. " + e.getMessage()); //Permitimos el arranque de la aplicacin utilizando la configuracin de los properties. //throw new ExceptionInInitializerError("No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible."+e.getMessage()); } return properties; }
From source file:org.viafirma.util.ConfigUtil.java
/** * Recupera el conjunto de propiedades que utiliza la aplicacin. * @param context/* w ww. ja va 2s . c om*/ * @return */ public String readConfigProperty(String property) { Context initCtx; try { initCtx = new InitialContext(); Context contextInit = (Context) initCtx.lookup("java:comp/env"); // recuperamos ahora todos los parametros JNDI que estan en el raiz de la aplicacin NamingEnumeration<NameClassPair> propiedadesJDNI = contextInit.list(""); while (propiedadesJDNI.hasMoreElements()) { NameClassPair propiedad = propiedadesJDNI.nextElement(); if (property.equalsIgnoreCase(propiedad.getName())) { // propiedad encontrada Object temp = contextInit.lookup(propiedad.getName()); if (temp instanceof String) { String valor = (String) temp; return valor; } } } } catch (Exception e) { throw new ExceptionInInitializerError( "No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible." + e.getMessage()); } log.fatal("No se pueden recuperar el parametro de configuracin " + property + " de configuracin. JNDI parece no estar disponible."); return null; }