Java tutorial
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.felix.webconsole; import java.io.IOException; import java.io.PrintWriter; import java.text.MessageFormat; import java.util.Dictionary; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.servlet.ServletRequestContext; import org.apache.felix.webconsole.internal.servlet.OsgiManager; import org.cg.dao.console.ExtOsgiManager; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; public abstract class AbstractWebConsolePluginServlet extends HttpServlet { @SuppressWarnings({ "rawtypes", "unchecked" }) public static String getRequestParameter(HttpServletRequest request, String name) { // just get the parameter if not a multipart/form-data POST if (!ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) { return request.getParameter(name); } // check, whether we alread have the parameters Map params = (Map) request.getAttribute(ATTR_FILEUPLOAD); if (params == null) { // parameters not read yet, read now // Create a factory for disk-based file items DiskFileItemFactory myFactory = new DiskFileItemFactory(); myFactory.setSizeThreshold(FACTORY_LIMIT); // Create a new file upload handler ServletFileUpload uploadServlet = new ServletFileUpload(myFactory); uploadServlet.setSizeMax(-1); // Parse the request params = new HashMap(); try { List parseItems = uploadServlet.parseRequest(request); for (Iterator fIter = parseItems.iterator(); fIter.hasNext();) { FileItem fileItem = (FileItem) fIter.next(); FileItem[] currentItem = (FileItem[]) params.get(fileItem.getFieldName()); if (currentItem == null) { currentItem = new FileItem[] { fileItem }; } else { FileItem[] newCurrent = new FileItem[currentItem.length + 1]; System.arraycopy(currentItem, 0, newCurrent, 0, currentItem.length); newCurrent[currentItem.length] = fileItem; currentItem = newCurrent; } params.put(fileItem.getFieldName(), currentItem); } } catch (FileUploadException fue) { } request.setAttribute(ATTR_FILEUPLOAD, params); } FileItem[] fileParam = (FileItem[]) params.get(name); if (fileParam != null) { for (int i = 0; i < fileParam.length; i++) { if (fileParam[i].isFormField()) { return fileParam[i].getString(); } } } // no valid string parameter, fail return null; } /** Pseudo class version ID to keep the IDE quite. */ private static final long serialVersionUID = 1L; private static final int FACTORY_LIMIT = 256000; /** * The name of the request attribute containig the map of FileItems from the * POST request */ public static final String ATTR_FILEUPLOAD = "org.apache.felix.webconsole.fileupload"; private static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"xhtml1-transitional.dtd\">" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html; utf-8\">" + "<link rel=\"icon\" href=\"{6}/res/imgs/favicon.ico\">" + "<title>{0} - {2}</title>" + "<script src=\"{5}/res/ui/jquery-1.3.2.min.js\" language=\"JavaScript\"></script>" + "<script src=\"{5}/res/ui/jquery.tablesorter-2.0.3.min.js\" language=\"JavaScript\"></script>" + "<script src=\"{5}/res/ui/admin.js\" language=\"JavaScript\"></script>" + "<script src=\"{5}/res/ui/ui.js\" language=\"JavaScript\"></script>" + "<script language=\"JavaScript\">" + "appRoot = \"{5}\";" + "pluginRoot = \"{7}\" + \"/{6}\";" + "</script>" + "<link href=\"{5}/res/ui/admin.css\" rel=\"stylesheet\" type=\"text/css\">" + "</head>" + "<body>" + "<div id=\"main\">" + "<div id=\"lead\">" + "<h1>" + "{0}<br>{2}" + "</h1>" + "<p>" + "<a target=\"_blank\" href=\"{3}\" title=\"{1}\"><img src=\"{5}/res/imgs/logo.png\" width=\"165\" height=\"63\" border=\"0\"></a>" + "</p>" + "</div>"; private String bundleVendorName; private BundleContext bundleContext; private String bundleProductWeb; private String bundleName; private String productName; @SuppressWarnings("rawtypes") public void activateBundle(BundleContext comingContext) { this.bundleContext = comingContext; Dictionary headersBook = comingContext.getBundle().getHeaders(); bundleVendorName = (String) headersBook.get(Constants.BUNDLE_VENDOR); bundleName = (String) headersBook.get(Constants.BUNDLE_NAME); // "OSGi Management Console"; bundleProductWeb = (String) headersBook.get(Constants.BUNDLE_DOCURL); productName = "Application Server"; } // ---------- AbstractWebConsolePlugin API // ---------------------------------- public void deActivate() { this.bundleContext = null; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter printWriter = startResponse(request, response); renderTopNavigation(request, printWriter); renderServletRequest(request, response); finalResponse(printWriter); } protected void finalResponse(PrintWriter printWriter) { printWriter.println("</body>"); printWriter.println("</html>"); } protected BundleContext getBundleContext() { return this.bundleContext; } public abstract String getServletCapital(); public abstract String getServletLabel(); // ---------- HttpServlet Overwrites // ---------------------------------------- public String getServletName() { return getServletCapital(); } protected abstract void renderServletRequest(HttpServletRequest comingRequest, HttpServletResponse comingResponse) throws ServletException, IOException; @SuppressWarnings({ "unchecked", "rawtypes" }) protected void renderTopNavigation(HttpServletRequest request, PrintWriter printWriter) { // assume pathInfo to not be null, else this would not be called boolean flag = true; String pathInfo = request.getPathInfo(); int slashPos = pathInfo.indexOf("/", 1); if (slashPos < 0) { slashPos = pathInfo.length(); flag = false; } boolean disabled = false; String appRoot = (String) request.getAttribute(ExtOsgiManager.ATTR_WEBAPP_ROOT); Map labelMap = (Map) request.getAttribute(OsgiManager.OSGI_LABEL_MAP); pathInfo = pathInfo.substring(1, slashPos); if (labelMap != null) { printWriter.println("<div id='technav'>"); SortedMap sortMap = new TreeMap(); for (Iterator iter = labelMap.entrySet().iterator(); iter.hasNext();) { Map.Entry labelMapEntry = (Map.Entry) iter.next(); if (labelMapEntry.getKey() == null) { } else if (disabled || pathInfo.equals(labelMapEntry.getKey())) { if (flag) { sortMap.put(labelMapEntry.getValue(), "<a class='technavat' href='" + appRoot + "/" + labelMapEntry.getKey() + "'>" + labelMapEntry.getValue() + "</a>"); } else { sortMap.put(labelMapEntry.getValue(), "<span class='technavat'>" + labelMapEntry.getValue() + "</span>"); } } else { sortMap.put(labelMapEntry.getValue(), "<a href='" + appRoot + "/" + labelMapEntry.getKey() + "'>" + labelMapEntry.getValue() + "</a>"); } } for (Iterator mapIter = sortMap.values().iterator(); mapIter.hasNext();) { printWriter.print("<nobr>"); printWriter.print(mapIter.next()); printWriter.println("</nobr>"); } printWriter.println("</div>"); } } /** * Utility method to handle relative redirects. Some app servers like web * sphere handle relative redirects differently */ protected void sendRedirectURL(final HttpServletRequest request, final HttpServletResponse response, String redirectUrl) throws IOException { // check for relative url if (!redirectUrl.startsWith("/")) { String base = request.getContextPath() + request.getServletPath() + request.getPathInfo(); int lastSlash = base.lastIndexOf('/'); if (lastSlash > -1) { base = base.substring(0, lastSlash); } else { lastSlash = base.indexOf(':'); base = (lastSlash > -1) ? base.substring(lastSlash + 1, base.length()) : ""; } if (!base.startsWith("/")) { base = '/' + base; } redirectUrl = base + '/' + redirectUrl; } response.sendRedirect(redirectUrl); } protected PrintWriter startResponse(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter printWriter = response.getWriter(); String responseHeader = MessageFormat.format(HEADER, new Object[] { bundleName, productName, getServletCapital(), bundleProductWeb, bundleVendorName, (String) request.getAttribute(OsgiManager.OSGI_APP_ROOT), getServletLabel(), (String) request.getAttribute(ExtOsgiManager.ATTR_WEBAPP_ROOT) }); printWriter.println(responseHeader); return printWriter; } }