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.rhq.helpers.rtfilter.util.ServletUtility.java

private static String getContextRootFromWarFileName(ServletContext servletContext) {
    String ctxName;/* w ww . j a  v a  2s  .  com*/
    ctxName = servletContext.getRealPath("/");
    if (null == ctxName) {
        return null;
    }
    if (ctxName.endsWith(SEPARATOR)) {
        ctxName = ctxName.substring(0, ctxName.length() - 1);
    }

    // the war name is from last '/' to end (sans .war, if it exists)
    ctxName = ctxName.substring(ctxName.lastIndexOf(SEPARATOR),
            ctxName.length() - (ctxName.endsWith(".war") ? 4 : 0));

    // Now remove crap that might be there
    if (ctxName.endsWith("-exp")) {
        ctxName = ctxName.substring(0, ctxName.length() - 4);
        // TODO jboss sometimes has some strange 5 digits in the name
    }
    return ctxName;
}

From source file:org.wso2.carbon.device.mgt.extensions.feature.mgt.util.AnnotationProcessor.java

/**
 * Find the URL pointing to "/WEB-INF/classes"  This method may not work in conjunction with IteratorFactory
 * if your servlet container does not extract the /WEB-INF/classes into a real file-based directory
 *
 * @param servletContext//from  w ww. j  a  va 2 s.co m
 * @return null if cannot determin /WEB-INF/classes
 */
public static URL findWebInfClassesPath(ServletContext servletContext) {
    String path = servletContext.getRealPath("/WEB-INF/classes");
    if (path == null)
        return null;
    File fp = new File(path);
    if (fp.exists() == false)
        return null;
    try {
        URI uri = fp.toURI();
        return uri.toURL();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.rhq.helpers.rtfilter.util.ServletUtility.java

/**
 * Try to read the context root from an application.xml file of a EAR archive
 *
 * @param  servletContext/*  w w w. j av  a  2  s  .  c  o  m*/
 *
 * @return context root or null if not found.
 */
private static String getContextRootFromApplicationXml(ServletContext servletContext) {
    String ctxRoot = null;

    String path = servletContext.getRealPath("/");
    if ((null == path) || !path.toLowerCase().contains(EAR_CONTENTS)) {
        return null;
    }

    // get the path to application.xml
    path = path.substring(0, path.lastIndexOf(EAR_CONTENTS) + EAR_CONTENTS.length());
    path += SEPARATOR + "META-INF" + SEPARATOR + "application.xml";
    File file = new File(path);
    if ((file == null) || (!file.canRead())) {
        LOG.debug(path + " is not readable");
        return null;
    }

    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = db.parse(file);
        Element root = doc.getDocumentElement(); // <application>
        NodeList modules = root.getChildNodes(); // <module>
        for (int i = 0; i < modules.getLength(); i++) {
            Node module = modules.item(i);
            NodeList moduleChildren = module.getChildNodes();
            for (int j = 0; j < moduleChildren.getLength(); j++) {
                Node child = moduleChildren.item(j);
                if ((child instanceof Element) && child.getNodeName().equals("web")) {
                    NodeList webChildren = child.getChildNodes();
                    for (int k = 0; k < webChildren.getLength(); k++) {
                        Node webChild = webChildren.item(k);
                        if (webChild.getNodeName().equals("context-root")) {
                            Node textNode = webChild.getFirstChild();
                            if (textNode != null) {
                                ctxRoot = textNode.getNodeValue();
                                break;
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        LOG.debug(e);
        ctxRoot = null;
    }

    LOG.debug("CtxRoot from application.xml: " + ctxRoot);
    return ctxRoot;
}

From source file:com.qualogy.qafe.web.ContextLoader.java

public static String getContextPath(ServletContext servletContext)
        throws MalformedURLException, URISyntaxException {
    // The default way: works on JBoss/Tomcat/Jetty
    String contextPath = servletContext.getRealPath("/WEB-INF/");

    // This is how a weblogic explicitly wants the fetching of resources.
    if (contextPath == null) {
        URL url = servletContext.getResource("/WEB-INF/");
        logger.log(Level.INFO, "Fallback scenario " + url.toString());
        if (url != null) {
            logger.log(Level.INFO, "URL to config file " + url.toString());
            contextPath = url.toURI().toString();
        } else {//from   ww  w  .  ja v a 2 s .  co m
            throw new RuntimeException(
                    "Strange Error: /WEB-INF/ cannot be found. Check the appserver or installation directory.");
        }
    }
    return contextPath;
}

From source file:fll.web.GatherBugReport.java

/**
 * Add the web application and tomcat logs to the zipfile.
 *//*w  w w.  ja  v a2  s  .  co m*/
private static void addLogFiles(final ZipOutputStream zipOut, final ServletContext application)
        throws IOException {

    // get logs from the webapp
    final File fllAppDir = new File(application.getRealPath("/"));
    final File[] webLogs = fllAppDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            return name.startsWith("fllweb.log");
        }
    });
    if (null != webLogs) {
        for (final File f : webLogs) {
            if (f.isFile()) {
                FileInputStream fis = null;
                try {
                    zipOut.putNextEntry(new ZipEntry(f.getName()));
                    fis = new FileInputStream(f);
                    IOUtils.copy(fis, zipOut);
                    fis.close();
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }
    }

    // get tomcat logs
    final File webappsDir = fllAppDir.getParentFile();
    LOGGER.trace("Webapps dir: " + webappsDir.getAbsolutePath());
    final File tomcatDir = webappsDir.getParentFile();
    LOGGER.trace("Tomcat dir: " + tomcatDir.getAbsolutePath());
    final File tomcatLogDir = new File(tomcatDir, "logs");
    LOGGER.trace("tomcat log dir: " + tomcatLogDir.getAbsolutePath());
    final File[] tomcatLogs = tomcatLogDir.listFiles();
    if (null != tomcatLogs) {
        for (final File f : tomcatLogs) {
            if (f.isFile()) {
                FileInputStream fis = null;
                try {
                    zipOut.putNextEntry(new ZipEntry(f.getName()));
                    fis = new FileInputStream(f);
                    IOUtils.copy(fis, zipOut);
                    fis.close();
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }
    }

}

From source file:com.orchestra.portale.externalauth.FbAuthenticationManager.java

public static User fbLoginJs(HttpServletRequest request, HttpServletResponse response,
        UserRepository userRepository) {

    //Get access_token from request
    String access_token = request.getParameter("access_token");
    User user = null;/*from ww w .java  2 s .  c  om*/

    if (StringUtils.isNotEmpty(access_token)) {

        try {

            Boolean validity = FacebookUtils.ifTokenValid(access_token);

            //if token is valid, retrieve userid and email from Facebook
            if (validity) {
                Map<String, String> userId_mail = FacebookUtils.getUserIDMail(access_token);
                String id = userId_mail.get("id");
                String email = userId_mail.get("email");

                try {
                    user = fbUserCheck(id, email, userRepository);
                } catch (UserNotFoundException ioex) {
                    /*Retrieve User Data to Registration*/
                    Map<String, String> userData = FacebookUtils.getUserData(access_token);

                    /*Create User*/
                    com.orchestra.portale.persistence.sql.entities.User new_user = new com.orchestra.portale.persistence.sql.entities.User();
                    new_user.setFbEmail(userData.get("email"));
                    new_user.setFbUser(userData.get("id"));
                    new_user.setUsername(userData.get("email"));
                    new_user.setFirstName(userData.get("firstName"));
                    new_user.setLastName(userData.get("lastName"));
                    new_user.setPassword(new BigInteger(130, new SecureRandom()).toString(32));

                    /*Create Role*/
                    com.orchestra.portale.persistence.sql.entities.Role new_user_role = new com.orchestra.portale.persistence.sql.entities.Role();
                    new_user_role.setRole("ROLE_USER");
                    new_user_role.setUser(new_user);
                    ArrayList<com.orchestra.portale.persistence.sql.entities.Role> new_user_roles = new ArrayList<com.orchestra.portale.persistence.sql.entities.Role>();
                    new_user_roles.add(new_user_role);
                    new_user.setRoles(new_user_roles);

                    /*Save User*/
                    userRepository.save(new_user);

                    //Save user image
                    try {
                        String img_url = userData.get("img");
                        String user_id_img = userRepository.findByUsername(new_user.getUsername()).getId()
                                .toString();

                        HttpSession session = request.getSession();
                        ServletContext sc = session.getServletContext();

                        String destination = sc.getRealPath("/") + "dist" + File.separator + "user"
                                + File.separator + "img" + File.separator + user_id_img + File.separator;

                        NetworkUtils.saveImageFromURL(img_url, destination, "avatar.jpg");

                    } catch (MalformedURLException ex) {
                        throw new FacebookException();
                    } catch (IOException ioexc) {
                        ioexc.getMessage();
                    }

                    /*Create Spring User*/
                    boolean enabled = true;
                    boolean accountNonExpired = true;
                    boolean credentialsNonExpired = true;
                    boolean accountNonLocked = true;

                    user = new User(new_user.getUsername(), new_user.getPassword().toLowerCase(), enabled,
                            accountNonExpired, credentialsNonExpired, accountNonLocked,
                            getAuthorities(new_user.getRoles()));

                }

            }

        } catch (FacebookException ioex) {
            ioex.printStackTrace();
        }

    }

    return user;
}

From source file:com.sifcoapp.report.util.ReportConfigUtil.java

public static void exportToPDFFile(ServletContext context, ExternalContext ec, JasperPrint jasperPrint,
        String fileName) throws FileNotFoundException, IOException {
    String ruta = context.getRealPath("WEB-INF") + "\\" + fileName + ".pdf";
    System.out.println(ruta);/*from   w w  w  .j  a v a2s  . c om*/
    try {
        JasperExportManager.exportReportToPdfFile(jasperPrint, ruta);
        //enviandolo al browser
        ec.responseReset();
        ec.setResponseContentType(ec.getMimeType(ruta));
        //ec.setResponseContentLength(contentLength); 
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".pdf\"");

        InputStream input = new FileInputStream(ruta);
        OutputStream output = ec.getResponseOutputStream();
        IOUtils.copy(input, output);

        System.out.println("Sending to browser...");
    } catch (JRException ex) {
        Logger.getLogger(ReportConfigUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:br.univali.celine.lms.config.LMSConfig.java

public static void buildConfig(ServletContext context) throws Exception {

    if (config != null)
        return;/*from   www.  ja  v  a  2  s .c o m*/

    config = new LMSConfig(context);
    doBuildConfig(context.getRealPath("/") + "/WEB-INF");

}

From source file:com.future.pos.util.SystemInitializer.java

private static String getPathFromContext(ServletContext servletContext, String path) {
    String realPath = servletContext.getRealPath(path);
    if (realPath == null) {
        String hardcodedPath = "/var/lib/openshift/5478455ce0b8cde36400001e/jbossews/future/";
        System.out.println("Hardcoded Path: " + hardcodedPath);
        String[] paths = path.split("/");
        realPath = hardcodedPath + paths[paths.length - 1];
    }//from  www  . j a  v  a2s . c  o m
    System.out.println("Real Path: " + realPath);
    return realPath;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationsDependencyInjector.java

/**
 * This method is used to inject vis dependencies i.e. the vis algorithms that are 
  * being implemented into the vis controller. Modified Dependency Injection pattern is 
  * used here. XML file containing the location of all the vis is saved in accessible folder. 
 * @param servletContext/*from   w ww  . j a va  2 s .co m*/
 * @return
 */
private synchronized static Map<String, VisualizationRequestHandler> initVisualizations(
        ServletContext servletContext) {

    /*
     * A visualization request has already been made causing the visualizationIDsToClass to be
     * initiated & populated with visualization ids to its request handlers.
     * */
    if (visualizationIDsToClass != null) {
        return visualizationIDsToClass;
    }

    String resourcePath = servletContext
            .getRealPath(VisualizationFrameworkConstants.RELATIVE_LOCATION_OF_FM_VISUALIZATIONS_BEAN);

    ApplicationContext context = new ClassPathXmlApplicationContext("file:" + resourcePath);

    BeanFactory factory = context;

    VisualizationInjector visualizationInjector = (VisualizationInjector) factory
            .getBean("visualizationInjector");

    visualizationIDsToClass = visualizationInjector.getVisualizationIDToClass();

    return visualizationIDsToClass;
}