Example usage for javax.servlet.jsp PageContext getServletContext

List of usage examples for javax.servlet.jsp PageContext getServletContext

Introduction

In this page you can find the example usage for javax.servlet.jsp PageContext getServletContext.

Prototype


abstract public ServletContext getServletContext();

Source Link

Document

The ServletContext instance.

Usage

From source file:com.ideo.jso.Group.java

/**
 * Adds a tag into the flow to include a resource "the classic way", and suffix by a timestamp corresponding to the last modification date of the file
 * @param pageContext//  w w  w .ja v a 2  s. c om
 * @param out
 * @param webPath
 * @param tagBegin
 * @param tagEnd
 * @throws IOException
 */
private void includeResource(PageContext pageContext, Writer out, String webPath, String tagBegin,
        String tagEnd) throws IOException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

    String fileName = pageContext.getServletContext().getRealPath(webPath);

    out.write(tagBegin);
    out.write(request.getContextPath());
    if (!webPath.startsWith("/"))
        out.write("/");
    out.write(webPath);

    if (fileName != null && fileName.length() > 0) {
        long timestamp = new File(fileName).lastModified();
        out.write("?" + JsoServlet.TIMESTAMP + "=" + timestamp);
    }
    out.write(tagEnd);
    out.write("\n");
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 *  An utility method for finding a JSP page.  It searches only under
 *  either current context or by the absolute name.
 *
 *  @param pageContext the JSP PageContext
 *  @param name The name of the JSP page to look for (e.g "Wiki.jsp")
 *  @return The context path to the resource
 *///from  w  ww  . ja  v a2 s  .  co m
public String findJSP(PageContext pageContext, String name) {
    ServletContext sContext = pageContext.getServletContext();

    return findResource(sContext, name);
}

From source file:com.truthbean.core.web.kindeditor.FileUpload.java

@Override
public void service(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {

    final PageContext pageContext;
    HttpSession session = null;/*  www .j  a va  2  s. c o m*/
    final ServletContext application;
    final ServletConfig config;
    JspWriter out = null;
    final Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=UTF-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");
        out.write("\r\n");

        /**
         * KindEditor JSP
         *
         * JSP???? ??
         *
         */
        // ?
        String savePath = pageContext.getServletContext().getRealPath("/") + "resource/";

        String savePath$ = savePath;

        // ?URL
        String saveUrl = request.getContextPath() + "/resource/";

        // ???
        HashMap<String, String> extMap = new HashMap<>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // ?
        long maxSize = 10 * 1024 * 1024 * 1024L;

        response.setContentType("text/html; charset=UTF-8");

        if (!ServletFileUpload.isMultipartContent(request)) {
            out.println(getError(""));
            return;
        }
        // 
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            out.println(getError("?"));
            return;
        }
        // ??
        if (!uploadDir.canWrite()) {
            out.println(getError("??"));
            return;
        }

        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if (!extMap.containsKey(dirName)) {
            out.println(getError("???"));
            return;
        }
        // 
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            if (!item.isFormField()) {
                // ?
                if (item.getSize() > maxSize) {
                    out.println(getError("??"));
                    return;
                }
                // ??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    out.println(getError("??????\n??"
                            + extMap.get(dirName) + "?"));
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                } catch (Exception e) {
                    out.println(getError(""));
                    return;
                }

                JSONObject obj = new JSONObject();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);

                request.getSession().setAttribute("fileName", savePath$ + fileName);
                request.getSession().setAttribute("filePath", savePath + newFileName);
                request.getSession().setAttribute("fileUrl", saveUrl + newFileName);

                out.println(obj.toJSONString());
            }
        }

        out.write('\r');
        out.write('\n');
    } catch (IOException | FileUploadException t) {
        if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0) {
                if (response.isCommitted()) {
                    out.flush();
                } else {
                    out.clearBuffer();
                }
            }
            if (_jspx_page_context != null) {
                _jspx_page_context.handlePageException(t);
            } else {
                throw new ServletException(t);
            }
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 *   Lists the skins available under this template.  Returns an
 *   empty Set, if there are no extra skins available.  Note that
 *   this method does not check whether there is anything actually
 *   in the directories, it just lists them.  This may change
 *   in the future.//from   w w  w  .  ja  va  2 s  . co  m
 *
 *   @param pageContext the JSP PageContext
 *   @param template The template to search
 *   @return Set of Strings with the skin names.
 *   @since 2.3.26
 */
@SuppressWarnings("unchecked")
public Set listSkins(PageContext pageContext, String template) {
    String place = makeFullJSPName(template, SKIN_DIRECTORY);

    ServletContext sContext = pageContext.getServletContext();

    Set<String> skinSet = sContext.getResourcePaths(place);
    TreeSet<String> resultSet = new TreeSet<String>();

    if (log.isDebugEnabled())
        log.debug("Listings skins from " + place);

    if (skinSet != null) {
        String[] skins = {};

        skins = skinSet.toArray(skins);

        for (int i = 0; i < skins.length; i++) {
            String[] s = StringUtils.split(skins[i], "/");

            if (s.length > 2 && skins[i].endsWith("/")) {
                String skinName = s[s.length - 1];
                resultSet.add(skinName);
                if (log.isDebugEnabled())
                    log.debug("...adding skin '" + skinName + "'");
            }
        }
    }

    return resultSet;
}

From source file:com.ideo.jso.Group.java

/**
 * Display the js import tags, depending of the group parameters set in the XML descriptor and of the tag exploded parameter.
 * @param pageContext/*w  ww.  ja  v a2s. c o m*/
 * @param out the writer into which will be written the tags  
 * @param exploded the way to import JS files : merged or not
 * @throws IOException
 */
public void printIncludeJSTag(PageContext pageContext, Writer out, boolean exploded) throws IOException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    if (exploded) {
        for (int i = 0; i < getDeepJsNames().size(); i++)
            includeResource(pageContext, out, (String) getDeepJsNames().get(i),
                    "<script type=\"text/javascript\" src=\"", "\"></script>");
    } else {
        long maxJSTimestamp = getMaxJSTimestamp(pageContext.getServletContext());

        out.write("<script type=\"text/javascript\" src=\"");
        out.write(request.getContextPath());
        out.write("/jso/");
        out.write(getName());
        out.write(".js?" + JsoServlet.TIMESTAMP + "=");
        out.write("" + maxJSTimestamp);
        out.write("\"></script>\n");

    }
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 * List all installed i18n language properties
 * /*  w  w w  .ja v  a  2s.c  om*/
 * @param pageContext
 * @return map of installed Languages (with help of Juan Pablo Santos Rodriguez)
 * @since 2.7.x
 */
public Map listLanguages(PageContext pageContext) {
    LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>();

    String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString();
    JarInputStream jarStream = null;

    try {
        JarEntry entry;
        InputStream inputStream = pageContext.getServletContext().getResourceAsStream(I18NRESOURCE_PATH);
        jarStream = new JarInputStream(inputStream);

        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();

            if (!entry.isDirectory() && name.startsWith(I18NRESOURCE_PREFIX)
                    && name.endsWith(I18NRESOURCE_SUFFIX)) {
                name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX));

                Locale locale = new Locale(name.substring(0, 2),
                        ((name.indexOf("_") == -1) ? "" : name.substring(3, 5)));

                String defaultLanguage = "";

                if (clientLanguage.startsWith(name)) {
                    defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE);
                }

                resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage);
            }
        }
    } catch (IOException ioe) {
        if (log.isDebugEnabled())
            log.debug("Could not search jar file '" + I18NRESOURCE_PATH
                    + "'for properties files due to an IOException: \n" + ioe.getMessage());
    } finally {
        if (jarStream != null) {
            try {
                jarStream.close();
            } catch (IOException e) {
            }
        }
    }

    return resultMap;
}

From source file:com.ideo.jso.Group.java

/**
 * Display the css import tags, depending of the group parameters set in the XML descriptor.
 * @param pageContext//www . j ava2  s.co  m
 * @param out the writer into which will be written the tags  
 * @throws IOException
 */
public void printIncludeCSSTag(PageContext pageContext, Writer out) throws IOException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    if (!isMinimizeCss()) {
        //not minimized, just act as a normal stylesheet link
        for (int i = 0; i < getCssNames().size(); i++)
            includeResource(pageContext, out, (String) getCssNames().get(i),
                    "<link rel=\"stylesheet\" type=\"text/css\" href=\"", "\"/>");
    } else {
        // merge all this group stylesheet
        if (getCssNames().size() != 0) {
            long cssTimeStamp = getMaxCSSTimestamp(pageContext.getServletContext());

            out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
            out.write(request.getContextPath());
            out.write("/jso/");
            out.write(getName());
            out.write(".css?" + JsoServlet.TIMESTAMP + "=");
            out.write("" + cssTimeStamp);
            out.write("\"></link>\n");
        }
    }
    // include the subgroups stylesheet. No recursivity for minimization
    for (Iterator iterator = getSubgroups().iterator(); iterator.hasNext();) {
        Group subGroup = (Group) iterator.next();
        subGroup.printIncludeCSSTag(pageContext, out);
    }
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 *  Attempts to locate a resource under the given template.  If that template
 *  does not exist, or the page does not exist under that template, will
 *  attempt to locate a similarly named file under the default template.
 *  <p>//from w  w w. j  av  a  2s  .c  o m
 *  Even though the name suggests only JSP files can be located, but in fact
 *  this method can find also other resources than JSP files.
 *
 *  @param pageContext The JSP PageContext
 *  @param template From which template we should seek initially?
 *  @param name Which resource are we looking for (e.g. "ViewTemplate.jsp")
 *  @return path to the JSP page; null, if it was not found.
 */
public String findJSP(PageContext pageContext, String template, String name) {
    if (name == null || template == null) {
        log.fatal("findJSP() was asked to find a null template or name (" + template + "," + name + ")."
                + " JSP page '" + ((HttpServletRequest) pageContext.getRequest()).getRequestURI() + "'");
        throw new InternalWikiException("Illegal arguments to findJSP(); please check logs.");
    }

    return findResource(pageContext.getServletContext(), template, name);
}

From source file:org.apache.jsp.WEB_002dINF.pages.includes.topmenu_jsp.java

public void _jspService(final javax.servlet.http.HttpServletRequest request,
        final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {//from   ww w. j a  v a  2 s. c o  m
        response.setContentType("text/html");
        pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        if (_jspx_meth_c_005fif_005f0(_jspx_page_context))
            return;
    } catch (java.lang.Throwable t) {
        if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    out.clearBuffer();
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
            else
                throw new ServletException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}