List of usage examples for javax.servlet.http Cookie setComment
public void setComment(String purpose)
From source file:com.tremolosecurity.proxy.filter.PostProcess.java
protected void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpResponse response, String finalURL, HttpFilterChain curChain, HttpRequestBase httpRequest) throws IOException, Exception { boolean isText; HttpEntity entity = null;/*from w ww .jav a 2 s . co m*/ try { entity = response.getEntity(); /*if (entity != null) { entity = new BufferedHttpEntity(entity); }*/ } catch (Throwable t) { throw new Exception(t); } InputStream ins = null; boolean entExists = false; if (entity == null) { resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); ins = new StringBufferInputStream(""); } else { try { ins = entity.getContent(); resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); entExists = true; } catch (IllegalStateException e) { //do nothing } } if (entExists) { org.apache.http.Header hdr = response.getFirstHeader("Content-Type"); org.apache.http.Header encoding = response.getFirstHeader("Content-Encoding"); /*if (hdr == null) { isText = false; } else { isText = response.getFirstHeader("Content-Type").getValue().startsWith("text"); if (encoding != null ) { isText = (! encoding.getValue().startsWith("gzip")) && (! encoding.getValue().startsWith("deflate")); } if (isText) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); resp.setLocale(response.getLocale()); } }*/ isText = false; try { resp.setCharacterEncoding(null); } catch (Throwable t) { //we're not doing anything } StringBuffer stmp = new StringBuffer(); if (response.getFirstHeader("Content-Type") != null) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); } if (response.getLocale() != null) { resp.setLocale(response.getLocale()); } org.apache.http.Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { org.apache.http.Header header = headers[i]; if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Length")) { if (!header.getValue().equals("0")) { continue; } } else if (header.getName().equals("Transfer-Encoding")) { continue; } else if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) { //System.out.println(header.getValue()); String cookieVal = header.getValue(); /*if (cookieVal.endsWith("HttpOnly")) { cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly")); } //System.out.println(cookieVal);*/ List<HttpCookie> cookies = HttpCookie.parse(cookieVal); Iterator<HttpCookie> it = cookies.iterator(); while (it.hasNext()) { HttpCookie cookie = it.next(); String cookieFinalName = cookie.getName(); if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) { stmp.setLength(0); stmp.append("JSESSIONID").append('-') .append(holder.getApp().getName().replaceAll(" ", "|")); cookieFinalName = stmp.toString(); } Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue()); respcookie.setComment(cookie.getComment()); if (cookie.getDomain() != null) { respcookie.setDomain(cookie.getDomain()); } if (cookie.hasExpired()) { respcookie.setMaxAge(0); } else { respcookie.setMaxAge((int) cookie.getMaxAge()); } respcookie.setPath(cookie.getPath()); respcookie.setSecure(cookie.getSecure()); respcookie.setVersion(cookie.getVersion()); resp.addCookie(respcookie); } } else if (header.getName().equals("Location")) { if (holder.isOverrideHost()) { fixRedirect(req, resp, finalURL, header); } else { resp.addHeader("Location", header.getValue()); } } else { resp.addHeader(header.getName(), header.getValue()); } } curChain.setIns(ins); curChain.setText(isText); curChain.setEntity(entity); curChain.setHttpRequestBase(httpRequest); //procData(req, resp, holder, isText, entity, ins); } else { isText = false; } }
From source file:cn.tiup.httpproxy.ProxyServlet.java
/** Copy cookie from the proxy to the servlet client. * Replaces cookie path to local path and renames cookie to avoid collisions. *///from www .jav a 2 s. c o m protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String headerValue) { List<HttpCookie> cookies = HttpCookie.parse(headerValue); for (HttpCookie cookie : cookies) { //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = getCookieNamePrefix(cookie.getName()) + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(cookie.getPath()); //set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. * Replaces cookie path to local path and renames cookie to avoid collisions. */// ww w . jav a 2s. c om protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String header) { List<HttpCookie> cookies = HttpCookie.parse(header); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (HttpCookie cookie : cookies) { //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = getCookieNamePrefix() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); //set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:com.fuseim.webapp.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and * renames cookie to avoid collisions.// www . java2 s. com */ protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String headerValue) { List<HttpCookie> cookies = HttpCookie.parse(headerValue); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (HttpCookie cookie : cookies) { //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = doPreserveCookies ? cookie.getName() : getCookieNamePrefix(cookie.getName()) + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); //set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to * local path and renames cookie to avoid collisions. *//*from w ww . j a va 2 s.co m*/ protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) { List<HttpCookie> cookies = HttpCookie.parse(header.getValue()); String path = getServletContext().getServletContextName(); if (path == null) { path = ""; } path += servletRequest.getServletPath(); for (HttpCookie cookie : cookies) { // set cookie name prefixed w/ a proxy value so it won't collide w/ // other cookies String proxyCookieName = getCookieNamePrefix() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); // set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
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 {/*from ww w.jav a 2s . com*/ 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:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java
private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) { notNull(path, "Path"); if (requestBody != null && !multiParts.isEmpty()) { throw new IllegalStateException( "You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?"); }//ww w . j av a2s . co m String baseUri; if (isNotBlank(basePath)) { baseUri = mergeAndRemoveDoubleSlash(basePath, path); } else { baseUri = path; } final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri); if (!queryParams.isEmpty()) { new ParamApplier(queryParams) { @Override protected void applyParam(String paramName, String[] paramValues) { uriComponentsBuilder.queryParam(paramName, paramValues); } }.applyParams(); } String uri = uriComponentsBuilder.build().toUriString(); final MockHttpServletRequestBuilder request; if (multiParts.isEmpty()) { request = MockMvcRequestBuilders.request(method, uri, pathParams); } else if (method != POST) { throw new IllegalArgumentException("Currently multi-part file data uploading only works for " + POST); } else { request = MockMvcRequestBuilders.fileUpload(uri, pathParams); } String requestContentType = findContentType(); if (!params.isEmpty()) { new ParamApplier(params) { @Override protected void applyParam(String paramName, String[] paramValues) { request.param(paramName, paramValues); } }.applyParams(); if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) { setContentTypeToApplicationFormUrlEncoded(request); } } if (!formParams.isEmpty()) { if (method == GET) { throw new IllegalArgumentException("Cannot use form parameters in a GET request"); } new ParamApplier(formParams) { @Override protected void applyParam(String paramName, String[] paramValues) { request.param(paramName, paramValues); } }.applyParams(); boolean isInMultiPartMode = isInMultiPartMode(request); if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) { setContentTypeToApplicationFormUrlEncoded(request); } } if (!attributes.isEmpty()) { new ParamApplier(attributes) { @Override protected void applyParam(String paramName, String[] paramValues) { request.requestAttr(paramName, paramValues[0]); } }.applyParams(); } if (RestDocsClassPathChecker.isSpringRestDocsInClasspath() && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) { request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri)); } if (StringUtils.isNotBlank(requestContentType)) { request.contentType(MediaType.parseMediaType(requestContentType)); } if (headers.exist()) { for (Header header : headers) { request.header(header.getName(), header.getValue()); } } if (cookies.exist()) { for (Cookie cookie : cookies) { javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); if (cookie.hasComment()) { servletCookie.setComment(cookie.getComment()); } if (cookie.hasDomain()) { servletCookie.setDomain(cookie.getDomain()); } if (cookie.hasMaxAge()) { servletCookie.setMaxAge(cookie.getMaxAge()); } if (cookie.hasPath()) { servletCookie.setPath(cookie.getPath()); } if (cookie.hasVersion()) { servletCookie.setVersion(cookie.getVersion()); } servletCookie.setSecure(cookie.isSecured()); request.cookie(servletCookie); } } if (!sessionAttributes.isEmpty()) { request.sessionAttrs(sessionAttributes); } if (!multiParts.isEmpty()) { MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request; for (MockMvcMultiPart multiPart : multiParts) { MockMultipartFile multipartFile; String fileName = multiPart.getFileName(); String controlName = multiPart.getControlName(); String mimeType = multiPart.getMimeType(); if (multiPart.isByteArray()) { multipartFile = new MockMultipartFile(controlName, fileName, mimeType, (byte[]) multiPart.getContent()); } else if (multiPart.isFile() || multiPart.isInputStream()) { InputStream inputStream; if (multiPart.isFile()) { try { inputStream = new FileInputStream((File) multiPart.getContent()); } catch (FileNotFoundException e) { return SafeExceptionRethrower.safeRethrow(e); } } else { inputStream = (InputStream) multiPart.getContent(); } try { multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream); } catch (IOException e) { return SafeExceptionRethrower.safeRethrow(e); } } else { // String multipartFile = new MockMultipartFile(controlName, fileName, mimeType, ((String) multiPart.getContent()).getBytes()); } multiPartRequest.file(multipartFile); } } if (requestBody != null) { if (requestBody instanceof byte[]) { request.content((byte[]) requestBody); } else if (requestBody instanceof File) { byte[] bytes = toByteArray((File) requestBody); request.content(bytes); } else { request.content(requestBody.toString()); } } logRequestIfApplicable(method, baseUri, path, pathParams); return performRequest(request); }
From source file:org.apache.jetspeed.modules.actions.JLoginUser.java
public void doPerform(RunData rundata) throws Exception { JetspeedRunData data = (JetspeedRunData) rundata; String username = data.getParameters().getString("username", ""); String password = data.getParameters().getString("password", ""); boolean newUserApproval = JetspeedResources.getBoolean("newuser.approval.enable", false); String secretkey = (String) data.getParameters().getString("secretkey", null); if (secretkey != null) { // its the first logon - we are verifying the secretkey // handle the buttons on the ConfirmRegistration page String button1 = data.getParameters().getString("submit1", null); if (button1 != null && button1.equalsIgnoreCase("Cancel")) { data.setScreenTemplate(TurbineTemplate.getDefaultScreen()); return; }/*from w w w . j av a 2 s . c om*/ // check to make sure the user entered the right confirmation key // if not, then send them to the ConfirmRegistration screen JetspeedUser user = JetspeedSecurity.getUser(username); if (user == null) { logger.warn("JLogin User: Unexpected condition : user is NULL"); return; } String confirm_value = user.getConfirmed(); if (!secretkey.equals(confirm_value) && !confirm_value.equals(JetspeedResources.CONFIRM_VALUE)) { if (newUserApproval) { data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID")); data.setScreenTemplate("NewUserAwaitingAcceptance"); return; } else { if (user.getConfirmed().equals(JetspeedResources.CONFIRM_VALUE_REJECTED)) { data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID")); data.setScreenTemplate("NewUserRejected"); return; } else { data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID")); data.setScreenTemplate("ConfirmRegistration"); return; } } } user.setConfirmed(JetspeedResources.CONFIRM_VALUE); data.setMessage(Localization.getString(rundata, "JLOGINUSER_WELCOME")); JetspeedSecurity.saveUser(user); } JetspeedUser user = null; try { user = JetspeedSecurity.login(username, password); JetspeedSecurity.saveUser(user); } catch (LoginException e) { data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_LOGIN)); String message = e.getMessage() != null ? e.getMessage() : e.toString(); data.setMessage(message); data.setUser(JetspeedSecurity.getAnonymousUser()); data.getUser().setHasLoggedIn(new Boolean(false)); if (e instanceof FailedLoginException) { if (!disableCheck(data)) { logger.info("JLoginUser: Credential Failure on login for user: " + username); data.setMessage(Localization.getString(rundata, "PASSWORDFORM_FAILED_MSG")); } } else if (e instanceof AccountExpiredException) { logger.info("JLoginUser: Account Expired for user " + username); } else if (e instanceof CredentialExpiredException) { logger.info("JLoginUser: Credentials expired for user: " + username); data.setScreenTemplate( JetspeedResources.getString(JetspeedResources.CHANGE_PASSWORD_TEMPLATE, "ChangePassword")); data.setMessage(Localization.getString(rundata, "PASSWORDFORM_EXPIRED_MSG")); data.getParameters().setString("username", username); } return; } catch (Throwable other) { data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_ERROR)); String message = other.getMessage() != null ? other.getMessage() : other.toString(); data.setMessage(message); data.setStackTrace(org.apache.turbine.util.StringUtils.stackTrace(other), other); JetspeedUser juser = new FakeJetspeedUser(JetspeedSecurity.getAnonymousUserName(), false); data.setUser(juser); return; } if ("T".equals(user.getDisabled())) { data.setMessage(Localization.getString(rundata, "JLOGINUSER_ACCOUNT_DISABLED")); data.setScreenTemplate(JetspeedResources.getString("logon.disabled.form")); data.getUser().setHasLoggedIn(new Boolean(false)); return; } // check for being confirmed before allowing someone to finish logging in if (data.getUser().hasLoggedIn()) { if (JetspeedSecurity.isDisableAccountCheckEnabled()) { // dst: this needs some refactoring. I don't believe this api is necessary JetspeedSecurity.resetDisableAccountCheck(data.getParameters().getString("username", "")); } String confirmed = data.getUser().getConfirmed(); if (confirmed == null || !confirmed.equals(JetspeedResources.CONFIRM_VALUE)) { if (confirmed != null && confirmed.equals(JetspeedResources.CONFIRM_VALUE_REJECTED)) { data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID")); data.setScreenTemplate("NewUserRejected"); data.getUser().setHasLoggedIn(new Boolean(false)); return; } else { data.setMessage(Localization.getString(rundata, "JLOGINUSER_CONFIRMFIRST")); data.setScreenTemplate("ConfirmRegistration"); data.getUser().setHasLoggedIn(new Boolean(false)); return; } } // user has logged in successfully at this point boolean automaticLogonEnabled = JetspeedResources.getBoolean("automatic.logon.enable", false); if (automaticLogonEnabled) { //Does the user want to use this facility? boolean userRequestsRememberMe = data.getParameters().getBoolean("rememberme", false); if (userRequestsRememberMe) { //save cookies on the users machine. int maxage = JetspeedResources.getInt("automatic.logon.cookie.maxage", -1); String comment = JetspeedResources.getString("automatic.logon.cookie.comment", ""); String domain = JetspeedResources.getString("automatic.logon.cookie.domain"); String path = JetspeedResources.getString("automatic.logon.cookie.path", "/"); if (domain == null) { String server = data.getServerName(); domain = "." + server; } String loginCookieValue = null; if (JetspeedResources.getString("automatic.logon.cookie.generation", "everylogon") .equals("everylogon")) { loginCookieValue = "" + Math.random(); data.getUser().setPerm("logincookie", loginCookieValue); JetspeedSecurity.saveUser(data.getJetspeedUser()); } else { loginCookieValue = (String) data.getUser().getPerm("logincookie"); if (loginCookieValue == null || loginCookieValue.length() == 0) { loginCookieValue = "" + Math.random(); data.getUser().setPerm("logincookie", loginCookieValue); JetspeedSecurity.saveUser(data.getJetspeedUser()); } } Cookie userName = new Cookie("username", data.getUser().getUserName()); Cookie loginCookie = new Cookie("logincookie", loginCookieValue); userName.setMaxAge(maxage); userName.setComment(comment); userName.setDomain(domain); userName.setPath(path); loginCookie.setMaxAge(maxage); loginCookie.setComment(comment); loginCookie.setDomain(domain); loginCookie.setPath(path); data.getResponse().addCookie(userName); data.getResponse().addCookie(loginCookie); } } } else { disableCheck(data); } }