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.hzc.framework.ssh.controller.WebUtil.java

/**
 * jsonp?/*  w w  w  .  ja v  a  2  s.  co m*/
 *  + ?
 *
 * @param path
 * @param ufc
 * @return
 * @throws Exception
 */
public static <T> T uploadMultiAndProgress(String path, Class<T> c, UploadFileNewCall ufc,
        final ProgressListener pl) throws RuntimeException {
    try {
        HttpServletRequest request = getReq();
        //            final HttpSession session = getSession();
        ServletContext servletContext = getServletContext();
        File file = new File(servletContext.getRealPath(path));
        if (!file.exists())
            file.mkdir();

        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("UTF-8");
        upload.setProgressListener(pl);
        List<FileItem> fileItems = upload.parseRequest(request);

        T obj = c.newInstance();
        Field[] declaredFields = c.getDeclaredFields();
        for (FileItem item : fileItems) {
            if (!item.isFormField()) {

                String name = item.getName();
                String type = item.getContentType();
                if (StringUtils.isNotBlank(name)) {
                    File f = new File(file + File.separator + name);
                    item.write(f);
                    ufc.file(obj, f, name, name, item.getSize(), type); // ????
                }
            } else {

                String name = item.getFieldName();
                // ??,??
                for (Field field : declaredFields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    if (name.equals(fieldName)) {
                        String value = item.getString("UTF-8");
                        if (null == value) {
                            continue;
                        }
                        Class<?> type = field.getType();
                        if (type == Long.class) {
                            field.set(obj, Long.parseLong(value));
                        } else if (type == String.class) {
                            field.set(obj, value);
                        } else if (type == Byte.class) {
                            field.set(obj, Byte.parseByte(value));
                        } else if (type == Integer.class) {
                            field.set(obj, Integer.parseInt(value));
                        } else if (type == Character.class) {
                            field.set(obj, value.charAt(0));
                        } else if (type == Boolean.class) {
                            field.set(obj, Boolean.parseBoolean(value));
                        } else if (type == Double.class) {
                            field.set(obj, Double.parseDouble(value));
                        } else if (type == Float.class) {
                            field.set(obj, Float.parseFloat(value));
                        }
                    }
                }
            }
        }
        return obj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.codehaus.plexus.redback.struts2.interceptor.SecureActionInterceptor.java

private void executeReferrerSecurityCheck() {
    String referrer = ServletActionContext.getRequest().getHeader(HTTP_HEADER_REFERER);

    logger.debug("HTTP Referer header: {}", referrer);

    String[] tokens = StringUtils.splitPreserveAllTokens(referrer, "/", 3);

    if (tokens != null) {
        String path;//from   w w  w . j a  v  a 2s.  c  o m
        if (tokens.length < 3) {
            path = referrer;
        } else {
            path = tokens[tokens.length - 1];
        }

        logger.debug("Calculated virtual path: {}", path);

        ServletContext servletContext = ServletActionContext.getServletContext();

        String realPath = servletContext.getRealPath(path);

        if (StringUtils.isNotEmpty(realPath)) {
            // on windows realPath can return full path c:\\bla\\bla\....
            // so transforming \\ to /
            if (SystemUtils.IS_OS_WINDOWS) {
                realPath = StringUtils.replace(realPath, "\\", "/");
            }
            if (!realPath.endsWith(path)) {
                String errorMsg = "Failed referrer security check: Request did not come from the same server. "
                        + "Detected HTTP Referer header is '" + referrer + "'.";
                logger.error(errorMsg);
                throw new RuntimeException(errorMsg);
            } else {
                logger.debug("HTTP Referer header path found in server.");
            }
        }
    } else {
        logger.warn("HTTP Referer header is null.");
    }
}

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

@RequestMapping(value = "/savedpage", method = RequestMethod.POST)
public ModelAndView savedpage(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam("cover") MultipartFile cover, @RequestParam("file") MultipartFile[] files)
        throws InterruptedException {
    ModelAndView model = new ModelAndView("okpageadmin");

    DeepeningPage dp = new DeepeningPage();
    dp.setName(params.get("name"));
    System.out.println(params.get("name"));

    int i = 1;//  ww w  .j  av  a2 s  .co m
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        i = i + 1;
    }
    dp.setCategories(categories);

    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();

    //componente cover
    if (!cover.isEmpty()) {
        CoverImgComponent coverimg = new CoverImgComponent();
        coverimg.setLink("cover.jpg");
        listComponent.add(coverimg);
    }
    //componente galleria immagini
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    if (files.length > 0) {
        ImgGalleryComponent img_gallery = new ImgGalleryComponent();

        i = 0;
        while (i < files.length) {
            ImgGallery img = new ImgGallery();

            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("credit" + (i + 1))) {
                img.setCredit(params.get("credit" + (i + 1)));
            }

            i = i + 1;
            links.add(img);
        }
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {
        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    dp.setComponents(listComponent);

    pm.saveDeepeningPage(dp);

    DeepeningPage poi2 = pm.findDeepeningPageByName(dp.getName());

    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        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 + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {

            model.addObject("mess", "ERRORE!");
            return model;
        }
    }
    MultipartFile file = cover;

    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 + "dpage" + File.separator + "img"
                + File.separator + poi2.getId());
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

    } catch (Exception e) {

    }
    model.addObject("mess", "PAGINA INSERITA CORRETTAMENTE!");
    return model;
}

From source file:main.server.DemoPageProvider.java

public DemoPageProvider(ServletContext sc) {
    pageDir = new File(System.getProperty("user.dir", ""), "war/WEB-INF/pages");
    if (!pageDir.isDirectory()) {
        pageDir = new File(sc.getRealPath("WEB-INF/pages"));
        useSession = true;//  ww  w.j a va  2 s. co m
        log.info("Saving pages to session: " + pageDir);
    } else {
        log.info("Loading and saving pages from " + pageDir);
    }

    // discover our classes (in a real app they would be Spring beans or
    // something similar)
    ClassFinder cf = new ClassFinder(sc, "main");

    // find all PortletFactory's and alias them so fully qualified class
    // names don't end up in the XML
    for (Class cls : cf.findClasses("$Factory", PortletFactory.class)) {
        log.info("Portlet factory: " + cls.getName());
        xmlIO.alias(cls);
    }

    // create an instance of each DataProvider
    for (Class cls : cf.findClasses("DataProvider", WidgetDataProvider.class)) {
        int mod = cls.getModifiers();
        if (!Modifier.isAbstract(mod) && !Modifier.isInterface(mod)) {
            log.info("Data provider: " + cls.getName());
            try {
                add((WidgetDataProvider) cls.newInstance());
            } catch (Exception e) {
                log.error(e, e);
            }
        }
    }
}

From source file:de.betterform.agent.web.WebFactory.java

/**
 * get the absolute file path for a given relative path in the webapp. Handles some differences in server behavior
 * with the execution of context.getRealPath on various servers/operating systems
 *
 * @param path    a path relative to the context root of the webapp
 * @param context the servletcontext/*from   w ww. j ava 2s  .  c om*/
 * @return the absolute file path for given relative webapp path
 */
public static String getRealPath(String path, ServletContext context) throws XFormsConfigException {
    if (path == null) {
        path = "/";
    }
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    try {
        URI resourceURI = null;
        String computedRealPath = null;
        URL rootURL = Thread.currentThread().getContextClassLoader().getResource("/");
        URL resourceURL = context.getResource(path);

        if (rootURL != null) {
            resourceURI = rootURL.toURI();
        }

        if (resourceURI != null && resourceURI.getScheme().equalsIgnoreCase("file")) {
            String resourcePath = rootURL.getPath();
            String rootPath = new File(resourcePath).getParentFile().getParent();
            computedRealPath = new File(rootPath, path).getAbsolutePath();
        } else if (resourceURL != null) {
            computedRealPath = new File(resourceURL.toExternalForm(), path).getAbsolutePath();
        } else {
            String resourcePath = context.getRealPath("/");
            computedRealPath = new File(resourcePath, path).getAbsolutePath();
        }
        return java.net.URLDecoder.decode(computedRealPath, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        throw new XFormsConfigException("path could not be resolved: " + path, e);
    } catch (URISyntaxException e) {
        throw new XFormsConfigException("path could not be resolved: " + path, e);
    } catch (MalformedURLException e) {
        throw new XFormsConfigException("path could not be resolved: " + path, e);
    }
}

From source file:info.magnolia.cms.beans.config.ConfigLoader.java

/**
 * Initialize a ConfigLoader instance. All the supplied parameters will be set in
 * <code>info.magnolia.cms.beans.runtime.SystemProperty</code>
 * @param context ServletContext/*from  w w w  .j av  a2s  .  c  om*/
 * @param config contains initialization parameters
 * @see SystemProperty
 */
public ConfigLoader(ServletContext context, Map config) {

    String rootDir = context.getRealPath(StringUtils.EMPTY);

    if (log.isInfoEnabled()) {
        log.info("Assuming paths relative to {}", rootDir); //$NON-NLS-1$
    }
    SystemProperty.setProperty(SystemProperty.MAGNOLIA_APP_ROOTDIR, rootDir);

    // load mgnl-beans.properties first
    InputStream mgnlbeansStream = getClass().getResourceAsStream(MGNL_BEANS_PROPERTIES);
    if (mgnlbeansStream != null) {
        Properties mgnlbeans = new Properties();
        try {
            mgnlbeans.load(mgnlbeansStream);
        } catch (IOException e) {
            log.error("Unable to load {} due to an IOException: {}", MGNL_BEANS_PROPERTIES, e.getMessage());
        } finally {
            IOUtils.closeQuietly(mgnlbeansStream);
        }

        for (Iterator iter = mgnlbeans.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            SystemProperty.setProperty(key, mgnlbeans.getProperty(key));
        }

    } else {
        log.warn(
                "{} not found in the classpath. Check that all the needed implementation classes are defined in your custom magnolia.properties file.",
                MGNL_BEANS_PROPERTIES);
    }

    Iterator it = config.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry param = (Map.Entry) it.next();
        SystemProperty.setProperty((String) param.getKey(), (String) param.getValue());
    }

    if (StringUtils.isEmpty(System.getProperty("java.security.auth.login.config"))) { //$NON-NLS-1$
        try {
            System.setProperty("java.security.auth.login.config", Path //$NON-NLS-1$
                    .getAbsoluteFileSystemPath("WEB-INF/config/jaas.config")); //$NON-NLS-1$
        } catch (SecurityException se) {
            log.error("Failed to set java.security.auth.login.config, check application server settings"); //$NON-NLS-1$
            log.error(se.getMessage(), se);
            log.info("Aborting startup");
            return;
        }
    } else {
        if (log.isInfoEnabled()) {
            log.info("JAAS config file set by parent container or some other application"); //$NON-NLS-1$
            log.info("Config in use " + System.getProperty("java.security.auth.login.config")); //$NON-NLS-1$ //$NON-NLS-2$
            log.info(
                    "Please make sure JAAS config has all necessary modules (refer config/jaas.config) configured"); //$NON-NLS-1$
        }
    }

    this.load(context);
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

private static <T> T pbRecurrence(Class<T> c, String prefix) throws RuntimeException {
    try {//  w w  w . java2 s  . co  m
        HttpServletRequest request = ActionContext.getReq();
        T newInstance = c.newInstance();
        Field[] declaredFields = c.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            String name = field.getName();
            String key = "".equals(prefix) ? name : prefix + "." + name;
            String value = request.getParameter(key);

            Class<?> type = field.getType();
            if (type.isArray()) {//?string   file
                Class<?> componentType = type.getComponentType();
                if (componentType == String.class) {
                    String[] values = request.getParameterValues(name);
                    //                    if (null == value || "".equals(value)) continue;
                    //                    String[] split = value.split(",");
                    field.set(newInstance, values);
                } else if (componentType == File.class) {
                    ServletContext servletContext = getServletContext();
                    File file = new File(servletContext.getRealPath("upload"));
                    if (!file.exists())
                        file.mkdir();
                    MultipartRequest multi = new MultipartRequest(request, file.getAbsolutePath(),
                            1024 * 1024 * 1024, "UTF-8", new DefaultFileRenamePolicy());
                    Enumeration files = multi.getFileNames();
                    List<File> fileList = new ArrayList<File>();
                    if (files.hasMoreElements()) {
                        File f = multi.getFile((String) files.nextElement());
                        fileList.add(f);
                    }
                    field.set(newInstance, fileList.toArray(new File[] {}));
                }

            }
            // ? 
            validation(field, name, value);
            if (null == value) {
                continue;
            }
            if (type == Long.class) {
                field.set(newInstance, Long.parseLong(value));
            } else if (type == String.class) {
                field.set(newInstance, value);
            } else if (type == Byte.class) {
                field.set(newInstance, Byte.parseByte(value));
            } else if (type == Integer.class) {
                field.set(newInstance, Integer.parseInt(value));
            } else if (type == Character.class) {
                field.set(newInstance, value.charAt(0));
            } else if (type == Boolean.class) {
                field.set(newInstance, Boolean.parseBoolean(value));
            } else if (type == Double.class) {
                field.set(newInstance, Double.parseDouble(value));
            } else if (type == Float.class) {
                field.set(newInstance, Float.parseFloat(value));
            } else if (type == Date.class) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                field.set(newInstance, sdf.parse(value));
            } else { // 
                Object obj = pbRecurrence(field.getType(), name);// 
                field.set(newInstance, obj);
            }
        }
        return newInstance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netspective.sparx.theme.basic.StandardTemplateNavigationSkin.java

public boolean templateAvailable(ServletContext servletContext, String name) throws IOException {
    // First try to open as plain file (to bypass servlet container resource caches).
    String realPath = servletContext.getRealPath(name);
    if (realPath != null) {
        File file = new File(realPath);
        if (!file.isFile())
            return false;

        if (file.canRead())
            return true;
    }/*from   ww w.  j  a v a  2s .  com*/

    // If it fails, try to open it with servletContext.getResource.
    URL url = null;
    try {
        url = servletContext.getResource(name);
    } catch (MalformedURLException e) {
        return false;
    }
    return url == null ? false : true;
}

From source file:com.vangent.hieos.DocViewer.server.framework.ServletUtilMixin.java

/**
 * //from  w w  w  .jav a 2 s . c  o  m
 * @param servletContext
 */
public void init(ServletContext servletContext) {
    this.servletContext = servletContext;
    // FIXME: ? This may happen more than once, but likely OK since
    // all servlets share the same "xconfig.xml".
    String xConfigRealPath = servletContext.getRealPath(ServletUtilMixin.XCONFIG_FILE);
    System.out.println("Real Path: " + xConfigRealPath);
    XConfig.setConfigLocation(xConfigRealPath);
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 * ?????bean<br/>/*from  w  w  w. ja v  a 2 s . c  o m*/
 * ???
 *
 * @param <T>
 * @throws ValidationException
 */
public static <T> T packBean(Class<T> c) throws RuntimeException {
    try {
        HttpServletRequest request = ActionContext.getReq();
        T newInstance = c.newInstance();
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            String value = request.getParameter(name);

            Class<?> type = field.getType();
            if (type.isArray()) {//?string   file
                Class<?> componentType = type.getComponentType();
                if (componentType == String.class) {
                    String[] values = request.getParameterValues(name);
                    //                    if (null == value || "".equals(value)) continue;
                    //                    String[] split = value.split(",");
                    field.set(newInstance, values);
                } else if (componentType == File.class) {
                    ServletContext servletContext = getServletContext();
                    File file = new File(servletContext.getRealPath("upload"));
                    if (!file.exists())
                        file.mkdir();
                    MultipartRequest multi = new MultipartRequest(request, file.getAbsolutePath(),
                            MAX_POST_SIZE, "UTF-8", new DefaultFileRenamePolicy());
                    Enumeration files = multi.getFileNames();
                    List<File> fileList = new ArrayList<File>();
                    if (files.hasMoreElements()) {
                        File f = multi.getFile((String) files.nextElement());
                        fileList.add(f);
                    }
                    field.set(newInstance, fileList.toArray(new File[] {}));
                }

            }
            //            else if (type == File.class) {//?
            //                ServletContext servletContext = getServletContext();
            //                File file = new File(servletContext.getRealPath("upload"));
            //                if (!file.exists())
            //                    file.mkdir();
            //                MultipartRequest multi =
            //                        new MultipartRequest(request, file.getAbsolutePath(), 10 * 1024 * 1024, "UTF-8", new DefaultFileRenamePolicy());
            //                Enumeration files = multi.getFileNames();
            //                if (files.hasMoreElements()) {
            //                    field.set(newInstance, multi.getFile((String) files.nextElement()));
            //                }
            //            }
            // ? 
            validation(field, name, value);
            if (null == value || "".equals(value.trim())) {
                continue;
            }
            if (type == Long.class) {
                field.set(newInstance, Long.parseLong(value));
            } else if (type == String.class) {
                field.set(newInstance, value);
            } else if (type == Byte.class) {
                field.set(newInstance, Byte.parseByte(value));
            } else if (type == Integer.class) {
                field.set(newInstance, Integer.parseInt(value));
            } else if (type == Character.class) {
                field.set(newInstance, value.charAt(0));
            } else if (type == Boolean.class) {
                field.set(newInstance, Boolean.parseBoolean(value));
            } else if (type == Double.class) {
                field.set(newInstance, Double.parseDouble(value));
            } else if (type == Float.class) {
                field.set(newInstance, Float.parseFloat(value));
            } else if (type == Date.class) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                field.set(newInstance, sdf.parse(value));
            }
        }
        return newInstance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}