List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:net.ontopia.topicmaps.webed.impl.utils.TagUtils.java
public static ActionRegistryIF getActionRegistry(ServletRequest request) throws JspTagException { ServletContext servletContext = ((HttpServletRequest) request).getSession().getServletContext(); ActionRegistryIF registry = (ActionRegistryIF) servletContext.getAttribute(Constants.AA_REGISTRY); if (registry != null) return registry; // Read in Action Configuration and set it to application context String cfgpath = servletContext.getInitParameter(Constants.SCTXT_CONFIG_PATH); if (cfgpath == null) cfgpath = "classpath:actions.xml"; log.debug("Start reading action configuration from " + cfgpath); String str_delay = servletContext.getInitParameter(Constants.SCTXT_RELOAD_DELAY); long delay = 6000; // every 6 seconds by default if (str_delay != null) { try {//from www . jav a2 s . co m delay = Long.parseLong(str_delay) * 1000; // value in milliseconds } catch (NumberFormatException e) { delay = -1; log.warn("Warning: Falling back to no config re-reading, " + e); } } String ctxtPath = ((HttpServletRequest) request).getContextPath(); String realpath = servletContext.getRealPath(""); ActionConfigurator aconf = new ActionConfigurator(ctxtPath, realpath, cfgpath, delay); ActionConfigRegistrator registrator = new ActionConfigRegistrator(servletContext); //!aconf.addObserver(registrator); //!aconf.readAndWatchRegistry(); // HACK to make loading config files from classpath work aconf.readRegistryConfiguration(); registry = aconf.getRegistry(); registrator.configurationChanged(registry); log.debug("Setup action configuration for the web editor and assigned it to application context."); return registry; }
From source file:org.wso2.carbon.apimgt.everywhere.webapp.publisher.APIPublisherLifecycleListener.java
private List<URL> convertToFileUrl(URL[] libPath, URL classPath, ServletContext context) { if ((libPath != null || libPath.length == 0) && classPath == null) { return null; }/*from www .jav a2 s . c o m*/ List<URL> list = new ArrayList<URL>(); if (classPath != null) { list.add(classPath); } if (libPath.length != 0) { final String libBasePath = context.getRealPath("/WEB-INF/lib"); for (URL lib : libPath) { String path = lib.getPath(); if (path != null) { String fileName = path.substring(path.lastIndexOf(File.separator)); try { list.add(new URL("jar:file://" + libBasePath + File.separator + fileName + "!/")); } catch (MalformedURLException e) { e.printStackTrace(); } } } } return list; }
From source file:com.haulmont.cuba.web.controllers.StaticContentController.java
protected LookupResult lookupNoCache(HttpServletRequest req) { final String path = getPath(req); if (isForbidden(path)) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); ServletContext context = req.getSession().getServletContext(); final URL url; try {//from w ww .j ava2s.c o m url = context.getResource(path); } catch (MalformedURLException e) { return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path"); } if (url == null) return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found"); final String mimeType = getMimeType(path); final String realpath = context.getRealPath(path); if (realpath != null) { // Try as an ordinary file File f = new File(realpath); if (!f.isFile()) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); else { return createLookupResult(req, f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url); } } else { try { // Try as a JAR Entry final ZipEntry ze = ((JarURLConnection) url.openConnection()).getJarEntry(); if (ze != null) { if (ze.isDirectory()) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); else return createLookupResult(req, ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req), url); } else // Unexpected? return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), url); } catch (ClassCastException e) { // Unknown resource type return createLookupResult(req, -1, mimeType, -1, acceptsDeflate(req), url); } catch (IOException e) { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } } }
From source file:com.mycompany.CRMFly.ManagedBeans.EmployeeBean.java
public void handleFileUpload(FileUploadEvent event) { // UploadedFile file = event.getFile(); setUploaded_image(event.getFile());//from w w w . j av a2s. c o m ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String v_file_ext = getUploaded_image().getFileName() .split("\\.")[(getUploaded_image().getFileName().split("\\.").length) - 1]; setUpload_location(servletContext.getRealPath("") + File.separator + "temp-images" + File.separator + "3" + "." + v_file_ext); FileImageOutputStream imageOutput; try { imageOutput = new FileImageOutputStream(new File(getUpload_location())); imageOutput.write(getUploaded_image().getContents(), 0, getUploaded_image().getContents().length); imageOutput.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } byte[] file = new byte[uploaded_image.getContents().length]; System.arraycopy(uploaded_image.getContents(), 0, file, 0, uploaded_image.getContents().length); employee.setPhoto(file); FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, msg); }
From source file:com.googlecode.jsfFlex.component.ext.AbstractFlexUIApplication.java
@Override public void encodeBegin(FacesContext context) throws IOException { ExternalContext extContext = context.getExternalContext(); ServletContext servContext = ServletContext.class.cast(extContext.getContext()); setApplicationPath(servContext.getRealPath("")); Map<String, String> xmlnsMap = getXmlnsMap(); xmlnsMap.put(MX_XMLNS, MX_DEFAULT_XMLNS_URL); xmlnsMap.put(S_XMLNS, S_DEFAULT_XMLNS_URL); xmlnsMap.put(FX_XMLNS, FX_DEFAULT_XMLNS_URL); if (getProvidedAdditionalXmlnsMap() != null) { Map<String, String> providedAdditionalXmlnsMap = getProvidedAdditionalXmlnsMap(); for (String currXmlnsKey : providedAdditionalXmlnsMap.keySet()) { String currXmlnsUrl = providedAdditionalXmlnsMap.get(currXmlnsKey); currXmlnsKey = currXmlnsKey.indexOf(':') > -1 ? currXmlnsKey : XMLNS_PREFIX + currXmlnsKey; xmlnsMap.put(currXmlnsKey, currXmlnsUrl); }/*from w w w. ja v a 2 s . c o m*/ } String mode = extContext.getInitParameter(FlexConstants.CONFIG_MODE_NAME); AbstractFlexContext flexContext = new FlexContextImpl(getMxmlPackageName(), mode, this); String webContextPath = extContext.getRequestContextPath(); String swfWebPath = webContextPath + "/" + FlexConstants.SWF_DIRECTORY_NAME + "/"; String applicationSwfWebPath = swfWebPath + getMxmlPackageName() + "/"; flexContext.setSwfWebPath(swfWebPath); flexContext.setApplicationSwfWebPath(applicationSwfWebPath); flexContext.setWebContextPath(webContextPath); //setting or appending scripts to execute upon application initialization String init = String.class.cast(getAttributes().get(INITIALIZE_ATTR)); init = (init == null) ? INITIALIZE_CALL : init + " " + INITIALIZE_CALL; getAttributes().put(INITIALIZE_ATTR, init); String localeWebContextRelativePath = extContext .getInitParameter(FlexConstants.LOCALE_WEB_CONTEXT_RELATIVE_PATH); if (localeWebContextRelativePath != null) { flexContext.setLocaleWebContextPath( _applicationPath + File.separatorChar + localeWebContextRelativePath + File.separatorChar); } String flexJavaSDKPath = extContext.getInitParameter(FlexConstants.FLEX_JAVA_SDK_PATH); if (flexJavaSDKPath != null) { flexContext.setFlexJavaSDKPath(flexJavaSDKPath); } String projectWorkspaceWebFlashDirectory = extContext .getInitParameter(FlexConstants.PROJECT_WORKSPACE_WEB_FLASH_DIRECTORY); if (projectWorkspaceWebFlashDirectory != null) { flexContext.setProjectWorkspaceWebFlashDirectory(projectWorkspaceWebFlashDirectory); } //to reflect the correct state when debugging if (flexContext.isProductionEnv()) { //do not need to create preMXML, MXML, and SWF files } else { String mxmlPath = _applicationPath + File.separatorChar + FlexConstants.MXML_DIRECTORY_NAME + File.separatorChar + getMxmlPackageName() + File.separatorChar; String swfPath = _applicationPath + File.separatorChar + FlexConstants.SWF_DIRECTORY_NAME + File.separatorChar; String applicationSwfPath = swfPath + getMxmlPackageName() + File.separatorChar + getMxmlPackageName() + FlexConstants.SWF_FILE_EXT; /* * The above swfBasePath will hold placeholder of where swf-source-files's source-file[s] will be echoed to. * The files that will be echoed can be found in flexConstants.xml and are simply the contents that will be used * by the system's ActionScripts. */ String flexSDKPath = _applicationPath + File.separatorChar + FlexConstants.FLEX_SDK_DIRECTORY_NAME + File.separatorChar; String webXmlFlexSDKPath = extContext.getInitParameter(FlexConstants.PROVIDED_FLEX_SDK_PATH); String swcPath = _applicationPath + File.separatorChar + FlexConstants.SWC_DIRECTORY_NAME + File.separatorChar; String jsfFlexSwcPath = swcPath + FlexConstants.JSF_FLEX_MAIN_SWC_DIRECTORY_NAME + File.separatorChar; //externalLibraryPath will contain .swc file String swcFileAbsolutePath = jsfFlexSwcPath + FlexConstants.JSF_FLEX_MAIN_SWC_ARCHIVE_NAME + FlexConstants.SWC_FILE_EXT; addExternalLibraryPath(swcFileAbsolutePath); //runtimeSharedLibrary has to be relative to the Web root path file String jsfFlexMainSwcWebpath = swfWebPath + FlexConstants.JSF_FLEX_MAIN_SWC_ARCHIVE_NAME + FlexConstants.SWF_FILE_EXT; addRuntimeSharedLibrary(jsfFlexMainSwcWebpath); if (getFlexSDKPath() != null && getFlexSDKPath().trim().length() > 0) { flexContext.setFlexSDKPath(getFlexSDKPath()); } else if (webXmlFlexSDKPath != null) { flexContext.setFlexSDKPath(webXmlFlexSDKPath); } else { flexContext.setFlexSDKPath(flexSDKPath); } flexContext.setMxmlPath(mxmlPath); flexContext.setApplicationSwfPath(applicationSwfPath); flexContext.setSwfPath(swfPath); flexContext.setJsfFlexSwcPath(jsfFlexSwcPath); flexContext.setSwcPath(swcPath); //set the attributes for jsfFlexFlashApplicationConfiguration JsfFlexFlashApplicationConfiguration jsfFlexFlashApplicationConfiguration = flexContext .getJsfFlexFlashApplicationConfiguration(); String flashToJavaScriptLogLevel = extContext .getInitParameter(FlexConstants.FLASH_TO_JAVASCRIPT_LOG_LEVEL_NAME); if (flashToJavaScriptLogLevel == null) { flashToJavaScriptLogLevel = extContext.getInitParameter(FlexConstants.CONFIG_MODE_NAME); if (flashToJavaScriptLogLevel.equals(FlexConstants.PRODUCTION_MODE)) { flashToJavaScriptLogLevel = FlexConstants.FLASH_TO_JAVASCRIPT_LOG_WARN_LEVEL; } else { flashToJavaScriptLogLevel = FlexConstants.FLASH_TO_JAVASCRIPT_LOG_LOG_LEVEL; } } if (flashToJavaScriptLogLevel.equals(FlexConstants.FLASH_TO_JAVASCRIPT_LOG_LOG_LEVEL)) { jsfFlexFlashApplicationConfiguration.setFlashToJavaScriptLogMode("1"); } else if (flashToJavaScriptLogLevel.equals(FlexConstants.FLASH_TO_JAVASCRIPT_LOG_DEBUG_LEVEL)) { jsfFlexFlashApplicationConfiguration.setFlashToJavaScriptLogMode("2"); } else if (flashToJavaScriptLogLevel.equals(FlexConstants.FLASH_TO_JAVASCRIPT_LOG_INFO_LEVEL)) { jsfFlexFlashApplicationConfiguration.setFlashToJavaScriptLogMode("3"); } else if (flashToJavaScriptLogLevel.equals(FlexConstants.FLASH_TO_JAVASCRIPT_LOG_WARN_LEVEL)) { jsfFlexFlashApplicationConfiguration.setFlashToJavaScriptLogMode("4"); } else { jsfFlexFlashApplicationConfiguration.setFlashToJavaScriptLogMode("5"); } String preMxmlPath = _applicationPath + File.separatorChar + FlexConstants.PREMXML_DIRECTORY_NAME + File.separatorChar + getMxmlPackageName() + File.separatorChar; flexContext.setPreMxmlPath(preMxmlPath); //Does this even need to be present within the JSF-component or should it passed as default within the task? setAccessible(true); } super.encodeBegin(context); }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadControls(ServletContext servletContext) throws Exception { // assume no controls int controlCount = 0; // create a list for our controls List<JSONObject> jsonControls = new ArrayList<JSONObject>(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/controls/")); // create a filter for finding .control.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".control.xml"); }//from w w w .jav a2 s . c o m }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/control.xsd")); // create a validator Validator validator = schema.newValidator(); // loop the xml files in the folder for (File xmlFile : dir.listFiles(xmlFilenameFilter)) { // get a scanner to read the file Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A"); // read the xml into a string String xml = fileScanner.next(); // close the scanner (and file) fileScanner.close(); // validate the control xml file against the schema validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); // convert the string into JSON JSONObject jsonControlCollection = org.json.XML.toJSONObject(xml).getJSONObject("controls"); JSONObject jsonControl; int index = 0; int count = 0; if (jsonControlCollection.optJSONArray("control") == null) { jsonControl = jsonControlCollection.getJSONObject("control"); } else { jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index); count = jsonControlCollection.getJSONArray("control").length(); } do { // check this type does not already exist for (int i = 0; i < jsonControls.size(); i++) { if (jsonControl.getString("type").equals(jsonControls.get(i).getString("type"))) throw new Exception(" control type is loaded already. Type names must be unique"); } // add the jsonControl to our array jsonControls.add(jsonControl); // inc the control count controlCount++; // inc the count of controls in this file index++; // get the next one if (index < count) jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index); } while (index < count); } // sort the list of controls by name Collections.sort(jsonControls, new Comparator<JSONObject>() { @Override public int compare(JSONObject c1, JSONObject c2) { try { return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false); } catch (JSONException e) { return 0; } } }); // create a JSON Array object which will hold json for all of the available controls JSONArray jsonArrayControls = new JSONArray(jsonControls); // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet) servletContext.setAttribute("jsonControls", jsonArrayControls); _logger.info(controlCount + " controls loaded in .control.xml files"); return controlCount; }
From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java
public String getVHostName(ServletContext context) { String jbossWebXml = context.getRealPath("/WEB-INF/jboss-web.xml"); try {// w w w.j ava 2 s. c o m DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(jbossWebXml); XPathFactory xpFactory = XPathFactory.newInstance(); XPath xpath = xpFactory.newXPath(); XPathExpression expr = xpath.compile("/jboss-web/virtual-host/text()"); NodeList result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); if (result.getLength() > 0) { return result.item(0).getNodeValue(); } } catch (Exception e) { log.warn("Failed to read/parse file.", e); } return WarUtils.getWarName(context); }
From source file:com.ideo.jso.Group.java
/** * //from www .jav a 2 s .c o m * @param servletContext * @return the more recent modification date of the css file of this group, as a long * @throws MalformedURLException */ private long getMaxCSSTimestamp(ServletContext servletContext) throws MalformedURLException { long maxJSTimeStamp = cssBuffer.getTimestamp(); List files = getCssNames(); for (int i = 0; i < files.size(); i++) { String webPath = (String) files.get(i); String fileName = servletContext.getRealPath(webPath); long mx = getFileTimeStamp(fileName); if (mx > maxJSTimeStamp) maxJSTimeStamp = mx; } return maxJSTimeStamp; }
From source file:com.piusvelte.hydra.ConnectionManager.java
private ConnectionManager(ServletContext ctx) { ctx.log("Hydra ConnectionManager instantiated"); String[] fullPathParts;/* www . j av a 2 s . c o m*/ if (System.getProperty("os.name").startsWith("Windows")) { fullPathParts = ctx.getRealPath(File.separator).split("\\\\", -1); sHydraDir = fullPathParts[0] + File.separator + WIN_DIR; } else { fullPathParts = ctx.getRealPath(File.separator).split(File.separator, -1); sHydraDir = fullPathParts[0] + File.separator + NIX_DIR; } sHydraDir += File.separator + "hydra"; ctx.log("Working Directory: " + sHydraDir); if (fullPathParts.length > 2) { if (fullPathParts.length > 3) { sHydraDir += File.separator + fullPathParts[fullPathParts.length - 3]; } sHydraDir += File.separator + fullPathParts[fullPathParts.length - 2]; } mQueueRetryInterval = QueueThread.DEFAULT_QUEUERETRYINTERVAL; File hydraDir = new File(sHydraDir); if (hydraDir.exists()) { sHydraDir += File.separator; InputStream is = null; try { is = new FileInputStream(sHydraDir + HYDRA_PROPERTIES); } catch (FileNotFoundException e1) { ctx.log("The properties file at " + (sHydraDir + HYDRA_PROPERTIES) + " could not be found."); e1.printStackTrace(); } if (is != null) { Properties properties = new Properties(); try { properties.load(is); ctx.log("Hydra properties file read"); if (properties.containsKey(sPassphrase)) passphrase = properties.getProperty(sPassphrase); sQueueFile = sHydraDir + "queue"; tokenFile = sHydraDir + "tokens"; try { loadTokens(); } catch (Exception e) { e.printStackTrace(); } if (properties.containsKey(sQueueRetryInterval)) mQueueRetryInterval = Integer.parseInt(properties.getProperty(sQueueRetryInterval)); if (properties.containsKey(sDatabases)) { String[] databaseAliases = properties.getProperty(sDatabases).split(",", -1); String[] databaseProperties = new String[] { sType, sDatabase, sHost, sPort, sUsername, sPassword, sConnections, sDASU, sDASP, sSQLENVINIT }; for (String databaseAlias : databaseAliases) { HashMap<String, String> database = new HashMap<String, String>(); for (String databaseProperty : databaseProperties) { database.put(databaseProperty, properties.getProperty(databaseAlias + "." + databaseProperty, "")); } synchronized (databaseLock) { sDatabaseSettings.put(databaseAlias, database); sDatabaseConnections.put(databaseAlias, new ArrayList<DatabaseConnection>()); queuedDatabaseRequests.put(databaseAlias, 0); } } } } catch (IOException e) { e.printStackTrace(); } } else { initProps(); } } else if (hydraDir.mkdirs()) { sHydraDir += File.separator; initProps(); } else { ctx.log("properties doesn't exist, and creating it failed at: " + sHydraDir); } }
From source file:graphene.rest.ws.impl.ExportGraphRSImpl.java
@Override public Response exportGraphAsJSON(@QueryParam("fileName") final String fileName, @QueryParam("fileExt") final String fileExt, @QueryParam("username") final String username, @QueryParam("timeStamp") final String timeStamp, // this is the // client // timestamp in // millisecs as a string final String graphJSONdata) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(outputStream); // DEBUG/* ww w. j a v a 2 s . co m*/ logger.debug("exportGraphAsJSON: fileName = " + fileName + ", fileExt = " + fileExt + ", graphJSONdata length = " + graphJSONdata.length()); try { writer.write(graphJSONdata); } catch (final IOException e) { logger.error("exportGraphAsJSON: Exception writing JSON"); logger.error(e.getMessage()); } try { writer.close(); outputStream.flush(); outputStream.close(); } catch (final java.io.IOException ioe) { logger.error("exportGraphAsJSON: I/O Exception when attempting to close output. Details " + ioe.getMessage()); } // Create the file on the Web Server File file = null; ServletContext servletContext = null; try { servletContext = globals.getServletContext(); } catch (final Exception se) { logger.error("exportGraphAsJSON: ServletContext is null."); } String path = null; final String serverfileName = "GraphExport" + "_" + username + "_" + timeStamp + "_" + fileName + fileExt; if (servletContext != null) { path = servletContext.getRealPath("/"); } // TODO - get the path from the servlerContext or the request param // TODO the file should be placed under the webserver's dir if (path == null) { // TODO - handle case if the Server is Linux instead of Windows path = "C:/Windows/Temp"; // Temp hack } // DEBUG logger.debug("exportGraphAsJSON: file path = " + path); try { file = new File(path, serverfileName); // file.mkdirs(); final FileOutputStream fout = new FileOutputStream(file); fout.write(outputStream.toByteArray()); fout.close(); String finalPath = file.toURI().toString(); finalPath = finalPath.replace("file:/", ""); // remove leading // DEBUG // logger.debug("exportGraphAsJSON: file toURI = " + finalPath); final ResponseBuilder response = Response.ok(finalPath); response.type("text/plain"); final Response responseOut = response.build(); return responseOut; } catch (final Exception fe) { logger.error( "exportGraphAsJSON: Failed to create file for export. Details: " + fe.getLocalizedMessage()); } return null; }