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.kuali.ext.mm.web.listener.StandaloneInitializeListener.java

protected String findBasePath(ServletContext servletContext) {
    String realPath = servletContext.getRealPath("/");
    // if cannot obtain real path (because, e.g., deployed as WAR
    // try a reasonable guess
    if (realPath == null) {
        if (System.getProperty(CATALINA_BASE) != null) {
            realPath = System.getProperty(CATALINA_BASE);
        } else {//from   w ww.  j  a va  2  s  .  c o  m
            realPath = ".";
        }
    }
    String basePath = new File(realPath).getAbsolutePath();
    // append a trailing path separator to make relatives paths work in conjunction
    // with empty ("current working directory") basePath
    if (basePath.length() > 0 && !basePath.endsWith(File.separator)) {
        basePath += File.separator;
    }
    return basePath;
}

From source file:de.xwic.sandbox.server.ServletLifecycleListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    HibernateDAOProvider hbnDP = new HibernateDAOProvider();

    DAOFactory factory = CommonConfiguration.createCommonDaoFactory(hbnDP);

    DAOSystem.setDAOFactory(factory);/*from   w  w w . jav  a 2  s  .c  o m*/
    DAOSystem.setSecurityManager(new ServerSecurityManager());
    DAOSystem.setUseCaseService(new DefaultUseCaseService(hbnDP));
    DAOSystem.setFileHandler(new HbnFileOracleFixDAO());

    SandboxModelConfig.register(factory);
    StartModelConfig.register(factory);

    DemoAppModelConfig.register(factory);

    final ServletContext context = event.getServletContext();
    SandboxModelConfig.setWebRootDirectory(new File(context.getRealPath("/")));

    final String rootPath = context.getRealPath("");

    final File path = new File(rootPath + "/config");
    Setup setup;
    try {
        setup = XmlConfigLoader.loadSetup(path.toURI().toURL());
    } catch (Exception e) {
        log.error("Error loading product configuration", e);
        throw new RuntimeException("Error loading product configuration: " + e, e);
    }
    ConfigurationManager.setSetup(setup);

    if (!HibernateUtil.isInitialized()) {
        Configuration configuration = new Configuration();
        configuration.configure(); // load configuration settings from hbm file.
        // load properties
        Properties prop = new Properties();
        InputStream in = context.getResourceAsStream("WEB-INF/hibernate.properties");
        if (in == null) {
            in = context.getResourceAsStream("/WEB-INF/hibernate.properties");
        }
        if (in != null) {
            try {
                prop.load(in);
                configuration.setProperties(prop);
            } catch (IOException e) {
                log.error("Error loading hibernate.properties. Skipping this step! : " + e);
            }
        }
        HibernateUtil.initialize(configuration);
    }

    File prefStorePath = new File(new File(rootPath), "WEB-INF/prefstore");
    if (!prefStorePath.exists() && !prefStorePath.mkdirs()) {
        throw new IllegalStateException("Error initializing preference store: can not create directory "
                + prefStorePath.getAbsolutePath());
    }
    Platform.initialize(new StorageProvider(prefStorePath), new UserContextPreferenceProvider());

}

From source file:ro.nextreports.server.web.themes.ThemesManager.java

private void generateStyle(String templateFile, String generatedFilePath) {
    InputStream styleTemplateStream = getClass().getResourceAsStream(templateFile);
    InputStream propertiesStream = getClass().getResourceAsStream(getPropertiesFile(theme));
    try {/* w  ww.  j  a va2  s .c o m*/
        String styleTemplate = IOUtils.toString(styleTemplateStream);
        StrSubstitutor sub = new StrSubstitutor(createValues(propertiesStream));
        String resolvedString = sub.replace(styleTemplate);
        ServletContext context = NextServerApplication.get().getServletContext();
        String fileName = context.getRealPath(generatedFilePath);
        //         URI outputURI = new URI(("file:///"+ URIUtil.encodePath(fileName)));                      
        //         File styleFile = new File(outputURI);
        File styleFile = new File(fileName);
        FileUtils.writeStringToFile(styleFile, resolvedString);
        LOG.info("Generated style file " + templateFile + " in folder " + styleFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeInputStream(styleTemplateStream);
        closeInputStream(propertiesStream);
    }
}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    relativePath = config.getInitParameter("filepath");
    tempPath = config.getInitParameter("temppath");

    javax.servlet.ServletContext context = getServletContext();

    filePath = context.getRealPath(relativePath);
    tempPath = context.getRealPath(tempPath);
}

From source file:com.log4ic.compressor.servlet.CompressionServlet.java

protected String getRootAbsolutePath(ServletContext context) {
    String prefix = context.getRealPath("/");

    if (StringUtils.isBlank(prefix)) {
        java.net.URL url = this.getClass().getResource("/");
        prefix = url.getFile();//from w ww. j a v  a  2 s  .  co  m
    }
    if (!prefix.endsWith("/")) {
        prefix += "/";
    }
    return prefix;
}

From source file:com.jaspersoft.jasperserver.remote.settings.DateTimeSettingsProvider.java

private File getSettingsFile(String path) {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attr.getRequest();
    ServletContext servletContext = request.getSession().getServletContext();
    String realPath = servletContext.getRealPath(path);

    return new File(realPath);
}

From source file:com.springsecurity.plugin.util.ImageResizer.java

public File createFile(MultipartFile file, ServletContext context, String fileName) {
    try {//from ww  w .  j a  v  a 2 s  .co m
        byte[] bytes = file.getBytes();
        // Creating the directory to store file
        String rootPath = context.getRealPath("");
        File dir = new File(rootPath + File.separator + MENU_IMG_FOLDER + File.separator + "Temp");
        if (!dir.exists())
            dir.mkdirs();
        String filePath = dir.getAbsolutePath() + File.separator + fileName;
        // Create the file on server
        File serverFile = new File(filePath);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();
        return serverFile;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.cloud.servlet.StaticResourceServletTest.java

@Test
public void testNoSuchFile() throws ServletException, IOException {
    final StaticResourceServlet servlet = Mockito.mock(StaticResourceServlet.class);
    Mockito.doCallRealMethod().when(servlet).doGet(Matchers.any(HttpServletRequest.class),
            Matchers.any(HttpServletResponse.class));
    final ServletContext servletContext = Mockito.mock(ServletContext.class);
    Mockito.when(servletContext.getRealPath("notexisting.css"))
            .thenReturn(new File(rootDirectory, "notexisting.css").getAbsolutePath());
    Mockito.when(servlet.getServletContext()).thenReturn(servletContext);

    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getServletPath()).thenReturn("notexisting.css");
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    servlet.doGet(request, response);/*w  w w.  j av  a2 s  .  c  o m*/
    Mockito.verify(response).setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:nl.b3p.viewer.components.ComponentRegistry.java

private File resolvePath(ServletContext sc, String p) {
    File path = new File(sc.getRealPath(p));
    log.debug(String.format("Real path for \"%s\": %s", p, path));

    if (!path.exists() || !path.canRead()) {
        log.info(String.format("Cannot load component metadata from non-existing or unreadable paths \"%s\"."
                + "trying as non-virtual path.", path));
        path = new File(p);
    }//  w  ww.  j  ava2s. c  o  m

    if (!path.exists() || !path.canRead()) {
        log.error(String.format("Cannot load component metadata from non-existing or unreadable paths \"%s\"",
                path));
        return null;
    }
    return path;
}

From source file:com.cloud.servlet.StaticResourceServletTest.java

private HttpServletResponse doGetTest(final String uri, final Map<String, String> headers)
        throws ServletException, IOException {
    final StaticResourceServlet servlet = Mockito.mock(StaticResourceServlet.class);
    Mockito.doCallRealMethod().when(servlet).doGet(Matchers.any(HttpServletRequest.class),
            Matchers.any(HttpServletResponse.class));
    final ServletContext servletContext = Mockito.mock(ServletContext.class);
    Mockito.when(servletContext.getRealPath(uri)).thenReturn(new File(rootDirectory, uri).getAbsolutePath());
    Mockito.when(servlet.getServletContext()).thenReturn(servletContext);

    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getServletPath()).thenReturn(uri);
    Mockito.when(request.getHeader(Matchers.anyString())).thenAnswer(new Answer<String>() {

        @Override/*from www . ja va 2s.com*/
        public String answer(final InvocationOnMock invocation) throws Throwable {
            return headers.get(invocation.getArguments()[0]);
        }
    });
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    final ServletOutputStream responseBody = Mockito.mock(ServletOutputStream.class);
    Mockito.when(response.getOutputStream()).thenReturn(responseBody);
    servlet.doGet(request, response);
    return response;
}