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.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * Gets an absolute path to CKFinder resource folder for which path is calculated from baseURL configuration property.<br>
 * This method has limited capabilities. First it will check is folder should be created in application context. If not it will try to
 * create folder in Tomcat ROOT folder or GlassFish docroot folder. If this fails this method will fall back and try to create folder
 * inside application context (features like gallery may not work in this case as most likely baseURL and baseDir point to different
 * locations).<br>/*from  w  w  w .ja  va 2 s . c  o m*/
 * Finally if nothing worked this method returns {@code null}.
 *
 * @param path relative or absolute path to a CKFinder folder.
 * @return an absolute path to a folder in CKFinder
 * @throws ConnectorException when {@code ServletContext} is {@code null} or path to resource cannot be obtained.
 */
public static String calculatePathFromBaseUrl(String path) throws ConnectorException {
    if (path != null && !path.equals("")) {
        ServletContext sc = ServletContextFactory.getServletContext();
        String tempPath = PathUtils.addSlashToBeginning(path);
        String finalPath;
        if (tempPath.startsWith(sc.getContextPath() + "/")) {
            //Try creating path relative to application context.
            if ((finalPath = sc.getRealPath(tempPath.replace(sc.getContextPath(), ""))) != null) {
                return finalPath;
            } else if ((finalPath = sc.getRealPath(CKFINDER_FOLDER_NAME)) != null) {
                //If above is null, try getting path to direct subfolder in application context.
                finalPath = PathUtils.escape(finalPath);
                return finalPath.substring(0, finalPath.lastIndexOf(CKFINDER_FOLDER_NAME))
                        + tempPath.replace(sc.getContextPath(), "");
            } else {
                finalPath = getClassPath();
                if (finalPath.indexOf(sc.getContextPath()) >= 0) {
                    finalPath = finalPath.substring(0, finalPath.indexOf(sc.getContextPath()));
                    finalPath = finalPath + tempPath;
                    return finalPath;
                } else {
                    finalPath = null;
                }
            }
        } else {
            //Try creating path to ROOT on TC or docroot on GF
            finalPath = getClassPath();

            String tcPath = getTomcatRootPath(sc, finalPath);
            String gfPath = getGlassFishRootPath(sc, finalPath);
            if (!tcPath.equals("")) {
                tempPath = filterRelativePathChars(tempPath);
                finalPath = tcPath + tempPath;
            } else if (!gfPath.equals("")) {
                tempPath = filterRelativePathChars(tempPath);
                finalPath = gfPath + tempPath;
            } else {
                //Fall back and try creating path relative application context
                String realPath = sc.getRealPath(tempPath);
                if (realPath != null) {
                    return realPath;
                } else if (finalPath.indexOf(sc.getContextPath() + "/") >= 0) {
                    finalPath = finalPath.substring(0,
                            finalPath.indexOf(sc.getContextPath()) + sc.getContextPath().length());
                    tempPath = filterRelativePathChars(tempPath);
                    finalPath = finalPath + tempPath;
                } else {
                    finalPath = null;
                }
            }
        }
        return finalPath;
    }
    return null;
}

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

@RequestMapping(value = "/updatedpage", method = RequestMethod.POST)
public ModelAndView updatePoi(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam(value = "file", required = false) MultipartFile[] files,
        @RequestParam(value = "cover", required = false) MultipartFile cover,
        @RequestParam(value = "fileprec", required = false) String[] fileprec,
        @RequestParam(value = "imgdel", required = false) String[] imgdel) throws InterruptedException {

    DeepeningPage poi = pm.findDeepeningPage(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }//w w w.  java  2 s. c  o m
    }
    ModelAndView model = new ModelAndView("okpageadmin");
    model.addObject("mess", "PAGINA MODIFICATA CORRETTAMENTE!");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    poi.setName(params.get("name"));

    int i = 1;
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

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

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 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("newcredit" + (i + 1)))
                img.setCredit(params.get("newcredit" + (i + 1)));
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1)))
                img.setCredit(params.get("credit" + (iximg + 1)));
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        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);
    }
    poi.setComponents(listComponent);

    pm.saveDeepeningPage(poi);

    DeepeningPage poi2 = pm.findDeepeningPageByName(poi.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();
            System.out.println("FILE CREATO IN POSIZIONE:" + serverFile.getAbsolutePath().toString());

        } catch (Exception e) {
            e.printStackTrace();
            return model;
        }
    }
    if (!cover.isEmpty()) {
        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) {
            return model;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE

    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }

    return model;
}

From source file:net.jforum.util.JForumConfig.java

public JForumConfig(ServletContext servletContext, SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
    this.setReloadingStrategy(new FileChangedReloadingStrategy());
    this.setDelimiterParsingDisabled(true);

    try {/*from w  w  w.  j  a  v  a2  s  .  c om*/
        loadProps();
        if (servletContext != null) {
            setProperty(ConfigKeys.APPLICATION_PATH, servletContext.getRealPath(""));
        }
        loadDatabaseProperties();
        normalizeTemplateDirectory();
    } catch (Exception e) {
        throw new ForumException(e);
    }
}

From source file:info.joseluismartin.gtc.admin.MapViewer.java

/**
 * Get a Script from filesystem/*from   w w w. j  av a 2s  .  c o  m*/
 * @param path relative path to context
 * @return String with script context or null on IOExceptions
 */
private String getScript(String path) {
    String script = null;

    ServletContext sc = ((WebApplicationContext) getApplication().getContext()).getHttpSession()
            .getServletContext();
    File file = new File(sc.getRealPath(path));
    try {
        script = FileUtils.readFileToString(file);
    } catch (IOException e) {
        log.error(e);
    }

    return script;
}

From source file:org.zanata.ZanataInit.java

public void initZanata(ServletContext context) throws Exception {
    checkAppServerVersion();//from   w w  w. j a  v a2s .co  m
    String appServerHome = context.getRealPath("/");
    File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");
    VersionInfo zanataVersion;
    Attributes atts = null;
    if (manifestFile.canRead()) {
        Manifest mf = new Manifest();
        try (FileInputStream fis = new FileInputStream(manifestFile)) {
            mf.read(fis);
        }
        atts = mf.getMainAttributes();
    }
    zanataVersion = VersionUtility.getVersionInfo(atts, ZanataInit.class);
    this.applicationConfiguration.setVersion(zanataVersion.getVersionNo());
    this.applicationConfiguration.setBuildTimestamp(zanataVersion.getBuildTimeStamp());
    this.applicationConfiguration.setScmDescribe(zanataVersion.getScmDescribe());
    this.applicationConfiguration.applyLoggingConfiguration();
    logBanner(zanataVersion);
    boolean authlogged = false;
    if (applicationConfiguration.isInternalAuth()) {
        log.info("Internal authentication: enabled");
        authlogged = true;
    }
    if (applicationConfiguration.isOpenIdAuth()) {
        log.info("OpenID authentication: enabled");
        authlogged = true;
    }
    if (applicationConfiguration.isKerberosAuth()) {
        log.info("SPNEGO/Kerberos authentication: enabled");
        authlogged = true;
    }
    if (!authlogged) {
        log.info("Using JAAS authentication");
    }
    log.info("Enable copyTrans: {}", this.applicationConfiguration.isCopyTransEnabled());
    String javamelodyDir = System.getProperty("javamelody.storage-directory");
    log.info("JavaMelody stats directory: " + javamelodyDir);
    String indexBase = applicationConfiguration.getHibernateSearchIndexBase();
    log.info("Lucene index directory: " + indexBase);
    if (indexBase != null) {
        checkLuceneLocks(new File(indexBase));
    }
    // Email server information
    log.info("Mail Session (JNDI): {}", EmailBuilder.MAIL_SESSION_JNDI);
    startupEvent.fire(new ServerStarted());
    log.info("Started Zanata...");
}

From source file:com.wavemaker.runtime.service.WaveMakerService.java

/**
 * Builds whitelist tables and sets isStudio for proxy security
 *//*w w w. j ava2 s . c o m*/
public WaveMakerService() {
    ServletContext context = RuntimeAccess.getInstance().getSession().getServletContext();
    String webinf = context.getRealPath("WEB-INF");
    try {
        isStudio = new File(webinf + File.separator + STUDIO_SPRINGAPP).exists();
    } catch (IllegalArgumentException iae) {
        isStudio = false;
    }

    try {
        hostSet = new HashSet<String>();
        domainSet = new HashSet<String>();
        String whiteFile = IOUtils.read(new File(webinf + File.separator + WHITELIST));
        String[] urlList = whiteFile.split("\\r?\\n");

        for (String urlString : urlList) {
            URL url = new URL(urlString);
            String host = url.getHost();
            hostSet.add(host);
            String domain = hostToDomain(host);
            if (domain != null) {
                domainSet.add(domain);
            }
        }
        logger.debug("Allowed hosts: " + hostSet.toString());
        logger.debug("Allowed domains: " + domainSet.toString());

    } catch (IOException ioe) {
        if (isStudio)
            logger.warn("*** ONLY Studio XHR calls allowed ***");
        else
            logger.warn("*** " + WHITELIST + " file not found, XHR proxy DISABLED ***");
    }
}

From source file:nl.armatiek.xslweb.configuration.Context.java

public void setServletContext(ServletContext servletContext) {
    this.servletContext = servletContext;
    this.contextPath = servletContext.getContextPath();
    this.webInfDir = new File(servletContext.getRealPath("/WEB-INF"));
}

From source file:eu.openanalytics.rsb.config.BootstrapConfigurationServletContextListener.java

private void copyUiFragments(final ServletContext servletContext) {
    final File fragmentsSourceDirectory = new File(ConfigurationFactory.RSB_CONFIGURATION_DIRECTORY,
            "fragments");
    if (!fragmentsSourceDirectory.isDirectory()) {
        return;/* w  ww  .  j  ava 2  s  .c  o  m*/
    }

    final String fragmentsDestinationPath = servletContext.getRealPath("/fragments");
    if (StringUtils.isBlank(fragmentsDestinationPath)) {
        return;
    }

    final File fragmentsDestinationDirectory = new File(fragmentsDestinationPath);

    final File[] sourceFragments = fragmentsSourceDirectory.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            return StringUtils.endsWith(name, ".html");
        }
    });

    if (sourceFragments == null) {
        return;
    }

    for (final File sourceFragment : sourceFragments) {
        final File destinationFragment = new File(fragmentsDestinationDirectory, sourceFragment.getName());

        try {
            FileCopyUtils.copy(sourceFragment, destinationFragment);
            LOGGER.info("Installed UI fragment: " + sourceFragment.getName());
        } catch (final IOException ioe) {
            LOGGER.error("Failed to copy UI fragment from: " + sourceFragment + " to: " + destinationFragment,
                    ioe);
        }
    }
}

From source file:org.jboss.bpm.report.ReportFacade.java

@GET
@Path("render/{fileName}")
@Produces("text/html")
public Response viewReportHtml(@PathParam("fileName") String fileName, @Context HttpServletRequest request,
        @Context ServletContext servletContext) {
    assertBirtAvailability();//  w  ww.  j ava 2  s  .  c  o m

    try {
        RenderMetaData renderMeta = defaultRenderMetaData(fileName, request);

        String outputFileName = birtService.view(renderMeta, servletContext, request);
        File reportFile = new File(
                servletContext.getRealPath("/WEB-INF" + birtService.getIntegrationConfig().getOutputDir()) + "/"
                        + outputFileName);
        return Response.ok(reportFile).type("text/html").build();
    } catch (Throwable e1) {
        return gracefulException(e1);
    }
}

From source file:com.kahlon.guard.controller.PersonImageManager.java

/**
 * Capture Image/*from w  w  w  . j  ava  2  s.  com*/
 * 
 * @param captureEvent
 */
public void onCapture(CaptureEvent captureEvent) {

    photo = getRandomImageName();
    byte[] data = captureEvent.getData();

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator
            + "image" + File.separator + "temp" + File.separator + photo + ".png";
    if (fileNames == null) {
        fileNames = new ArrayList<>();
    }
    fileNames.add(newFileName);

    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(new File(newFileName));
        imageOutput.write(data, 0, data.length);
        imageOutput.close();
        imageUpload = false;
    } catch (Exception e) {
        throw new FacesException("Error in writing captured image.");
    }
}