Example usage for javax.servlet ServletContext getRealPath

List of usage examples for javax.servlet ServletContext getRealPath

Introduction

In this page you can find the example usage for javax.servlet ServletContext getRealPath.

Prototype

public String getRealPath(String path);

Source Link

Document

Gets the real path corresponding to the given virtual path.

Usage

From source file:org.jboss.web.tomcat.tc5.WebCtxLoader.java

/**
 * Set the appropriate context attribute for our class path.  This
 * is required only because Jasper depends on it.
 *//*ww  w .  ja v a2  s . com*/
private void setClassPath() {
    // Validate our current state information
    if (!(webContainer instanceof Context))
        return;
    ServletContext servletContext = ((Context) webContainer).getServletContext();
    if (servletContext == null)
        return;

    try {
        Method method = webContainer.getClass().getMethod("getCompilerClasspath", null);
        Object baseClasspath = method.invoke(webContainer, null);
        if (baseClasspath != null) {
            servletContext.setAttribute(Globals.CLASS_PATH_ATTR, baseClasspath.toString());
            return;
        }
    } catch (Exception e) {
        // Ignore
        e.printStackTrace();
    }

    StringBuffer classpath = new StringBuffer();

    // Assemble the class path information from our repositories
    for (int i = 0; i < repositories.size(); i++) {
        String repository = repositories.get(i).toString();
        if (repository.startsWith("file://"))
            repository = repository.substring(7);
        else if (repository.startsWith("file:"))
            repository = repository.substring(5);
        else if (repository.startsWith("jndi:"))
            repository = servletContext.getRealPath(repository.substring(5));
        else
            continue;
        if (repository == null)
            continue;
        if (i > 0)
            classpath.append(File.pathSeparator);
        classpath.append(repository);
    }

    // Store the assembled class path as a servlet context attribute
    servletContext.setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString());

}

From source file:pe.gob.mef.gescon.web.ui.UserMB.java

public void handleFileUpload(FileUploadEvent event) {
    try {/*from   w  ww.java2s .  c  o  m*/
        byte[] img = event.getFile().getContents();
        this.imagenTemporal = File.separator + "resources" + File.separator + "images" + File.separator
                + event.getFile().getFileName();
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();
        String archivo = scontext.getRealPath("") + this.imagenTemporal;
        this.imagenTemporal = this.imagenTemporal.replace("\\", "/");
        FileOutputStream fos = new FileOutputStream(archivo);
        fos.write(img);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
}

From source file:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *//*  w w w  .j a v  a2 s  .c om*/
@Test
public void testDoPostURLFail() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletConfig config = mock(ServletConfig.class);
    ServletContext context = mock(ServletContext.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
    ServletOutputStream stream = mock(ServletOutputStream.class);
    HttpSession session = mock(HttpSession.class);

    when(request.getSession(true)).thenReturn(session);

    ArrayList<Workflow> flowList = new ArrayList<>();
    Workflow flow = new Workflow();
    flow.setStringVersion("Esto es una prueba");
    flow.setWsdls("<wsdl>http://www.ua.es</wsdl>");
    flow.setUrls("http://falsa.es");

    ArrayList<WorkflowInput> flowInputs = new ArrayList<>();
    WorkflowInput input = new WorkflowInput("pru0Input");
    input.setDepth(1);
    flowInputs.add(input);

    input = new WorkflowInput("pru1Input");
    input.setDepth(0);
    flowInputs.add(input);

    flow.setInputs(flowInputs);

    flowList.add(flow);
    when(session.getAttribute("workflows")).thenReturn(flowList);

    when(config.getServletContext()).thenReturn(context);
    URL url = this.getClass().getResource("/config.properties");
    File testFile = new File(url.getFile());
    when(context.getRealPath("/")).thenReturn(testFile.getParent() + "/");

    Part[] parts = new Part[] { new StringPart("user", "user"), new StringPart("pass", "pass"),
            new StringPart("workflow0pru0Input", "prueba0"), new StringPart("workflow0pru0Input0", "prueba0.0"),
            new StringPart("workflow0pru1Input", "prueba1")

    };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    WorkflowRunner runer = new WorkflowRunner();
    try {
        runer.init(config);
        runer.doPost(request, response);

    } catch (ServletException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (IOException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (NullPointerException ex) {
        //ok no funciona el server de taverna
    }
}

From source file:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *///from ww  w  . j a va 2 s  .  c om
@Test
public void testDoPost() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletConfig config = mock(ServletConfig.class);
    ServletContext context = mock(ServletContext.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
    ServletOutputStream stream = mock(ServletOutputStream.class);
    HttpSession session = mock(HttpSession.class);

    when(request.getSession(true)).thenReturn(session);

    ArrayList<Workflow> flowList = new ArrayList<>();
    Workflow flow = new Workflow();
    flow.setStringVersion("Esto es una prueba");
    flow.setWsdls("<wsdl>http://www.ua.es</wsdl>");
    flow.setUrls("http://www.ua.es");

    ArrayList<WorkflowInput> flowInputs = new ArrayList<>();
    WorkflowInput input = new WorkflowInput("pru0Input");
    input.setDepth(1);
    flowInputs.add(input);

    input = new WorkflowInput("pru1Input");
    input.setDepth(0);
    flowInputs.add(input);

    flow.setInputs(flowInputs);

    flowList.add(flow);
    when(session.getAttribute("workflows")).thenReturn(flowList);

    when(config.getServletContext()).thenReturn(context);
    URL url = this.getClass().getResource("/config.properties");
    File testFile = new File(url.getFile());
    when(context.getRealPath("/")).thenReturn(testFile.getParent() + "/");

    Part[] parts = new Part[] { new StringPart("user", "user"), new StringPart("pass", "pass"),
            new StringPart("workflow0pru0Input", "prueba0"), new StringPart("workflow0pru0Input0", "prueba0.0"),
            new StringPart("workflow0pru1Input", "prueba1")

    };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    WorkflowRunner runer = new WorkflowRunner();
    try {
        runer.init(config);
        runer.doPost(request, response);

    } catch (ServletException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (IOException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (NullPointerException ex) {
        //ok no funciona el server de taverna
    }
}

From source file:io.milton.cloud.server.web.templating.HtmlTemplater.java

public HtmlTemplater(ApplicationManager applicationManager, Formatter formatter,
        SpliffySecurityManager securityManager, ServletContext servletContext) {
    this.servletContext = servletContext;
    this.securityManager = securityManager;
    templateLoader = new HtmlTemplateLoader();
    java.util.Properties p = new java.util.Properties();
    p.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
    engine = new VelocityEngine(p);
    engine.setProperty("resource.loader", "mine");
    engine.setProperty("mine.resource.loader.instance", new HtmlTemplateLoaderResourceLoader());
    engine.setProperty("userdirective", VelocityContentDirective.class.getName() + ","
            + PortletsDirective.class.getName() + "," + RenderAppSettingsDirective.class.getName());

    templateParser = new HtmlTemplateParser();
    templateRenderer = new HtmlTemplateRenderer(applicationManager, formatter);

    roots = new ArrayList<>();
    File fWebappRoot = new File(servletContext.getRealPath("/"));
    roots.add(fWebappRoot);//w w  w .  ja v  a2  s. co m
    log.info("Using webapp root dir: " + fWebappRoot.getAbsolutePath());

    String extraRoots = System.getProperty(ROOTS_SYS_PROP_NAME);
    if (extraRoots != null && !extraRoots.isEmpty()) {
        String[] arr = extraRoots.split(",");
        for (String s : arr) {
            File root = new File(s);
            if (!root.exists()) {
                throw new RuntimeException("Root template dir specified in system property does not exist: "
                        + root.getAbsolutePath() + " from property value: " + extraRoots);
            }
            roots.add(root);
            log.info("Using file template root: " + root.getAbsolutePath());
        }
    }
}

From source file:org.jboss.web.tomcat.service.WebCtxLoader.java

/**
 * Set the appropriate context attribute for our class path.  This
 * is required only because Jasper depends on it.
 */// www.  j ava  2s  . c o m
private void setClassPath() {
    // Validate our current state information
    if (!(webContainer instanceof Context))
        return;
    ServletContext servletContext = ((Context) webContainer).getServletContext();
    if (servletContext == null)
        return;

    try {
        Method method = webContainer.getClass().getMethod("getCompilerClasspath", (Class[]) null);
        Object baseClasspath = method.invoke(webContainer, (Object[]) null);
        if (baseClasspath != null) {
            servletContext.setAttribute(Globals.CLASS_PATH_ATTR, baseClasspath.toString());
            return;
        }
    } catch (Exception e) {
        // Ignore
        e.printStackTrace();
    }

    StringBuffer classpath = new StringBuffer();

    // Assemble the class path information from our repositories
    for (int i = 0; i < repositories.size(); i++) {
        String repository = repositories.get(i).toString();
        if (repository.startsWith("file://"))
            repository = repository.substring(7);
        else if (repository.startsWith("file:"))
            repository = repository.substring(5);
        else if (repository.startsWith("jndi:"))
            repository = servletContext.getRealPath(repository.substring(5));
        else
            continue;
        if (repository == null)
            continue;
        if (i > 0)
            classpath.append(File.pathSeparator);
        classpath.append(repository);
    }

    // Store the assembled class path as a servlet context attribute
    servletContext.setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString());

}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

private ArrayList<BuildInfo> loadBuildInfo(ServletContext servletContext) {
    final ArrayList<BuildInfo> res = new ArrayList<>();
    res.add(BuildInfo.readBuildInfo("au.edu.uq.cmm", "aclslib"));
    res.add(BuildInfo.readBuildInfo("au.edu.uq.cmm", "eccles"));
    try {//from w  ww.  j  av  a 2s .  c om
        Path start = FileSystems.getDefault().getPath(servletContext.getRealPath("/META-INF/maven"));
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().equals("pom.properties")) {
                    try (InputStream is = new FileInputStream(file.toFile())) {
                        res.add(BuildInfo.readBuildInfo(is));
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException ex) {
        LOG.error("Problem loading build info");
    }
    return res;
}

From source file:org.debux.webmotion.server.call.ServerContext.java

/**
 * Initialize the context./*from  w  w w  .  j av a2 s.  c o m*/
 * 
 * @param servletContext servlet context
 */
public void contextInitialized(ServletContext servletContext) {
    this.servletContext = servletContext;
    this.attributes = new HashMap<String, Object>();
    this.handlers = new SingletonFactory<WebMotionHandler>();
    this.controllers = new SingletonFactory<WebMotionController>();
    this.globalControllers = new HashMap<String, Class<? extends WebMotionController>>();
    this.injectors = new ArrayList<Injector>();

    this.beanUtil = BeanUtilsBean.getInstance();
    this.converter = beanUtil.getConvertUtils();

    // Register MBeans
    this.serverStats = new ServerStats();
    this.handlerStats = new HandlerStats();
    this.serverManager = new ServerContextManager(this);

    this.serverStats.register();
    this.handlerStats.register();
    this.serverManager.register();

    this.webappPath = servletContext.getRealPath("/");

    // Read the mapping in the current project
    MappingParser[] parsers = getMappingParsers();
    for (MappingParser parser : parsers) {
        mapping = parser.parse(mappingFileNames);
        if (mapping != null) {
            break;
        }
    }

    String skipConvensionScan = servletContext.getInitParameter("wm.skip.conventionScan");
    if (!"true".equals(skipConvensionScan)) {

        // Scan to generate mapping by convention
        ConventionScan[] conventions = getMappingConventions();
        for (ConventionScan conventionScan : conventions) {
            Mapping convention = conventionScan.scan();

            if (!convention.getActionRules().isEmpty() || !convention.getFilterRules().isEmpty()) {

                if (mapping == null) {
                    mapping = convention;
                } else {
                    mapping.getExtensionsRules().add(convention);
                }
            }
        }
    }

    if (mapping == null) {
        throw new WebMotionException("No mapping found for " + Arrays.toString(mappingFileNames) + " in "
                + Arrays.toString(mappingParsers));
    }

    // Fire onStart
    listeners = new ArrayList<WebMotionServerListener>();
    onStartServerListener(mapping);

    // Load mapping
    loadMapping();

    // Check mapping
    checkMapping();

    log.info("WebMotion is started");
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java

/**
 * Returns the localized version of an English html file
 * English file is something like <root dir>/doc/webUI/userGuide.html
 * the localized file will be <root dir>/doc/webUI/locale/userGuide.html
 *///www  .  ja v a2 s .  co m
public String getLocalizedHTMLFile(String htmlFile) {

    if (htmlFile == null || htmlFile.equals(""))
        return htmlFile;

    // split the file into directory and file name. file name could be followed
    // by #anchor or \#anchor or something else
    int dirIndex = htmlFile.lastIndexOf('/');
    int extensionIndex = htmlFile.indexOf(".html");
    if (dirIndex == -1 || extensionIndex == -1 || (dirIndex + 1) > extensionIndex)
        return htmlFile;
    String dirName = htmlFile.substring(0, dirIndex);
    String fileName = htmlFile.substring(dirIndex + 1, extensionIndex);
    String anchor = htmlFile.substring(extensionIndex + 5);

    UserPreferencesBean userBean = new UserPreferencesBean();
    Locale uiLocale = userBean.getUiLocale();

    ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

    String localizedFile = dirName + "/" + uiLocale.toString() + "/" + fileName + ".html";
    // start with .. because the callers are passing the context path
    String realPath = ctx.getRealPath("../" + localizedFile);
    File f = new File(realPath);
    if (f.exists())
        return localizedFile + anchor;

    // try to use language country, without variant
    if (uiLocale.getVariant() != null && !"".equals(uiLocale.getVariant())) {
        localizedFile = dirName + "/" + uiLocale.getLanguage() + "_" + uiLocale.getCountry() + "/" + fileName
                + ".html";
        realPath = ctx.getRealPath("../" + localizedFile);
        f = new File(realPath);
        if (f.exists())
            return localizedFile + anchor;
    }

    // try to use language without country and variant
    if (uiLocale.getCountry() != null && !"".equals(uiLocale.getCountry())) {
        localizedFile = dirName + "/" + uiLocale.getLanguage() + "/" + fileName + ".html";
        realPath = ctx.getRealPath("../" + localizedFile);
        f = new File(realPath);
        if (f.exists())
            return localizedFile + anchor;
    }
    //fall back to original file
    return htmlFile;
}

From source file:org.ambraproject.util.VersionedFileDirective.java

/**
 * Resolves the filesystem path based on a web request path.  This is made complicated by
 * {@link org.ambraproject.web.VirtualJournalMappingFilter}, which remaps certain paths to journal-specific paths.
 *
 * @param path The original web request path
 * @param request The request object we're currently serving.  Note that this request will have a different path
 *     than the path param./*ww w .  j  ava2  s.  c o  m*/
 * @return The path to the resource on the filesystem
 * @throws ServletException
 */
private String getRealPath(final String path, HttpServletRequest request) throws ServletException {
    VirtualJournalContext vjc = (VirtualJournalContext) request
            .getAttribute(VirtualJournalContext.PUB_VIRTUALJOURNAL_CONTEXT);
    ServletContext servletContext = request.getSession().getServletContext();

    // This is somewhat of a hack.  VirtualJournalContext.mapRequest was originally written to be called with an
    // HttpServletRequest (supplied by VirtualJournalMappingFilter).  To reuse the code, we create a fake request
    // for the resource in question, populating only the fields that matter.
    HttpServletRequest fakeRequest = new HttpServletRequestWrapper(request) {
        public String getRequestURI() {
            return path;
        }

        public String getContextPath() {
            return "";
        }

        public String getServletPath() {
            return path;
        }

        public String getPathInfo() {
            return null;
        }
    };
    Configuration configuration = ConfigurationStore.getInstance().getConfiguration();
    HttpServletRequest mappedRequest = vjc.mapRequest(fakeRequest, configuration, servletContext);

    // If getPathInfo is null, the request was not remapped, and is intended to be served from the root context.  In
    // that case we can get the real path from the ServletContext.
    return mappedRequest.getPathInfo() != null ? mappedRequest.getPathInfo() : servletContext.getRealPath(path);
}