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.restcomm.sbc.Bootstrapper.java

@Override
public void init(final ServletConfig config) throws ServletException {
    final ServletContext context = config.getServletContext();
    final String path = context.getRealPath("WEB-INF/conf/sbc.xml");
    // Initialize the configuration interpolator.
    final ConfigurationStringLookup strings = new ConfigurationStringLookup();
    strings.addProperty("home", home(config));
    strings.addProperty("uri", uri(config));
    ConfigurationInterpolator.registerGlobalLookup("sbc", strings);
    // Load the RestComm configuration file.
    Configuration xml = null;//from w w  w  . j  a v  a2 s  . co m
    try {
        xml = new XMLConfiguration(path);
    } catch (final ConfigurationException exception) {
        logger.error(exception);
    }
    xml.setProperty("runtime-settings.home-directory", home(config));
    xml.setProperty("runtime-settings.root-uri", uri(config));
    context.setAttribute(Configuration.class.getName(), xml);
    // Initialize global dependencies.
    final ClassLoader loader = getClass().getClassLoader();
    // Create the actor system.
    //final Config settings = ConfigFactory.load();
    ConfigFactory.load();
    // Create the storage system.
    DaoManager storage = null;
    try {
        storage = storage(xml, loader);
    } catch (final ObjectInstantiationException exception) {
        throw new ServletException(exception);
    }

    context.setAttribute(DaoManager.class.getName(), storage);
    ShiroResources.getInstance().set(DaoManager.class, storage);
    ShiroResources.getInstance().set(Configuration.class, xml.subset("runtime-settings"));
    // Create high-level restcomm configuration
    RestcommConfiguration.createOnce(xml);
    // Initialize identityContext
    IdentityContext identityContext = new IdentityContext(xml);
    context.setAttribute(IdentityContext.class.getName(), identityContext);

    logger.info("Extern IP:" + xml.getString("runtime-settings.external-ip"));

    Version.printVersion();

}

From source file:com.orchestra.portale.controller.UserEditController.java

@RequestMapping(value = "userEditProfile", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ModelAndView updateUser(HttpServletRequest request, @ModelAttribute("SpringWeb") User user,
        MultipartFile avatar) {//from www  .j  a v  a  2 s.  c  o m
    ModelAndView model = new ModelAndView("userInfo");
    User olduser = pm.findUserByUsername(user.getUsername());
    user.setId(olduser.getId());

    if (user.getPassword() == null || user.getPassword().equals("")) {
        user.setPassword(olduser.getPassword());
    } else {
        user.setPassword(crypt(user.getPassword()));
    }

    pm.saveUser(user);

    if (avatar.getSize() > 0) {

        User user2 = pm.findUserByUsername(user.getUsername());
        MultipartFile file = avatar;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
                    + File.separator + user2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "avatar.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {

        }

    }
    model.addObject("user", user);
    HttpSession session = request.getSession();
    ServletContext sc = session.getServletContext();
    File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
            + File.separator + user.getId() + File.separator + "avatar.jpg");
    if (dir.exists()) {
        model.addObject("avatar", "./dist/user/img/" + user.getId() + "/avatar.jpg");
    } else {
        model.addObject("avatar", "./dist/img/default_avatar.png");
    }
    return model;
}

From source file:psiprobe.controllers.apps.ViewXmlConfController.java

@Override
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (displayTarget == null) {
        throw new RuntimeException("Display target is not set for " + getClass().getName());
    }//w  w  w  .j  av a 2  s .c  o m

    String xmlPath;
    File xmlFile = null;
    ModelAndView mv = new ModelAndView(getViewName());

    if (TARGET_WEB_XML.equals(displayTarget)) {
        ServletContext sctx = context.getServletContext();
        xmlPath = sctx.getRealPath("/WEB-INF/web.xml");
        xmlFile = new File(xmlPath);
        mv.addObject("fileDesc",
                getMessageSourceAccessor().getMessage("probe.src.app.viewxmlconf.webxml.desc"));
    } else if (TARGET_CONTEXT_XML.equals(displayTarget)) {
        xmlFile = getContainerWrapper().getTomcatContainer().getConfigFile(context);
        if (xmlFile != null) {
            xmlPath = xmlFile.getPath();
        } else {
            xmlPath = null;
        }
        mv.addObject("fileDesc",
                getMessageSourceAccessor().getMessage("probe.src.app.viewxmlconf.contextxml.desc"));
    } else {
        throw new RuntimeException("Unknown display target " + getDisplayTarget());
    }

    mv.addObject("displayTarget", displayTarget);
    mv.addObject("downloadUrl", downloadUrl);

    if (xmlFile != null) {
        mv.addObject("fileName", xmlFile.getName());
        if (xmlFile.exists()) {
            try (FileInputStream fis = new FileInputStream(xmlFile)) {
                String encoding = System.getProperty("file.encoding");
                mv.addObject("content", Utils.highlightStream("web.xml", fis, "xml",
                        encoding == null ? "ISO-8859-1" : encoding));
            }
        } else {
            logger.debug("File {} of {} application does not exists.", xmlPath, contextName);
        }
    } else {
        logger.debug("Cannot determine path to {} file of {} application.", getDisplayTarget(), contextName);
    }

    return mv;
}

From source file:com.liusoft.dlog4j.servlet.DLOG_ActionServlet.java

/**
 * Globals.WEBAPP_PATH??access??????/*from w  w  w.j a va2  s .  com*/
 */
public void init() throws ServletException {
    ServletContext context = getServletContext();
    if (Globals.WEBAPP_PATH == null)
        Globals.WEBAPP_PATH = context.getRealPath("");
    //?
    try {
        DLOGSecurityManager.init(context);
    } catch (IOException e) {
        throw new ServletException(e);
    }
    //???
    try {
        DLOGUserManager.init(context);
    } catch (Exception e) {
        throw new ServletException(e);
    }
    //Struts?
    super.init();

    encoding = getInitParameter("encoding");
    if (encoding == null)
        encoding = Globals.ENC_UTF_8;
}

From source file:com.athena.sqs.MessageDispatchListener.java

public void contextInitialized(ServletContextEvent sce) {
    ServletContext servletContext = sce.getServletContext();
    sqsConfigLocation = servletContext.getInitParameter("sqsConfigLocation");

    String realPath = servletContext.getRealPath(sqsConfigLocation);
    if (logger.isDebugEnabled()) {
        logger.debug("****************** SQS Config ******************");
        logger.debug("LOCATION : " + sqsConfigLocation);
        logger.debug("REAL LOCATION : " + realPath);
        logger.debug("************************************************");
    }/* w w w .j a v a2  s .  co  m*/

    ApplicationContext applicationContext = (ApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    // TODO : You can load your own application config here
}

From source file:org.bee.tl.ext.spring.BeetlGroupUtilConfiguration.java

public void setServletContext(ServletContext sc) {

    webPath = sc.getRealPath("/");
    root = webPath + root;

}

From source file:org.nuxeo.ecm.platform.thumbnail.factories.ThumbnailDocumentFactory.java

protected Blob getDefaultThumbnail(DocumentModel doc) {
    if (doc == null) {
        return null;
    }/*from ww  w  .  j a va2  s. c om*/
    TypeInfo docType = doc.getAdapter(TypeInfo.class);
    String iconPath = docType.getBigIcon();
    if (iconPath == null) {
        iconPath = docType.getIcon();
    }
    if (iconPath == null) {
        return null;
    }

    ServletContext servletContext = ServletHelper.getServletContext();
    String path = servletContext.getRealPath(iconPath);
    if (path == null) {
        return null;
    }

    try {
        File iconFile = new File(path);
        if (iconFile.exists()) {
            String mimeType = servletContext.getMimeType(path);
            if (mimeType == null) {
                MimetypeRegistry mimetypeRegistry = Framework.getService(MimetypeRegistry.class);
                mimeType = mimetypeRegistry.getMimetypeFromFilename(iconPath);
            }
            return Blobs.createBlob(iconFile, mimeType);
        }
    } catch (IOException e) {
        log.warn(String.format("Could not fetch the thumbnail blob from icon path '%s'", iconPath), e);
    }

    return null;
}

From source file:codes.thischwa.c5c.requestcycle.impl.GlobalFilemanagerConfig.java

private void loadConfigFile(ServletContext context) throws RuntimeException {
    InputStream in = null;/* w w w .  ja va2  s.co m*/

    try {
        File fmScriptDir = new File(context.getRealPath(PropertiesLoader.getFilemanagerPath()), "scripts");

        // defined: filemanager/scripts/filemanager.config.js
        File configFile = new File(fmScriptDir, BASE_FILE_NAME);
        if (configFile.exists()) {
            logger.info("Defined userConfig file found.");
            in = new BufferedInputStream(new FileInputStream(configFile));
        }

        // defined: filemanager/scripts/filemanager.config.js.default
        configFile = new File(fmScriptDir, BASE_FILE_NAME + ".default");
        if (configFile.exists()) {
            logger.info("Defined filemanagers default config file found.");
            in = new BufferedInputStream(new FileInputStream(configFile));
        }

        // load the object
        ObjectMapper mapper = new ObjectMapper();
        userConfig = mapper.readValue(in, FilemanagerConfig.class);
    } catch (Exception e) {
        logger.error("Error while loading the config file!", e);
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.accada.epcis.repository.query.QueryInitServlet.java

/**
 * Loads the application property file and populates a java.util.Properties
 * instance./*from   w ww.  ja va  2 s  .c om*/
 * 
 * @param servletConfig
 *            The ServletConfig used to locate the application property
 *            file.
 */
private void loadApplicationProperties(ServletConfig servletConfig) {
    properties = new Properties();

    // read application.properties from classpath
    String path = "/";
    String appConfigFile = "application.properties";
    InputStream is = QueryInitServlet.class.getResourceAsStream(path + appConfigFile);

    try {
        if (is == null) {
            // read properties from file specified in servlet context
            ServletContext ctx = servletConfig.getServletContext();
            path = ctx.getRealPath("/");
            appConfigFile = ctx.getInitParameter(APP_CONFIG_LOCATION);
            is = new FileInputStream(path + appConfigFile);
        }
        properties.load(is);
        is.close();
        LOG.info("Loaded application properties from " + path + appConfigFile);
    } catch (IOException e) {
        LOG.error("Unable to load application properties from " + path + appConfigFile, e);
    }
}

From source file:org.rhq.enterprise.gui.common.upload.UploadRenderer.java

public void decode(FacesContext context, UIComponent component) {
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    FileItem item = (FileItem) request.getAttribute(clientId);

    Object newValue;/*from  ww w  . j  a  v  a 2  s  .  com*/
    ValueExpression valueExpression = component.getValueExpression("value");
    if (valueExpression != null) {
        Class valueType = valueExpression.getType(context.getELContext());
        if (valueType == byte[].class) {
            newValue = item.get();
        } else if (valueType == InputStream.class) {
            try {
                newValue = item.getInputStream();
            } catch (IOException ex) {
                throw new FacesException(ex);
            }
        } else {
            String encoding = request.getCharacterEncoding();
            if (encoding != null) {
                try {
                    newValue = item.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    newValue = item.getString();
                }
            } else {
                newValue = item.getString();
            }
        }

        ((EditableValueHolder) component).setSubmittedValue(newValue);
        ((EditableValueHolder) component).setValid(true);
    }

    Object target = component.getAttributes().get("target");

    if (target != null) {
        File file;
        if (target instanceof File) {
            file = (File) target;
        } else {
            ServletContext servletContext = (ServletContext) external.getContext();
            String realPath = servletContext.getRealPath(target.toString());
            file = new File(realPath);
        }

        try {
            item.write(file);
        } catch (Exception ex) {
            throw new FacesException(ex);
        }
    }
}