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.apache.struts.scripting.ScriptAction.java

/**
 *  Loads the script from cache if possible. Reloads if the script has been
 *  recently modified.//from  ww  w  . ja v  a2 s .  com
 *
 *@param  name     The name of the script
 *@param  context  The servlet context
 *@return          The script object
 */
protected Script loadScript(String name, ServletContext context) {

    Script script = (Script) scripts.get(name);
    if (script == null) {
        script = new Script();
        script.file = new File(context.getRealPath(name));
        try {
            script.lang = BSFManager.getLangFromFilename(script.file.getName());
        } catch (BSFException ex) {
            LOG.warn(ex, ex);
        }
    }

    boolean reloadScript = false;
    long scriptLastModified = script.file.lastModified();
    if (scriptLastModified > script.timeLastLoaded) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading updated or new script: " + script.file.getName());
        }
        reloadScript = true;
    }

    if (reloadScript || script.string == null) {
        synchronized (this) {
            script.timeLastLoaded = System.currentTimeMillis();
            FileReader reader = null;
            try {
                reader = new FileReader(script.file);
                script.string = IOUtils.getStringFromReader(reader);
            } catch (IOException ex) {
                LOG.error("Unable to load script: " + script.file, ex);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        LOG.debug(ex, ex);
                    }
                }
            }
        }
    }

    return script;
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

private byte[] emptyGif(ServletContext ctx) throws IOException {
    if (emptyImage != null)
        return emptyImage;

    String path = ctx.getRealPath("/data/jarss/img/empty.gif");
    byte[] data = IOUtils.toByteArray(new FileInputStream(path));

    emptyImage = data;/*w w w. j  a v  a 2  s  . c  om*/
    return data;
}

From source file:Bean.CAT.ModifTestBean.java

public void unirListas() throws IOException, FileNotFoundException, ClassNotFoundException {

    System.out.println(" ingresando unir listas");
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();//from   ww w  .  j av a2s.com
    String pathTermNuevos = (String) servletContext.getRealPath("/") + "/Terminos/NuevosTermDiccGlobal.obj";
    String pathTermNuevosAsoc = (String) servletContext.getRealPath("/")
            + "/Terminos/NuevosTermAsocDiccGlobal.obj";
    File f = new File(pathTermNuevos);
    File e = new File(pathTermNuevosAsoc);
    // if(f.exists() && !f.isDirectory()) { 

    if (f.exists() && e.exists()) {

        System.out.println(" la lista de cambios ya existe por lo que se deserializarn");
        listNuevosTermAsocDiccGlobal = deserializarNuevosTermAsocDiccGlobal();
        listNuevosTermDiccGlobal = deserializarlistNuevosTermDiccGlobal();

    }

    List<TerminoLamina>[] terminosTempGlobal = new ArrayList[10];
    System.out.println("comenzando union de listas asoc");
    for (int i = 0; i < 10; i++) {
        System.out.println("union " + i);
        List<TerminoLamina> terminosTemp = ListUtils.union(listNuevosTermAsocDicc[i],
                listNuevosTermAsocDiccGlobal[i]);
        terminosTempGlobal[i] = terminosTemp;

    }
    System.out.println("comenzando union de listas nuevos terminos");
    List<TerminoLamina>[] terminosTempGlobal2 = new ArrayList[10];
    for (int i = 0; i < 10; i++) {
        System.out.println("union " + i);
        List<TerminoLamina> terminosTemp2 = ListUtils.union(listNuevosTermDicc[i], listNuevosTermDiccGlobal[i]);
        terminosTempGlobal2[i] = terminosTemp2;

    }
    listNuevosTermAsocDiccGlobal = terminosTempGlobal;
    listNuevosTermDiccGlobal = terminosTempGlobal2;

    //serializamos los cambios en las listas del diccionario
    serializarListasCambiosDiccionario();
    System.out.println(" se serializaron las listas globales de cambios en diccionario");

}

From source file:com.siberhus.web.ckeditor.servlet.OpenFileManagerConnectorServlet.java

private String getBaseDir(HttpServletRequest request, String baseUrl) {
    CkeditorConfig config = CkeditorConfigurationHolder.config();
    ServletContext servletContext = request.getSession().getServletContext();
    String baseDir = null;//from w  w  w  . ja  va 2  s. com
    if (config.upload().baseurl(request) != null) {
        baseDir = PathUtils.checkSlashes(baseUrl, "L+ R+", true);
        baseDir = servletContext.getRealPath(baseDir);
        baseDir = PathUtils.checkSlashes(baseDir, "R+", false);
    } else {
        baseDir = servletContext.getRealPath(baseUrl);
        baseDir = PathUtils.checkSlashes(baseDir, "R+", false);
    }

    File f = new File(baseDir);
    if (!f.exists()) {
        f.mkdirs();
    }
    return baseDir;
}

From source file:tds.student.sql.repository.ConfigLoader.java

@Override
public void setServletContext(ServletContext servletContext) {
    _projectsPath = servletContext.getRealPath("/Projects");
}

From source file:com.delpac.bean.OrdenRetiroBean.java

public void download(OrdenRetiro ord) throws SQLException, JRException, IOException {
    conexion con = new conexion();
    try {//w w  w .j  a va  2  s.  c o m
        HashMap<String, Object> parametros = new HashMap<String, Object>();
        //Contexto
        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servleContext = (ServletContext) context.getExternalContext().getContext();
        //Parametros
        parametros.put("RutaImagen", servleContext.getRealPath("/reportes/"));
        parametros.put("cod_ordenretiro", ord.getCod_ordenretiro());
        //String del jasper
        String temperatura = ord.getEs_temperado() == 1 ? "ReporteFreezer.jasper" : "ReporteNoFreezer.jasper";
        //            String jrxmlPath = temperatura.equals("ReporteFreezer.jasper") ? "ReporteFreezer.jrxml" : "ReporteNoFreezer.jrxml";//server
        //InputStream
        //            InputStream is = new FileInputStream(servleContext.getRealPath("/reportes/") + jrxmlPath);//server
        String dirReporte = servleContext.getRealPath("/reportes/" + temperatura);
        String nom_archivo = "OR_BK_" + ord.getBooking() + ".pdf";
        //            String exportDir = System.getProperty("catalina.base") + "/OrdenesRetiro/";//server
        //            String exportPath = exportDir + nom_archivo;//server
        //JasperDesign
        //            JasperDesign design = JRXmlLoader.load(is);//server
        //            JasperReport jasperReport = JasperCompileManager.compileReport(design);//server
        //Servlet Response
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.addHeader("Content-disposition", "attachment;filename=" + nom_archivo);
        response.setContentType("application/pdf");
        //            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, con.getConnection());//server
        JasperPrint jasperPrint = JasperFillManager.fillReport(dirReporte, parametros, con.getConnection());
        //            JasperExportManager.exportReportToPdfFile(jasperPrint, exportPath); //server
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
        context.responseComplete();
    } catch (Exception e) {
        System.err.println(e);
    }
    listadoOrdenes = daoOrdenRetiro.findAllOrdenes();
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadThemes(ServletContext servletContext) throws Exception {

    // assume no themes
    int themeCount = 0;

    // create a list for our themes
    List<Theme> themes = new ArrayList<Theme>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/themes/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".theme.xml");
        }/*from   w  w w  .  ja  v  a 2  s. com*/
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/theme.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"))));

        // create a theme object from the xml
        Theme theme = new Theme(xml);

        // add it to our collection
        themes.add(theme);

        // inc the template count
        themeCount++;

    }

    // sort the list of templates by name
    Collections.sort(themes, new Comparator<Theme>() {
        @Override
        public int compare(Theme t1, Theme t2) {
            return Comparators.AsciiCompare(t1.getName(), t2.getName(), false);
        }

    });

    // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet)
    servletContext.setAttribute("themes", themes);

    _logger.info(themeCount + " templates loaded in .template.xml files");

    return themeCount;

}

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

/**
 * Set the paths for the files that specify how to perform the update
 *//*w  w w. ja va  2  s. co m*/
private void putNonReportingPathsIntoSettings(ServletContext ctx, UpdateSettings settings) {
    settings.setAskUpdatedQueryFile(ctx.getRealPath(askQueryFile()));
    settings.setDiffFile(ctx.getRealPath(diffFile()));
    settings.setSparqlConstructAdditionsDir(ctx.getRealPath(dataDir + "sparqlConstructs/additions"));
    settings.setSparqlConstructDeletionsDir(ctx.getRealPath(dataDir + "sparqlConstructs/deletions"));
    settings.setSuccessAssertionsFile(ctx.getRealPath(successAssertionsFile()));
    settings.setSuccessRDFFormat("N3");
}

From source file:edu.stanford.muse.webapp.JSPHelper.java

/**
 * gets the root dir for the logged in user -- this is the dir.
 * corresponding to /<userkey>/*from   w ww .j  av a2 s.c  om*/
 * inside the actual webapp dir.
 * currently used only for attachments and save messages. the eventual goal
 * is to get
 * rid of this method because it is not secure in a multi-user environment.
 */
public static String getRootDir(HttpServletRequest request) {
    HttpSession session = request.getSession();
    String userKey = (String) getSessionAttribute(session, "userKey");
    ServletContext application = session.getServletContext();
    String documentRootPath = application.getRealPath("/").toString();

    return documentRootPath + File.separatorChar + userKey;
}

From source file:org.jbpm.designer.web.profile.impl.JbpmProfileImpl.java

private void initializeLocalPlugins(ServletContext context) {
    Map<String, IDiagramPlugin> registry = PluginServiceImpl.getLocalPluginsRegistry(context);
    FileInputStream fileStream = null;
    try {//from   w  w w  . j  ava2 s.  com
        try {
            fileStream = new FileInputStream(new StringBuilder(context.getRealPath("/")).append("/")
                    .append(ConfigurationProvider.getInstance().getDesignerContext()).append("profiles")
                    .append("/").append("jbpm.xml").toString());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(fileStream, "UTF-8");
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("profile".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("stencilset".equals(reader.getAttributeLocalName(i))) {
                            _stencilSet = reader.getAttributeValue(i);
                        }
                    }
                } else if ("plugin".equals(reader.getLocalName())) {
                    String name = null;
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("name".equals(reader.getAttributeLocalName(i))) {
                            name = reader.getAttributeValue(i);
                        }
                    }
                    _plugins.put(name, registry.get(name));
                } else if ("localhistory".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("enabled".equals(reader.getAttributeLocalName(i))) {
                            String localhistoryenabled = reader.getAttributeValue(i);
                            if (!isEmpty(localhistoryenabled)) {
                                _localHistoryEnabled = localhistoryenabled;
                            } else {
                                _logger.info("Invalid local history enabled");
                            }
                        }
                        if ("timeout".equals(reader.getAttributeLocalName(i))) {
                            String localhistorytimeout = reader.getAttributeValue(i);
                            if (!isEmpty(localhistorytimeout)) {
                                _localHistoryTimeout = localhistorytimeout;
                            } else {
                                _logger.info("Invalid local history timeout");
                            }
                        }
                    }
                } else if ("storesvgonsave".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("enabled".equals(reader.getAttributeLocalName(i))) {
                            String storesvgonsaveenabled = reader.getAttributeValue(i);
                            if (!isEmpty(storesvgonsaveenabled)) {
                                _storeSVGonSaveOption = storesvgonsaveenabled;
                            } else {
                                _logger.info("Invalid store svg on save enabled");
                            }
                        }
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        _logger.error(e.getMessage(), e);
        throw new RuntimeException(e); // stop initialization
    } finally {
        if (fileStream != null) {
            try {
                fileStream.close();
            } catch (IOException e) {
            }
        }
        ;
    }
}