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.delpac.bean.OrdenRetiroBean.java

public void commitCreate1() throws SQLException, JRException, IOException {
    int keyGenerated = daoOrdenRetiro.crearOrdenRetiro(ord, temperado, sessionUsuario, ingresado);
    conexion con = new conexion();
    try {/*from  w  w w.  j  av a2s.  co m*/
        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servleContext = (ServletContext) context.getExternalContext().getContext();
        String temperatura = temperado == true ? "ReporteFreezer.jasper" : "ReporteNoFreezer.jasper";
        String jrxmlPath = temperatura.equals("ReporteFreezer.jasper") ? "ReporteFreezer.jrxml"
                : "ReporteNoFreezer.jrxml";//server
        String nom_archivo = "OR_BK_" + ord.getBooking() + ".pdf";
        String exportDir = System.getProperty("catalina.base") + "/OrdenesRetiro/";//server
        String exportPath = exportDir + nom_archivo;//server            
        String dirReporte = servleContext.getRealPath("/reportes/" + temperatura);
        File reporte = new File(servleContext.getRealPath("/reportes/") + jrxmlPath);
        HashMap<String, Object> parametros = new HashMap<String, Object>();
        List<JasperPrint> prints = new ArrayList<JasperPrint>();
        for (int cont = 1; cont <= ingresado; cont++) {
            parametros.put("RutaImagen", servleContext.getRealPath("/reportes/"));
            parametros.put("cod_ordenretiro", keyGenerated);
            keyGenerated--;
            JasperPrint jasperPrint = JasperFillManager.fillReport(dirReporte, parametros, con.getConnection());//server
            prints.add(jasperPrint);
        }
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.addHeader("Content-disposition", "attachment;filename=" + nom_archivo);
        response.setContentType("application/pdf");
        JRPdfExporter exporter = new JRPdfExporter();
        exporter.setExporterInput(SimpleExporterInput.getInstance(prints));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
        SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
        configuration.setCreatingBatchModeBookmarks(true);
        exporter.setConfiguration(configuration);
        exporter.exportReport();
        context.responseComplete();
    } catch (Exception e) {
        System.err.println(e);
    }
    listadoOrdenes = daoOrdenRetiro.findAllOrdenes();
}

From source file:com.liferay.portal.struts.PortalTilesDefinitionsFactory.java

/**
 * Parse specified xml file and add definition to specified definitions set.
 * This method is used to load several description files in one instances list.
 * If filename exists and definition set is <code>null</code>, create a new set. Otherwise, return
 * passed definition set (can be <code>null</code>).
 * @param servletContext Current servlet context. Used to open file.
 * @param filename Name of file to parse.
 * @param xmlDefinitions Definitions set to which definitions will be added. If null, a definitions
 * set is created on request./* w w w  .j a v  a  2  s  .  co  m*/
 * @return XmlDefinitionsSet The definitions set created or passed as parameter.
 * @throws DefinitionsFactoryException On errors parsing file.
 */
private XmlDefinitionsSet parseXmlFile(ServletContext servletContext, String filename,
        XmlDefinitionsSet xmlDefinitions) throws DefinitionsFactoryException {

    try {
        InputStream input = servletContext.getResourceAsStream(filename);
        // Try to load using real path.
        // This allow to load config file under websphere 3.5.x
        // Patch proposed Houston, Stephen (LIT) on 5 Apr 2002
        if (null == input) {
            try {
                input = new java.io.FileInputStream(servletContext.getRealPath(filename));
            } catch (Exception e) {
            }
        }

        // If the config isn't in the servlet context, try the class loader
        // which allows the config files to be stored in a jar
        if (input == null) {
            input = getClass().getResourceAsStream(filename);
        }

        // If still nothing found, this mean no config file is associated
        if (input == null) {
            if (log.isDebugEnabled()) {
                log.debug("Can't open file '" + filename + "'");
            }
            return xmlDefinitions;
        }

        // Check if parser already exist.
        // Doesn't seem to work yet.
        //if( xmlParser == null )
        if (true) {
            xmlParser = new XmlParser();
            xmlParser.setValidating(isValidatingParser);
        }

        // Check if definition set already exist.
        if (xmlDefinitions == null) {
            xmlDefinitions = new XmlDefinitionsSet();
        }

        xmlParser.parse(input, xmlDefinitions);

    } catch (SAXException ex) {
        if (log.isDebugEnabled()) {
            log.debug("Error while parsing file '" + filename + "'.");
            ex.printStackTrace();
        }
        throw new DefinitionsFactoryException("Error while parsing file '" + filename + "'. " + ex.getMessage(),
                ex);

    } catch (IOException ex) {
        throw new DefinitionsFactoryException(
                "IO Error while parsing file '" + filename + "'. " + ex.getMessage(), ex);
    }

    return xmlDefinitions;
}

From source file:org.bibalex.wamcp.storage.WAMCPStorage.java

public long createFromTemplate(String templateFilePathRel, String shelfmark, String albumName,
        String albumCaption, String albumCoverName)
        throws IOException, SVNException, WFSVNException, JDOMException, WAMCPException, BAGException {

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();//www .  ja va2 s.  co  m

    String templateFilePath = servletContext.getRealPath(templateFilePathRel);
    File templateFile = new File(templateFilePath);

    SAXBuilder saxBuilder = new SAXBuilder();

    saxBuilder.setFeature("http://xml.org/sax/features/validation", false);
    saxBuilder.setFeature("http://xml.org/sax/features/namespaces", true);
    saxBuilder.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    // Unsupported:
    // saxBuilder.setFeature("http://xml.org/sax/features/xmlns-uris",
    // false);

    Document templateDoc = saxBuilder.build(templateFile);
    return this.createFromDocument(templateDoc, shelfmark, albumName, albumCaption, albumCoverName);
}

From source file:axiom.servlet.AbstractServletClient.java

/**
 * Forward the request to a static file. The file must be reachable via
 * the context's protectedStatic resource base.
 *///from  w  w  w .j  a  va2s  . c om
void sendForward(HttpServletResponse res, HttpServletRequest req, ResponseTrans axiomres) throws IOException {
    String forward = axiomres.getForward();
    ServletContext cx = getServletConfig().getServletContext();
    String path = cx.getRealPath(forward);
    if (path == null)
        throw new IOException("Resource " + forward + " not found");

    File file = new File(path);
    // calculate checksom on last modified date and content length.
    byte[] checksum = getChecksum(file);
    String etag = "\"" + new String(Base64.encode(checksum)) + "\"";
    res.setHeader("ETag", etag);
    String etagHeader = req.getHeader("If-None-Match");
    if (etagHeader != null) {
        StringTokenizer st = new StringTokenizer(etagHeader, ", \r\n");
        while (st.hasMoreTokens()) {
            if (etag.equals(st.nextToken())) {
                res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
        }
    }
    int length = (int) file.length();
    res.setContentLength(length);
    res.setContentType(axiomres.getContentType());

    InputStream in = cx.getResourceAsStream(forward);
    if (in == null)
        throw new IOException("Can't read " + path);
    try {
        OutputStream out = res.getOutputStream();

        int bufferSize = 4096;
        byte buffer[] = new byte[bufferSize];
        int l;

        while (length > 0) {
            if (length < bufferSize)
                l = in.read(buffer, 0, length);
            else
                l = in.read(buffer, 0, bufferSize);

            if (l == -1)
                break;

            length -= l;
            out.write(buffer, 0, l);
        }
    } finally {
        in.close();
    }
}

From source file:com.aurel.track.ApplicationStarter.java

private void printSystemInfo() {
    LOGGER.info("Java: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version"));
    LOGGER.info("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.arch"));
    Locale loc = Locale.getDefault();
    LOGGER.info("Default locale: " + loc.getDisplayName());

    ServletContext application = ApplicationBean.getInstance().getServletContext();
    try {/*  w  ww. j a va  2  s .com*/
        LOGGER.info("Servlet real path: " + application.getRealPath(File.separator));
    } catch (Exception ex) {
        LOGGER.error("Error trying to obtain getRealPath()");
    }
    LOGGER.info("Servlet container: " + application.getServerInfo());

    Connection conn = null;
    try {
        PropertiesConfiguration pc = ApplicationBean.getInstance().getDbConfig();
        LOGGER.info("Configured database type: " + pc.getProperty("torque.database.track.adapter"));
        LOGGER.info(
                "Configured database driver: " + pc.getProperty("torque.dsfactory.track.connection.driver"));
        LOGGER.info("Configured JDBC URL: " + pc.getProperty("torque.dsfactory.track.connection.url"));
        conn = Torque.getConnection(BaseTSitePeer.DATABASE_NAME);
        DatabaseMetaData dbm = conn.getMetaData();
        LOGGER.info("Database type: " + dbm.getDatabaseProductName() + " " + dbm.getDatabaseProductVersion());
        LOGGER.info("Driver info:   " + dbm.getDriverName() + " " + dbm.getDriverVersion());
        Statement stmt = conn.createStatement();
        Date d1 = new Date();
        stmt.executeQuery("SELECT * FROM TSTATE");
        Date d2 = new Date();
        stmt.close();
        LOGGER.info("Database test query done in " + (d2.getTime() - d1.getTime()) + " milliseconds ");
    } catch (Exception e) {
        System.err.println("Problem retrieving meta data");
        LOGGER.error("Problem retrieving meta data");
    } finally {
        if (conn != null) {
            Torque.closeConnection(conn);
        }
    }
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private void installPlugin(AvailableArtifact availableArtifact, String version, InputStream is)
        throws Exception {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext)
            .getServletContext();//  w w  w  .  j  a va  2 s.  c  o  m
    String filename = availableArtifact.getGroupId() + "_" + availableArtifact.getArtifactId() + "_" + version
            + ".war";
    String artifactName = availableArtifact.getArtifactId();
    String appRootPath = servletContext.getRealPath("/");
    File destDir = new File(appRootPath);
    String tempDirPath = appRootPath + "componentinstaller" + File.separator + artifactName;
    File artifactFile = new File(appRootPath + "componentinstaller" + File.separator + filename);

    FileUtils.copyInputStreamToFile(is, artifactFile);
    this.extractArchiveFile(artifactFile, tempDirPath);
    File artifactFileRootDir = new File(
            artifactFile.getParentFile().getAbsolutePath() + File.separator + artifactName);

    List<File> tilesFiles = (List<File>) FileUtils.listFiles(artifactFileRootDir,
            FileFilterUtils.suffixFileFilter("-tiles.xml"), FileFilterUtils.trueFileFilter());
    if (tilesFiles == null) {
        tilesFiles = new ArrayList<File>();
    }

    File tempArtifactRootDir = this.extractAllJars(destDir, artifactName);
    List<File> pluginSqlFiles = (List<File>) FileUtils.listFiles(tempArtifactRootDir, new String[] { "sql" },
            true);
    List<File> pluginXmlFiles = (List<File>) FileUtils.listFiles(tempArtifactRootDir, new String[] { "xml" },
            true);

    List<File> mainAppJarLibraries = (List<File>) FileUtils.listFiles(
            new File(destDir.getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "lib"),
            new String[] { "jar" }, true);
    List<File> pluginJarLibraries = (List<File>) FileUtils.listFiles(artifactFileRootDir,
            new String[] { "jar" }, true);
    pluginJarLibraries = filterOutDuplicateLibraries(mainAppJarLibraries, pluginJarLibraries);

    FileUtils.copyDirectory(artifactFileRootDir, destDir);

    List<File> allFiles = new ArrayList<File>();
    File systemParamsFile = FileUtils.getFile(destDir + File.separator + "WEB-INF" + File.separator + "conf",
            "systemParams.properties");
    allFiles.add(systemParamsFile);
    allFiles.addAll(pluginJarLibraries);
    allFiles.addAll(pluginSqlFiles);
    allFiles.addAll(pluginXmlFiles);
    //The classloader's content is stored in servlet context and 
    //updated every time so the classloader will eventually contain 
    //the classes and resources of all the installed plugins
    List<URL> urlList = (List<URL>) servletContext.getAttribute("pluginInstallerURLList");
    if (urlList == null) {
        urlList = new ArrayList<URL>();
        servletContext.setAttribute("pluginInstallerURLList", urlList);
    }
    Set<File> jarSet = (Set<File>) servletContext.getAttribute("pluginInstallerJarSet");
    if (jarSet == null) {
        jarSet = new HashSet<File>();
        servletContext.setAttribute("pluginInstallerJarSet", jarSet);
    }
    jarSet.addAll(pluginJarLibraries);
    URLClassLoader cl = getURLClassLoader(urlList, allFiles.toArray(new File[0]), servletContext);
    loadClasses(jarSet.toArray(new File[0]), cl);
    servletContext.setAttribute("componentInstallerClassLoader", cl);
    ComponentManager.setComponentInstallerClassLoader(cl);

    //load plugin and dependencies contexts 
    File componentFile = this.getFileFromArtifactJar(tempArtifactRootDir, "component.xml");
    String componentToInstallName = this.getComponentName(componentFile);

    InitializerManager initializerManager = (InitializerManager) this._applicationContext
            .getBean("InitializerManager");
    initializerManager.reloadCurrentReport();
    SystemInstallationReport currentReport = initializerManager.getCurrentReport();
    if (null != currentReport.getComponentReport(componentToInstallName, false)) {
        currentReport.removeComponentReport(componentToInstallName);
        this.saveReport(currentReport);
        initializerManager.reloadCurrentReport();
    }

    List<String> components = this.getAllComponents(artifactFileRootDir);

    Properties properties = new Properties();
    properties.load(new FileInputStream(systemParamsFile));

    for (String componentName : components) {
        List<String> configLocs = new ArrayList<String>();
        InitializerManager currenInitializerManager = (InitializerManager) _applicationContext
                .getBean("InitializerManager");
        currentReport = currenInitializerManager.getCurrentReport();
        ComponentInstallationReport cir = currentReport.getComponentReport(componentName, false);
        if (null != cir && cir.getStatus().equals(SystemInstallationReport.Status.UNINSTALLED)) {
            currentReport.removeComponentReport(componentName);
            this.saveReport(currentReport);
            currenInitializerManager.reloadCurrentReport();
        }

        configLocs = this.getConfigPaths(artifactFileRootDir, componentName);
        if (configLocs.isEmpty()) {
            continue;
        }

        ClassPathXmlApplicationContext newContext = (ClassPathXmlApplicationContext) loadContext(
                (String[]) configLocs.toArray(new String[0]), cl, componentName, properties);

        this.reloadActionsDefinitions(newContext);
        this.reloadResourcsBundles(newContext, servletContext);
        TilesContainer container = TilesAccess.getContainer(servletContext);
        this.reloadTilesDefinitions(tilesFiles, container);

        currenInitializerManager.reloadCurrentReport();
        ComponentManager componentManager = (ComponentManager) _applicationContext.getBean("ComponentManager");
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(newContext.getClassLoader());
            componentManager.refresh();
        } catch (Exception e) {
            throw e;
        } finally {
            Thread.currentThread().setContextClassLoader(currentClassLoader);
        }
    }
}

From source file:it.classhidra.core.controller.bsController.java

public static String getContextConfigPath(ServletContext servletContext) {
    String path = servletContext.getRealPath("/");
    if (appInit != null && appInit.getApplication_path_config() != null)
        path += appInit.getApplication_path_config();
    path = path.replace('\\', '/');
    //      while (path.indexOf("//")>-1) path=path.replace("//", "/");
    while (path.indexOf("//") > -1)
        path = util_format.replace(path, "//", "/");
    return path;/*ww w.  j  av a  2 s . c  om*/
}

From source file:com.alfaariss.oa.helper.stylesheet.StyleSheetEngine.java

private File resolveFile(String filename, ServletContext context) throws OAException {
    //Try absolute
    File file = new File(filename);
    if (!file.exists()) {
        _logger.warn("File not found at: " + file.getAbsolutePath());

        //Try user directory
        String sUserDir = System.getProperty("user.dir");
        StringBuffer sbFile = new StringBuffer(sUserDir);
        if (!sUserDir.endsWith(File.separator))
            sbFile.append(File.separator);
        sbFile.append(file);//from  ww w .  jav  a  2 s  .c  o m
        file = new File(sbFile.toString());
        if (!file.exists()) {
            _logger.warn("File not found at: " + file.getAbsolutePath());

            if (context != null) {
                //Try WEB-INF/conf
                String sWebInf = context.getRealPath("WEB-INF");
                sbFile = new StringBuffer(sWebInf);
                if (!sbFile.toString().endsWith(File.separator))
                    sbFile.append(File.separator);
                sbFile.append("conf").append(File.separator);
                sbFile.append(filename);
                file = new File(sbFile.toString());
                if (!file.exists()) {
                    _logger.error("File not found: " + filename);
                    throw new OAException(SystemErrors.ERROR_CONFIG_READ);
                }
            } else {
                _logger.error("File not found: " + filename);
                throw new OAException(SystemErrors.ERROR_CONFIG_READ);
            }
        }
    }
    _logger.info("Using file: " + file.getAbsolutePath());
    return file;

}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(method = RequestMethod.GET)
public void doDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {

    int BUFFER_SIZE = 4096;
    String filePath = "/WEB-INF/jsp/studentviewgenerated.jsp";
    // get absolute path of the application
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    System.out.println("appPath = " + appPath);

    // construct the complete absolute path of the file
    String fullPath = appPath + filePath;
    File downloadFile = new File(fullPath);
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    String mimeType = context.getMimeType(fullPath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }//from  ww w .  j a v  a2 s  . co  m
    System.out.println("MIME type: " + mimeType);

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();

}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Gets a file (or directory) with a specific name from the root of the web application
 * @param servletContext//  www.ja va2 s .co m
 * @param fileName
 * @return
 */
public static File getResourceFileFromWebAppRoot(ServletContext servletContext, String fileName) {
    URL urlDest;
    File file = null;
    //first try to get the template dir through class.getResource(path)
    urlDest = PluginUtils.class.getResource("/../../" + fileName);
    urlDest = createValidFileURL(urlDest);
    if (urlDest != null) {
        file = new File(urlDest.getPath());
    }
    //second try to get the template dir through servletContext.getResource(path)
    if ((file == null || !file.exists()) && servletContext != null) {
        try {
            urlDest = servletContext.getResource("/" + fileName);
            urlDest = createValidFileURL(urlDest);
            if (urlDest != null) {
                file = new File(urlDest.getPath());
            }
        } catch (MalformedURLException e) {
            LOGGER.error("Getting the URL through getServletContext().getResource(path) failed with "
                    + e.getMessage());
        }
    }
    //third try to get the template dir through servletContext.getRealPath(path)
    if ((file == null || !file.exists()) && servletContext != null) {
        String path;
        //does not work for unexpanded .war
        path = servletContext.getRealPath(File.separator) + fileName;
        file = new File(path);
    }
    return file;
}