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:com.nabla.dc.server.MyReadWriteDatabase.java

@Inject
public MyReadWriteDatabase(final ServletContext serverContext, final ReportManager reportManager)
        throws SQLException, DispatchException {
    super("dcrw", serverContext, IRoles.class, serverContext.getInitParameter("root_password"));

    if ("1".equals(serverContext.getInitParameter(PRODUCTION_MODE))) {
        if (log.isDebugEnabled())
            log.debug("loading internal report table");
        final Connection conn = getConnection();
        try {//from   ww w  . jav  a 2  s . c  o m
            final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn);
            try {
                Database.executeUpdate(conn, "DELETE FROM report WHERE internal_name IS NOT NULL;");
                final File reportFolder = new File(
                        serverContext.getRealPath(ReportManager.INTERNAL_REPORT_FOLDER));
                for (File folder : reportFolder.listFiles((FileFilter) DirectoryFileFilter.INSTANCE))
                    loadInternalReport(conn, folder, reportManager);
                guard.setSuccess();
            } finally {
                guard.close();
            }
        } finally {
            conn.close();
        }
    }
}

From source file:org.codelibs.fess.helper.SystemHelper.java

public void refreshDesignJspFiles() {
    final ServletContext servletContext = LaServletContextUtil.getServletContext();
    stream(ComponentUtil.getVirtualHostHelper().getVirtualHostPaths())
            .of(stream -> stream.filter(s -> s != null && !s.equals("/")).forEach(key -> {
                designJspFileNameMap.entrySet().stream().forEach(e -> {
                    final File jspFile = new File(
                            servletContext.getRealPath("/WEB-INF/view" + key + "/" + e.getValue()));
                    if (!jspFile.exists()) {
                        jspFile.getParentFile().mkdirs();
                        final File baseJspFile = new File(
                                servletContext.getRealPath("/WEB-INF/view/" + e.getValue()));
                        try {
                            Files.copy(baseJspFile.toPath(), jspFile.toPath());
                        } catch (final IOException ex) {
                            logger.warn("Could not copy from " + baseJspFile.getAbsolutePath() + " to "
                                    + jspFile.getAbsolutePath(), ex);
                        }//from  ww  w  .j  a va  2s  . c  o m
                    }
                });
            }));
}

From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java

/**
 * Converts a relative path to an absolute, if necessary
 * @param   directory//www .  j ava  2s .co  m
 * @returns   absolutized path, or null if invalid
 */
private String getAbsolutePath(String directory, ServletContext context) {
    if (directory != null && !new File(directory).isDirectory()
            && new File(context.getRealPath(directory)).isDirectory())
        return context.getRealPath(directory);
    else
        return directory;
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.RunSparqlConstructs.java

public void contextInitialized(ServletContextEvent sce) {
    try {/*from w w  w.jav a2 s . c om*/
        ServletContext ctx = sce.getServletContext();
        WebappDaoFactory wadf = ModelAccess.on(ctx).getWebappDaoFactory();

        String namespace = (wadf != null && wadf.getDefaultNamespace() != null) ? wadf.getDefaultNamespace()
                : DEFAULT_DEFAULT_NAMESPACE;

        OntModel baseOntModel = ModelAccess.on(ctx).getOntModel(FULL_ASSERTIONS);
        Model anonModel = ModelFactory.createDefaultModel();
        Model namedModel = ModelFactory.createDefaultModel();

        Set<String> resourcePaths = ctx.getResourcePaths(SPARQL_DIR);
        for (String path : resourcePaths) {
            log.debug("Attempting to execute SPARQL at " + path);
            File file = new File(ctx.getRealPath(path));
            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                StringBuffer fileContents = new StringBuffer();
                String ln;
                try {
                    while ((ln = reader.readLine()) != null) {
                        fileContents.append(ln).append('\n');
                    }
                    try {
                        Query q = QueryFactory.create(fileContents.toString(), Syntax.syntaxARQ);
                        QueryExecution qe = QueryExecutionFactory.create(q, baseOntModel);
                        qe.execConstruct(anonModel);
                    } catch (Exception e) {
                        String queryErrMsg = "Unable to execute query at " + path + " :";
                        log.error(queryErrMsg);
                        System.out.println(queryErrMsg);
                        e.printStackTrace();
                    }
                } catch (IOException ioe) {
                    log.error("IO Exception reading " + path + " :");
                    ioe.printStackTrace();
                }
            } catch (FileNotFoundException fnfe) {
                log.info(path + " not found. Skipping.");
            }
        }

        namedModel.add(anonModel);

        for (Iterator<Resource> i = anonModel.listSubjects(); i.hasNext();) {
            Resource s = i.next();
            if (s.isAnon()) {
                int randomInt = -1;
                while (randomInt < 0
                        || baseOntModel.getIndividual(namespace + LOCAL_NAME_PREPEND + randomInt) != null) {
                    randomInt = random.nextInt(Integer.MAX_VALUE);
                }
                Resource t = namedModel.createResource(s.getId());
                ResourceUtils.renameResource(t, namespace + LOCAL_NAME_PREPEND + randomInt);
            }
        }

        baseOntModel.addSubModel(namedModel);
        String msg = "Attaching " + namedModel.size() + " statements as a result of SPARQL CONSTRUCTS";
        log.info(msg);
        System.out.println(msg);

    } catch (Throwable t) {
        System.out.println("Throwable in listener " + this.getClass().getName());
        t.printStackTrace();
        log.error(t);
    }
}

From source file:fll.web.GatherBugReport.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    ZipOutputStream zipOut = null;
    final StringBuilder message = new StringBuilder();
    try {/* w w w  .  j a  v a  2 s  .  c o m*/
        if (null != SessionAttributes.getMessage(session)) {
            message.append(SessionAttributes.getMessage(session));
        }

        connection = datasource.getConnection();
        final Document challengeDocument = ApplicationAttributes.getChallengeDocument(application);

        final File fllWebInfDir = new File(application.getRealPath("/WEB-INF"));
        final String nowStr = new SimpleDateFormat("yyyy-MM-dd_HH-mm").format(new Date());
        final File bugReportFile = File.createTempFile(nowStr, ".zip", fllWebInfDir);

        zipOut = new ZipOutputStream(new FileOutputStream(bugReportFile));

        final String description = request.getParameter("bug_description");
        if (null != description) {
            zipOut.putNextEntry(new ZipEntry("bug_description.txt"));
            zipOut.write(description.getBytes(Utilities.DEFAULT_CHARSET));
        }

        zipOut.putNextEntry(new ZipEntry("server_info.txt"));
        zipOut.write(String.format(
                "Java version: %s%nJava vendor: %s%nOS Name: %s%nOS Arch: %s%nOS Version: %s%nServlet API: %d.%d%nServlet container: %s%n",
                System.getProperty("java.vendor"), //
                System.getProperty("java.version"), //
                System.getProperty("os.name"), //
                System.getProperty("os.arch"), //
                System.getProperty("os.version"), //
                application.getMajorVersion(), application.getMinorVersion(), //
                application.getServerInfo()).getBytes(Utilities.DEFAULT_CHARSET));

        addDatabase(zipOut, connection, challengeDocument);
        addLogFiles(zipOut, application);

        message.append(String.format(
                "<i>Bug report saved to '%s', please notify the computer person in charge to look for bug report files.</i>",
                bugReportFile.getAbsolutePath()));
        session.setAttribute(SessionAttributes.MESSAGE, message);

        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/"));

    } catch (final SQLException sqle) {
        throw new RuntimeException(sqle);
    } finally {
        SQLFunctions.close(connection);
        IOUtils.closeQuietly(zipOut);
    }

}

From source file:org.squale.welcom.struts.webServer.URLManager.java

/**
 * Retoune le webFile dans le repertoire webcontent
 * //ww w .  ja v  a 2 s.c o m
 * @param context context
 * @param pUrl url
 * @return le webfile
 */
public WebFile getWebFileFromContext(ServletContext context, String pUrl) {
    WebFile webFile = new WebFile(WebFile.TYPE_SERVLET);
    // Compatibilit Tomcat !!
    try {
        webFile.setUrl(context.getResource(pUrl));
    } catch (final Exception e) {
        try {
            // Test compatiblite Tomcat (Necessite un /)
            webFile.setUrl(context.getResource("/" + pUrl));
        } catch (final Exception ee) {
            // Recherche si la resource demand ne se trouve pas dans le jar Welcom
        }
    }

    if (webFile.getUrl() != null) {
        // recherche la date
        final String file = context.getRealPath(sUrl);

        final File f = new File(file);
        webFile.setLastDate(new Date(f.lastModified()));
        return webFile;
    } else {
        return null;
    }

}

From source file:com.siacra.beans.GrupoBean.java

public void handleFileUpload2(FileUploadEvent event) {
    try {/*from   w  w  w.jav a2s .  c  o m*/
        /* Obtenemos el path */
        ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String path = context.getRealPath("/WEB-INF/files/");
        /* Inicializamos el destino y el origen */

        InputStream inputStream = event.getFile().getInputstream();
        /*  Escribimos en el destino, leyendo la data del origen */
        /* Cerramos los archivos */
        inputStream.close();

        RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_INFO,
                "Informacion", "El archivo fue cargado correctamente"));
        archivoXlsx(path, event);

    } catch (IOException e) {
        RequestContext.getCurrentInstance().showMessageInDialog(new FacesMessage(FacesMessage.SEVERITY_FATAL,
                "Informacion", "El archivo no pudo ser cargado correctamente"));
        System.out.println(e.getMessage());
    }
}

From source file:com.nartex.FileManager.java

public FileManager(ServletContext servletContext, HttpServletRequest request) {
    // get document root like in php
    String contextPath = request.getContextPath();
    String documentRoot = servletContext.getRealPath("/").replaceAll("\\\\", "/");
    documentRoot = documentRoot.substring(0, documentRoot.indexOf(contextPath));

    this.referer = request.getHeader("referer");
    this.fileManagerRoot = documentRoot
            + referer.substring(referer.indexOf(contextPath), referer.indexOf("index.html"));

    // get uploaded file list
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (ServletFileUpload.isMultipartContent(request))
        try {/*  w  ww  .j av  a 2 s.  c  o m*/
            files = upload.parseRequest(request);
        } catch (Exception e) { // no error handling}
        }

    this.properties.put("Date Created", null);
    this.properties.put("Date Modified", null);
    this.properties.put("Height", null);
    this.properties.put("Width", null);
    this.properties.put("Size", null);

    // load config file
    loadConfig();

    if (config.getProperty("doc_root") != null)
        this.documentRoot = config.getProperty("doc_root");
    else
        this.documentRoot = documentRoot;

    dateFormat = new SimpleDateFormat(config.getProperty("date"));

    this.setParams();

    loadLanguageFile();
}

From source file:com.utilities.FileManager.java

public FileManager(ServletContext servletContext, HttpServletRequest request) {
    // get document root like in php
    String contextPath = request.getContextPath();
    String documentRoot = servletContext.getRealPath("/").replaceAll("\\\\", "/");
    System.out.println("CP: " + contextPath + " DR: " + documentRoot);
    //documentRoot = documentRoot.substring(0, documentRoot.indexOf(contextPath));

    this.referer = request.getHeader("referer");
    System.out.println("Referer: " + this.referer);
    this.fileManagerRoot = documentRoot; //+ referer.substring(referer.indexOf(contextPath), referer.indexOf("fileManager.jsp"));

    // get uploaded file list
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (ServletFileUpload.isMultipartContent(request))
        try {/*from   w  w w .j  a v a 2  s  .  c o  m*/
            files = upload.parseRequest(request);
        } catch (Exception e) { // no error handling}
        }

    this.properties.put("Date Created", null);
    this.properties.put("Date Modified", null);
    this.properties.put("Height", null);
    this.properties.put("Width", null);
    this.properties.put("Size", null);

    // load config file
    loadConfig();

    if (config.getProperty("doc_root") != null)
        this.documentRoot = config.getProperty("doc_root");
    else
        this.documentRoot = documentRoot;

    dateFormat = new SimpleDateFormat(config.getProperty("date"));

    this.setParams();

    loadLanguageFile();
}

From source file:Bean.CAT.TerminosBean.java

public List<Termino>[] deserializarTerminosTest()
           throws FileNotFoundException, IOException, ClassNotFoundException {

       List<Termino>[] terminos;
       ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
               .getContext();/*w  ww .  j  a  v a2 s  .co m*/
       String realPath = (String) servletContext.getRealPath("/"); // Sustituye "/" por el directorio ej: "/upload"

       //recuperar los terminos // setearle el rut del examinado para obtenerlo
       ObjectInputStream entrada = new ObjectInputStream(
               new FileInputStream(realPath + "/Tests/" + test.getIdTest() + ".obj"));
       terminos = (List<Termino>[]) entrada.readObject();

       return terminos;
   }