List of usage examples for javax.servlet.http HttpServletRequest isUserInRole
public boolean isUserInRole(String role);
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
private Boolean isSuperAdmin(HttpServletRequest req) { Boolean isSuperAdmin = Boolean.FALSE; Set<String> allSuperAdminGroups = userConnectivityService.getAllSuperAdminGroups(); for (String superAdminGroup : allSuperAdminGroups) { if (req.isUserInRole(superAdminGroup)) { isSuperAdmin = Boolean.TRUE; break; }/*ww w .jav a2s. c om*/ } return isSuperAdmin; }
From source file:nl.nn.adapterframework.http.RestServiceDispatcher.java
/** * Dispatch a request.// ww w.j a v a2s. c o m * @param uri the name of the IReceiver object * @param method the correlationId of this request; * @param request the <code>String</code> with the request/input * @return String with the result of processing the <code>request</code> throught the <code>serviceName</code> */ public String dispatchRequest(String restPath, String uri, HttpServletRequest httpServletRequest, String etag, String contentType, String request, Map context, HttpServletResponse httpServletResponse, ServletContext servletContext) throws ListenerException { String method = httpServletRequest.getMethod(); if (log.isTraceEnabled()) log.trace("searching listener for uri [" + uri + "] method [" + method + "]"); String matchingPattern = findMatchingPattern(uri); if (matchingPattern == null) { throw new ListenerException("no REST listener configured for uri [" + uri + "]"); } Map methodConfig = getMethodConfig(matchingPattern, method); if (methodConfig == null) { throw new ListenerException("No RestListeners specified for uri [" + uri + "] method [" + method + "]"); } if (context == null) { context = new HashMap(); } context.put("restPath", restPath); context.put("uri", uri); context.put("method", method); context.put("etag", etag); context.put("contentType", contentType); ServiceClient listener = (ServiceClient) methodConfig.get(KEY_LISTENER); String etagKey = (String) methodConfig.get(KEY_ETAG_KEY); String contentTypeKey = (String) methodConfig.get(KEY_CONTENT_TYPE_KEY); Principal principal = null; if (httpServletRequest != null) { principal = httpServletRequest.getUserPrincipal(); if (principal != null) { context.put("principal", principal.getName()); } } String ctName = Thread.currentThread().getName(); try { boolean writeToSecLog = false; if (listener instanceof RestListener) { RestListener restListener = (RestListener) listener; if (restListener.isRetrieveMultipart()) { if (ServletFileUpload.isMultipartContent(httpServletRequest)) { try { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(httpServletRequest); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). String fieldName = item.getFieldName(); String fieldValue = item.getString(); log.debug("setting parameter [" + fieldName + "] to [" + fieldValue + "]"); context.put(fieldName, fieldValue); } else { // Process form file field (input type="file"). String fieldName = item.getFieldName(); String fieldNameName = fieldName + "Name"; String fileName = FilenameUtils.getName(item.getName()); if (log.isTraceEnabled()) log.trace( "setting parameter [" + fieldNameName + "] to [" + fileName + "]"); context.put(fieldNameName, fileName); InputStream inputStream = item.getInputStream(); if (inputStream.available() > 0) { log.debug("setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]"); context.put(fieldName, inputStream); } else { log.debug("setting parameter [" + fieldName + "] to [" + null + "]"); context.put(fieldName, null); } } } } catch (FileUploadException e) { throw new ListenerException(e); } catch (IOException e) { throw new ListenerException(e); } } } writeToSecLog = restListener.isWriteToSecLog(); if (writeToSecLog) { context.put("writeSecLogMessage", restListener.isWriteSecLogMessage()); } boolean authorized = false; if (principal == null) { authorized = true; } else { String authRoles = restListener.getAuthRoles(); if (StringUtils.isNotEmpty(authRoles)) { StringTokenizer st = new StringTokenizer(authRoles, ",;"); while (st.hasMoreTokens()) { String authRole = st.nextToken(); if (httpServletRequest.isUserInRole(authRole)) { authorized = true; } } } } if (!authorized) { throw new ListenerException("Not allowed for uri [" + uri + "]"); } Thread.currentThread().setName(restListener.getName() + "[" + ctName + "]"); } if (etagKey != null) context.put(etagKey, etag); if (contentTypeKey != null) context.put(contentTypeKey, contentType); if (log.isTraceEnabled()) log.trace("dispatching request, uri [" + uri + "] listener pattern [" + matchingPattern + "] method [" + method + "] etag [" + etag + "] contentType [" + contentType + "]"); if (httpServletRequest != null) context.put("restListenerServletRequest", httpServletRequest); if (httpServletResponse != null) context.put("restListenerServletResponse", httpServletResponse); if (servletContext != null) context.put("restListenerServletContext", servletContext); if (secLogEnabled && writeToSecLog) { secLog.info(HttpUtils.getExtendedCommandIssuedBy(httpServletRequest)); } String result = listener.processRequest(null, request, context); if (result == null && !context.containsKey("exitcode")) { log.warn("result is null!"); } return result; } finally { if (listener instanceof RestListener) { Thread.currentThread().setName(ctName); } } }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
private Set<String> getUserRoles(HttpServletRequest req) { LOGGER.info("========Getting the user roles========="); Set<String> userGroups = null; Set<String> allGroups = userConnectivityService.getAllGroups(); if (null == allGroups || allGroups.isEmpty()) { LOGGER.error("No groups fetched from Authenticated User.....All groups is empty.Returning null"); } else {/*www . ja v a 2 s . c o m*/ userGroups = new HashSet<String>(); for (String group : allGroups) { if (null != group && !group.isEmpty() && req.isUserInRole(group)) { LOGGER.info("Added group is: " + group); userGroups.add(group); } } LOGGER.info("List of fetched user roles:"); for (String userRole : userGroups) { LOGGER.info(userRole + ","); } if (userGroups.isEmpty()) { String userName = WebServiceUtil.EMPTY_STRING; if (req.getUserPrincipal() != null) { userName = req.getUserPrincipal().getName(); } LOGGER.error("No roles found in Authenticated User for " + userName); userGroups = null; } } return userGroups; }
From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java
/** * Gets the user roles.// w w w .j a v a 2 s . c o m * * @param req the req * @return the user roles */ public Set<String> getUserRoles(final HttpServletRequest req) { LOGGER.info("========Getting the user roles========="); Set<String> allGroups = userConnectivityService.getAllGroups(); if (null == allGroups || allGroups.isEmpty()) { LOGGER.error("No groups fetched from Authenticated User.....All groups is empty.Returning null"); return null; } Set<String> userGroups = new HashSet<String>(); for (String group : allGroups) { if (null != group && !group.isEmpty()) { if (req.isUserInRole(group)) { LOGGER.info("Added group is: " + group); userGroups.add(group); } } } LOGGER.info("List of fetched user roles:"); for (String userRole : userGroups) { LOGGER.info(userRole + ","); } if (userGroups.isEmpty()) { String userName = WebServiceUtil.EMPTY_STRING; if (req.getUserPrincipal() != null) { userName = req.getUserPrincipal().getName(); } LOGGER.error("No roles found in Authenticated User for " + userName); userGroups = null; } return userGroups; }
From source file:jeeves.server.sources.http.JeevesServlet.java
private void execute(HttpServletRequest req, HttpServletResponse res) throws IOException { String ip = req.getRemoteAddr(); // if we do have the optional x-forwarded-for request header then // use whatever is in it to record ip address of client String forwardedFor = req.getHeader("x-forwarded-for"); if (forwardedFor != null) ip = forwardedFor;/* w ww.ja v a 2s . c om*/ Log.info(Log.REQUEST, "=========================================================="); Log.info(Log.REQUEST, "HTML Request (from " + ip + ") : " + req.getRequestURI()); if (Log.isDebugEnabled(Log.REQUEST)) { Log.debug(Log.REQUEST, "Method : " + req.getMethod()); Log.debug(Log.REQUEST, "Content type : " + req.getContentType()); // Log.debug(Log.REQUEST, "Context path : "+ req.getContextPath()); // Log.debug(Log.REQUEST, "Char encoding: "+ req.getCharacterEncoding()); Log.debug(Log.REQUEST, "Accept : " + req.getHeader("Accept")); // Log.debug(Log.REQUEST, "Server name : "+ req.getServerName()); // Log.debug(Log.REQUEST, "Server port : "+ req.getServerPort()); } // for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) { // String theHeader = (String)e.nextElement(); // if(Log.isDebugEnabled(Log.REQUEST)) { // Log.debug(Log.REQUEST, "Got header: "+theHeader); // Log.debug(Log.REQUEST, "With value: "+req.getHeader(theHeader)); // } // } HttpSession httpSession = req.getSession(); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "Session id is " + httpSession.getId()); UserSession session = (UserSession) httpSession.getAttribute("session"); //------------------------------------------------------------------------ //--- create a new session if doesn't exist if (session == null) { //--- create session session = new UserSession(); httpSession.setAttribute("session", session); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "Session created for client : " + ip); } session.setProperty("realSession", httpSession); //------------------------------------------------------------------------ //--- build service request ServiceRequest srvReq = null; //--- create request try { srvReq = ServiceRequestFactory.create(req, res, jeeves.getUploadDir(), jeeves.getMaxUploadSize()); } catch (FileUploadTooBigEx e) { StringBuffer sb = new StringBuffer(); sb.append("Opgeladen bestand overschrijdt de maximaal toegelaten grootte van " + jeeves.getMaxUploadSize() + " Mb\n"); sb.append("Error : " + e.getClass().getName() + "\n"); res.sendError(400, sb.toString()); // now stick the stack trace on the end and log the whole lot sb.append("Stack :\n"); sb.append(Util.getStackTrace(e)); Log.error(Log.REQUEST, sb.toString()); return; } catch (FileTypeNotAllowedEx e) { StringBuffer sb = new StringBuffer(); sb.append("Bestand heeft niet het juiste type\n"); sb.append("Error : " + e.getClass().getName() + "\n"); res.sendError(400, sb.toString()); // now stick the stack trace on the end and log the whole lot sb.append("Stack :\n"); sb.append(Util.getStackTrace(e)); Log.error(Log.REQUEST, sb.toString()); return; } catch (Exception e) { StringBuffer sb = new StringBuffer(); sb.append("Cannot build ServiceRequest\n"); sb.append("Cause : " + e.getMessage() + "\n"); sb.append("Error : " + e.getClass().getName() + "\n"); res.sendError(400, sb.toString()); // now stick the stack trace on the end and log the whole lot sb.append("Stack :\n"); sb.append(Util.getStackTrace(e)); Log.error(Log.REQUEST, sb.toString()); return; } if ("user.agiv.login".equals(srvReq.getService())) { if (srvReq.getParams() != null && srvReq.getParams().getChild("wa") != null && srvReq.getParams().getChild("wa").getTextTrim().equals("wsignoutcleanup1.0")) { srvReq.setService("user.agiv.logout"); } else { Principal p = req.getUserPrincipal(); if (p != null && p instanceof FederationPrincipal/* && SecurityTokenThreadLocal.getToken()==null*/) { FederationPrincipal fp = (FederationPrincipal) p; /* for (Claim c: fp.getClaims()) { System.out.println(c.getClaimType().toString() + ":" + (c.getValue()!=null ? c.getValue().toString() : "")); } */ Map<String, String> roleProfileMapping = new HashMap<String, String>(); String profile = null; roleProfileMapping.put("Authenticated", "RegisteredUser"); roleProfileMapping.put(nodeType + " Metadata Admin", "Administrator"); roleProfileMapping.put(nodeType + " Metadata Editor", "Editor"); roleProfileMapping.put(nodeType + " Metadata Hoofdeditor", "Hoofdeditor"); List<String> roleListToCheck = Arrays.asList(nodeType + " Metadata Admin", nodeType + " Metadata Hoofdeditor", nodeType + " Metadata Editor", "Authenticated"); for (String item : roleListToCheck) { if (req.isUserInRole(item)) { profile = roleProfileMapping.get(item); break; } } String contactid = Util.getClaimValue(fp, "contactid"); session.authenticate(contactid, contactid/* + "_" + Util.getClaimValue(fp,"name")*/, Util.getClaimValue(fp, "givenname"), Util.getClaimValue(fp, "surname"), profile != null ? profile : "RegisteredUser", Util.getClaimValue(fp, "emailaddress")); List<Map<String, String>> groups = new ArrayList<Map<String, String>>(); Map<String, String> group = new HashMap<String, String>(); String parentorganisationid = Util.getClaimValue(fp, "parentorganisationid"); String parentorganisationdisplayname = Util.getClaimValue(fp, "parentorganisationdisplayname"); group.put("name", StringUtils.isBlank(parentorganisationid) ? Util.getClaimValue(fp, "organisationid") : parentorganisationid); group.put("description", StringUtils.isBlank(parentorganisationdisplayname) ? (StringUtils.isBlank(parentorganisationid) ? Util.getClaimValue(fp, "organisationdisplayname") : parentorganisationid) : parentorganisationdisplayname); groups.add(group); session.setProperty("groups", groups); } else { System.out.println("Principal is not instance of FederationPrincipal"); } } } //--- execute request jeeves.dispatch(srvReq, session); }
From source file:src.servlets.ManagePropertys.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*w w w . ja v a 2 s .c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // //set date format // DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); // //get current date time with Date() // //Date date2 = new Date(); // //System.out.println(dateFormat.format(date2)); // // // // //get current date time with Calendar() // Calendar cal = Calendar.getInstance(); // System.out.println(dateFormat.format(cal.getTime())); // setup values Agents LoggedIn = null; try { LoggedIn = AgentsDB.getByUsername(request.getUserPrincipal().getName()); //request.setAttribute("agent", agent); } //end try catch (Exception ex) { //address = "/Error.jsp"; } int agentIdfromDB = 0; agentIdfromDB = LoggedIn.getAgentId(); Integer id = 0; String street = ""; String city = ""; Integer listingNum = 0; Integer styleId = 0; Integer typeId = 0; Integer bedrooms = 0; Float bathrooms = null; Integer squarefeet = 0; String description = ""; String lotsize = ""; Short garageSize = (short) 0; Integer garageId = 0; Integer agentId = agentIdfromDB;// Need to get ID from Session when created! Date dateAdded = null; String photo;//= request.getParameter("photo"); Double price = 0.0; List<FileItem> formItems2 = null; ////////////////// // if (!ServletFileUpload.isMultipartContent(request) && id!=0) { // // if not, we stop here // PrintWriter writer = response.getWriter(); // writer.println("Error: Form must has enctype=multipart/form-data."); // writer.flush(); // return; // } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } // Check file Extention @SuppressWarnings("unchecked") List<FileItem> formItems = null; String fileNameExt = ""; try { formItems = upload.parseRequest(request); formItems2 = formItems; } catch (FileUploadException ex) { Logger.getLogger(ManagePropertys.class.getName()).log(Level.SEVERE, null, ex); } if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { fileNameExt = new File(item.getName()).getName(); } if (item.getFieldName().equals("street")) { street = item.getString(); } if (item.getFieldName().equals("city")) { city = item.getString(); } if (item.getFieldName().equals("listingNum")) { listingNum = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("styleId")) { styleId = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("typeId")) { typeId = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("bedrooms")) { bedrooms = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("bathrooms")) { bathrooms = Float.parseFloat(item.getString()); } if (item.getFieldName().equals("squarefeet")) { squarefeet = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("description")) { description = item.getString(); } if (item.getFieldName().equals("lotsize")) { lotsize = item.getString(); } if (item.getFieldName().equals("garageId")) { garageId = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("garageSize")) { garageSize = Short.parseShort(item.getString()); } if (item.getFieldName().equals("price")) { price = Double.parseDouble(item.getString()); } if (item.getFieldName().equals("id")) { id = Integer.parseInt(item.getString()); } // if(item.getFieldName().equals("dateAdded")) // { // dateAdded = Date.valueOf(item.getString()); // } if (item.getFieldName().equals("photo")) { photo = item.getString(); } if (request.isUserInRole("admin")) { if (item.getFieldName().equals("agentId")) { agentId = Integer.parseInt(item.getString()); } } } } if (!ServletFileUpload.isMultipartContent(request) && id == 0) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } /////// String fileNameToLowerCase = fileNameExt.toLowerCase(); String fileExtension; if (fileNameToLowerCase.contains(".")) { fileExtension = fileNameToLowerCase.substring(fileNameToLowerCase.indexOf(".") + 1, fileNameToLowerCase.length()); } else { fileExtension = ""; } if (!fileExtension.equals("png") && !fileExtension.equals("jpg") && !fileExtension.equals("jpeg") && !fileExtension.equals("gif") && !fileExtension.equals("bmp") && id == 0) { PrintWriter writer = response.getWriter(); writer.println("Error: File must be one of the following formats only. (png,jpg,gif,bmp,jpeg)"); writer.flush(); return; } //////////////// String address = ""; //Setup new property Properties newProperty = new Properties(); newProperty.setStreet(street); newProperty.setCity(city); newProperty.setListingNum(listingNum); newProperty.setStyleId(styleId); newProperty.setTypeId(typeId); newProperty.setBedrooms(bedrooms); newProperty.setBathrooms(bathrooms); newProperty.setSquarefeet(squarefeet); newProperty.setDescription(description); newProperty.setLotsize(lotsize); newProperty.setGaragesize(garageSize); newProperty.setGarageId(garageId); newProperty.setAgentId(agentId); newProperty.setPrice(price); newProperty.setDateAdded(new java.sql.Date(System.currentTimeMillis())); if (id != 0) { if (fileExtension != "") { newProperty.setPhoto(id + "." + fileExtension); } newProperty.setListingNum(id); newProperty.setId(id); PropertiesDB.updateProperty(newProperty); } else { id = PropertiesDB.insertProperty(newProperty); newProperty.setPhoto(id + "." + fileExtension); newProperty.setListingNum(id); PropertiesDB.updateProperty(newProperty); } try { // parses the request's content to extract file data //@SuppressWarnings("unchecked") //List<FileItem> formItems = upload.parseRequest(request); if (formItems2 != null && formItems2.size() > 0) { // iterates over form's fields for (FileItem item : formItems2) { // processes only fields that are not form fields if (!item.isFormField()) { if (fileExtension != "") { String fileName = id + "." + fileExtension; String filePath = uploadPath + File.separator + "large" + File.separator + fileName; String filePathThumbnail = uploadPath + File.separator + "thumbnails" + File.separator + fileName; File storeFileThumbnail = new File(filePathThumbnail); File storeFile = new File(filePath); item.write(storeFile); //Thumnail library used for resizing of both images Thumbnails.of(storeFile).size(409, 307).toFile(storeFile);//Resize Main Image with current ratio maintained. (Required before using force size on larger images) Thumbnails.of(storeFile).forceSize(409, 307).toFile(storeFile);//Resize Main Image forcing size of 409x307 Thumbnails.of(storeFile).forceSize(75, 56).toFile(storeFileThumbnail);// create thumbnail of 75x56 request.setAttribute("Status", "This Property Has Been saved successfully!"); address = "ManagePropertys?GetProperties&Status=1"; } ////THIS IS HOW TO DELETE///// // storeFile.delete(); // storeFileThumbnail.delete(); ////THIS IS HOW TO DELETE///// } else { request.setAttribute("Status", "This Property Has Been Updated successfully!"); address = "ManagePropertys?GetProperties&Status=1"; } } } } catch (Exception ex) { address = "/Error.jsp"; } //end catch response.sendRedirect("/RealtyWebsite/" + address); // RequestDispatcher dispatcher = request.getRequestDispatcher(address); // dispatcher.forward(request, response); processRequest(request, response); }
From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {/*www .jav a 2s .c o m*/ throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:org.openqa.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {// w w w. jav a2 s . co m throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:com.pkrete.locationservice.admin.controller.mvc.TemplateController.java
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception, ServletException, IOException { /* Get the current user. */ Owner owner = UsersUtil.getUser(request, usersService).getOwner(); /* Model that is returned together with the view */ Map<String, Object> model = new HashMap<String, Object>(); // Currently selected language String lang = request.getParameter("select_lang"); // Currently selected template String template = request.getParameter("template"); // Id of the location that's used in template generation int locationId = this.converterService.strToInt(request.getParameter("location_id")); // Template name, if type is OTHER String otherName = request.getParameter("other_name"); // Include collection code to template's name if collection code exists String colCodeStr = request.getParameter("inc_col_code"); boolean incCollectionCode = (colCodeStr != null && colCodeStr.equalsIgnoreCase("true") ? true : false); // Current template name, used when renaming templates String templateOld = request.getParameter("template_old"); // Template type String templateType = request.getParameter("template_type"); // Currently selected stylesheet String stylesheet = request.getParameter("stylesheet"); // New stylesheet's name String stylesheetNew = request.getParameter("css_new"); // Currently selected JavaScript file String js = request.getParameter("js"); // New JavaScript file's name String jsNew = request.getParameter("js_new"); if (request.getParameter("btn_add_template") != null) { String templateNew = templatesService.buildTemplateName(locationId, otherName, incCollectionCode, TemplatesUtil.getTemplateType(templateType), owner); if (lang != null && !lang.isEmpty()) { if (TemplatesUtil.isTemplateNameValid(templateNew)) { if (!templatesService.exists(templateNew, lang, owner)) { if (templateOld.isEmpty()) { if (templatesService.create(templateNew, lang, owner)) { Object[] args = new Object[] { templateNew }; model.put("responseMsgTemplate", this.messageSource.getMessage("response.template.added", args, null)); } else { model.put("errorMsgTemplate", this.messageSource.getMessage("error.template.name.notvalid", null, null)); }//w w w. ja v a 2 s. c o m } else { if (templatesService.rename(templateOld, templateNew, lang, owner)) { Object[] args = new Object[] { templateOld, templateNew }; model.put("responseMsgTemplate", this.messageSource.getMessage("response.template.renamed", args, null)); } else { Object[] args = new Object[] { templateOld }; model.put("errorMsgTemplate", this.messageSource.getMessage("error.template.rename", args, null)); } } } else { model.put("errorMsgTemplate", this.messageSource.getMessage("error.template.exist", null, null)); } } else { model.put("errorMsgTemplate", this.messageSource.getMessage("error.template.name.notvalid", null, null)); } } else { model.put("errorMsgTemplate", this.messageSource.getMessage("error.template.no.lang", null, null)); } } else if (request.getParameter("btn_edit_template") != null) { return new ModelAndView( "redirect:edittemplate.htm?template=" + URLEncoder.encode(template, "UTF-8") + "&lang=" + lang); } else if (request.getParameter("btn_delete_template") != null) { if (templatesService.delete(template, lang, owner)) { Object[] args = new Object[] { template }; model.put("responseMsgTemplate", this.messageSource.getMessage("response.template.deleted", args, null)); } else { Object[] args = new Object[] { template }; model.put("errorMsgTemplate", this.messageSource.getMessage("error.template.delete", args, null)); } } else if (request.getParameter("btn_add_css") != null) { stylesheetNew += ".css"; if (CSSUtil.isCssNameValid(stylesheetNew)) { if (!cssService.exists(stylesheetNew, owner)) { if (cssService.create(stylesheetNew, owner)) { Object[] args = new Object[] { stylesheetNew }; model.put("responseMsgCss", this.messageSource.getMessage("response.css.added", args, null)); } else { model.put("errorMsgCss", this.messageSource.getMessage("error.css.name.notvalid", null, null)); } } else { model.put("errorMsgCss", this.messageSource.getMessage("error.css.exist", null, null)); } } else { model.put("errorMsgCss", this.messageSource.getMessage("error.css.name.notvalid", null, null)); } } else if (request.getParameter("btn_edit_css") != null) { return new ModelAndView("redirect:editcss.htm?stylesheet=" + stylesheet + "&lang=" + lang); } else if (request.getParameter("btn_delete_css") != null) { if (cssService.delete(stylesheet, owner)) { Object[] args = new Object[] { stylesheet }; model.put("responseMsgCss", this.messageSource.getMessage("response.css.deleted", args, null)); } else { Object[] args = new Object[] { stylesheet }; model.put("errorMsgCss", this.messageSource.getMessage("error.css.delete", args, null)); } } else if (request.getParameter("btn_edit_sys_css") != null) { return new ModelAndView("redirect:editcss.htm?lang=" + lang + "&sys=true&stylesheet=style.css"); } else if (request.getParameter("btn_edit_sys_template") != null) { return new ModelAndView("redirect:edittemplate.htm?template=template.txt&sys=true&lang=" + lang); } else if (request.getParameter("btn_add_js") != null) { jsNew += ".js"; if (JSUtil.isJsNameValid(jsNew)) { if (!jsService.exists(jsNew, owner)) { if (jsService.create(jsNew, owner)) { Object[] args = new Object[] { jsNew }; model.put("responseMsgJs", this.messageSource.getMessage("response.js.added", args, null)); } else { model.put("errorMsgJs", this.messageSource.getMessage("error.js.name.notvalid", null, null)); } } else { model.put("errorMsgJs", this.messageSource.getMessage("error.js.exist", null, null)); } } else { model.put("errorMsgJs", this.messageSource.getMessage("error.js.name.notvalid", null, null)); } } else if (request.getParameter("btn_edit_js") != null) { return new ModelAndView("redirect:editjs.htm?js=" + js + "&lang=" + lang); } else if (request.getParameter("btn_delete_js") != null) { if (jsService.delete(js, owner)) { Object[] args = new Object[] { js }; model.put("responseMsgJs", this.messageSource.getMessage("response.js.deleted", args, null)); } else { Object[] args = new Object[] { js }; model.put("errorMsgJs", this.messageSource.getMessage("error.js.delete", args, null)); } } List<Language> languages = owner.getLanguages(); if (lang != null) { model.put("templates", templatesService.getMap(lang, owner)); for (Language temp : languages) { if (temp.getCode().equals(lang)) { model.put("language", temp); break; } } } else if (!languages.isEmpty()) { model.put("templates", templatesService.getMap(languages.get(0).getCode(), owner)); model.put("language", languages.get(0)); } if (request.isUserInRole(UserGroup.ADMIN.toString())) { model.put("isAdmin", ""); } model.put("owner", owner.getCode()); model.put("locations", locationsService.getlLibraries(owner)); model.put("scripts", jsService.getList(owner)); model.put("stylesheets", cssService.getList(owner)); model.put("languages", languages); return new ModelAndView("template", "model", model); }