List of usage examples for javax.servlet.http HttpServletResponse SC_MOVED_PERMANENTLY
int SC_MOVED_PERMANENTLY
To view the source code for javax.servlet.http HttpServletResponse SC_MOVED_PERMANENTLY.
Click Source Link
From source file:org.j2free.util.ServletUtils.java
/** * /*from w ww. jav a2s . c om*/ * @param response * @param url */ public static void sendPermanentRedirect(HttpServletResponse response, String url) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", url); response.setHeader("Connection", "close"); }
From source file:com.zimbra.cs.dav.service.DavServlet.java
@Override public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ZimbraLog.clearContext();//from www. j a va 2 s.com addRemoteIpToLoggingContext(req); ZimbraLog.addUserAgentToContext(req.getHeader(DavProtocol.HEADER_USER_AGENT)); //bug fix - send 400 for Range requests String rangeHeader = req.getHeader(DavProtocol.HEADER_RANGE); if (null != rangeHeader) { sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Range header not supported", null, Level.debug); return; } RequestType rtype = getAllowedRequestType(req); ZimbraLog.dav.debug("Allowable request types %s", rtype); if (rtype == RequestType.none) { sendError(resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Not an allowed request type", null, Level.debug); return; } logRequestInfo(req); Account authUser = null; DavContext ctxt; try { AuthToken at = AuthProvider.getAuthToken(req, false); if (at != null && (at.isExpired() || !at.isRegistered())) { at = null; } if (at != null && (rtype == RequestType.both || rtype == RequestType.authtoken)) { authUser = Provisioning.getInstance().get(AccountBy.id, at.getAccountId()); } else if (at == null && (rtype == RequestType.both || rtype == RequestType.password)) { AuthUtil.AuthResult result = AuthUtil.basicAuthRequest(req, resp, true, this); if (result.sendErrorCalled) { logResponseInfo(resp); return; } authUser = result.authorizedAccount; } if (authUser == null) { try { sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed", null, Level.debug); } catch (Exception e) { } return; } ZimbraLog.addToContext(ZimbraLog.C_ANAME, authUser.getName()); ctxt = new DavContext(req, resp, authUser); } catch (AuthTokenException e) { sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e); return; } catch (ServiceException e) { sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e); return; } DavMethod method = sMethods.get(req.getMethod()); if (method == null) { setAllowHeader(resp); sendError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Not an allowed method", null, Level.debug); return; } long t0 = System.currentTimeMillis(); CacheStates cache = null; try { if (ZimbraLog.dav.isDebugEnabled()) { try { Upload upload = ctxt.getUpload(); if (upload.getSize() > 0 && upload.getContentType().startsWith("text")) { if (ZimbraLog.dav.isDebugEnabled()) { StringBuilder logMsg = new StringBuilder("REQUEST\n").append( new String(ByteUtil.readInput(upload.getInputStream(), -1, 20480), "UTF-8")); ZimbraLog.dav.debug(logMsg.toString()); } } } catch (DavException de) { throw de; } catch (Exception e) { ZimbraLog.dav.debug("ouch", e); } } cache = checkCachedResponse(ctxt, authUser); if (!ctxt.isResponseSent() && !isProxyRequest(ctxt, method)) { method.checkPrecondition(ctxt); method.handle(ctxt); method.checkPostcondition(ctxt); if (!ctxt.isResponseSent()) { resp.setStatus(ctxt.getStatus()); } } if (!ctxt.isResponseSent()) { logResponseInfo(resp); } } catch (DavException e) { if (e.getCause() instanceof MailServiceException.NoSuchItemException || e.getStatus() == HttpServletResponse.SC_NOT_FOUND) ZimbraLog.dav.info(ctxt.getUri() + " not found"); else if (e.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY || e.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY) ZimbraLog.dav.info("sending redirect"); try { if (e.isStatusSet()) { resp.setStatus(e.getStatus()); if (e.hasErrorMessage()) e.writeErrorMsg(resp.getOutputStream()); if (ZimbraLog.dav.isDebugEnabled()) { ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage(), e); } else { ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage()); } if (e.getCause() != null) ZimbraLog.dav.debug("exception: ", e.getCause()); } else { sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error handling method " + method.getName(), e); } } catch (IllegalStateException ise) { ZimbraLog.dav.debug("can't write error msg", ise); } } catch (ServiceException e) { if (e instanceof MailServiceException.NoSuchItemException) { sendError(resp, HttpServletResponse.SC_NOT_FOUND, ctxt.getUri() + " not found", null, Level.info); return; } sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error handling method " + method.getName(), e); } catch (Exception e) { try { sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error handling method " + method.getName(), e); } catch (Exception ex) { } } finally { long t1 = System.currentTimeMillis(); ZimbraLog.dav.info("DavServlet operation " + method.getName() + " to " + req.getPathInfo() + " (depth: " + ctxt.getDepth().name() + ") finished in " + (t1 - t0) + "ms"); if (cache != null) cacheCleanUp(ctxt, cache); ctxt.cleanup(); } }
From source file:org.apache.archiva.webdav.AbstractRepositoryServletTestCase.java
protected WebResponse getWebResponse(WebRequest webRequest) //, boolean followRedirect ) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI(webRequest.getUrl().getPath()); request.addHeader("User-Agent", "Apache Archiva unit test"); request.setMethod(webRequest.getHttpMethod().name()); if (webRequest.getHttpMethod() == HttpMethod.PUT) { PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast(webRequest); request.setContentType(putRequest.contentType); request.setContent(IOUtils.toByteArray(putRequest.inputStream)); }/*from w ww .j a va 2 s .co m*/ if (webRequest instanceof MkColMethodWebRequest) { request.setMethod("MKCOL"); } final MockHttpServletResponse response = execute(request); if (response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY) { String location = response.getHeader("Location"); log.debug("follow redirect to {}", location); return getWebResponse(new GetMethodWebRequest(location)); } return new WebResponse(null, null, 1) { @Override public String getContentAsString() { try { return response.getContentAsString(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } @Override public int getStatusCode() { return response.getStatus(); } @Override public String getResponseHeaderValue(String headerName) { return response.getHeader(headerName); } }; }
From source file:jeeves.server.dispatchers.ServiceManager.java
public void dispatch(ServiceRequest req, UserSession session) { ServiceContext context = new ServiceContext(req.getService(), monitorManager, providMan, profilMan, htContexts);/*from w ww. java 2s . c o m*/ context.setBaseUrl(baseUrl); context.setLanguage(req.getLanguage()); context.setUserSession(session); context.setIpAddress(req.getAddress()); context.setAppPath(appPath); context.setUploadDir(uploadDir); context.setMaxUploadSize(maxUploadSize); context.setInputMethod(req.getInputMethod()); context.setOutputMethod(req.getOutputMethod()); context.setHeaders(req.getHeaders()); context.setServlet(servlet); if (startupError) context.setStartupErrors(startupErrors); context.setAsThreadLocal(); //--- invoke service and build result Element response = null; ServiceInfo srvInfo = null; try { while (true) { String srvName = req.getService(); info("Dispatching : " + srvName); logParameters(req.getParams()); ArrayList<ServiceInfo> al = htServices.get(srvName); if (al == null) { error("Service not found : " + srvName); throw new ServiceNotFoundEx(srvName); } for (ServiceInfo si : al) { if (si.matches(req.getParams())) { srvInfo = si; break; } } if (srvInfo == null) { error("Service not matched in list : " + srvName); throw new ServiceNotMatchedEx(srvName); } //--------------------------------------------------------------------- //--- check access String profile = ProfileManager.GUEST; if (session.isAuthenticated()) profile = session.getProfile(); if (!profilMan.hasAccessTo(profile, srvName)) { error("Service not allowed : " + srvName); throw new ServiceNotAllowedEx(srvName); } TimerContext timerContext = monitorManager.getTimer(ServiceManagerServicesTimer.class).time(); try { // System.out.println(context.getResourceManager().hashCode() + "-THREAD-" + Thread.currentThread().getId() + "-" + Thread.currentThread().getName() + "-Start executing service:" + context.getService()); response = srvInfo.execServices(req.getParams(), context); // System.out.println(context.getResourceManager().hashCode() + "-THREAD-" + Thread.currentThread().getId() + "-" + Thread.currentThread().getName() + "-End executing service:" + context.getService()); } finally { timerContext.stop(); } //--------------------------------------------------------------------- //--- handle forward OutputPage outPage = srvInfo.findOutputPage(response); String forward = dispatchOutput(req, context, response, outPage, srvInfo.isCacheSet()); if (forward == null) { info(" -> dispatch ended for : " + srvName); return; } else { info(" -> forwarding to : " + forward); // Use servlet redirect for user.login and user.logout services. // TODO: Make redirect configurable for services in jeeves if (srvName.equals("metadata.quiet.delete") || srvName.equals("user.login") || srvName.equals("user.logout")) { HttpServiceRequest req2 = (HttpServiceRequest) req; req2.getHttpServletResponse().setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); req2.getHttpServletResponse().setHeader("Location", baseUrl + "/srv/" + req.getLanguage() + "/" + forward); return; } else { Element elForward = new Element(Jeeves.Elem.FORWARD); elForward.setAttribute(Jeeves.Attr.SERVICE, srvName); // --- send response to forwarded service request response.setName(Jeeves.Elem.REQUEST); response.addContent(elForward); context.setService(forward); req.setService(forward); req.setParams(response); } } } } catch (Throwable e) { handleError(req, response, context, srvInfo, e); } }
From source file:com.meltmedia.cadmium.servlets.BasicFileServlet.java
public static void sendPermanentRedirect(FileRequestContext context, String location) throws IOException { context.response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); context.response.setContentType(context.contentType); context.response.setHeader(LOCATION_HEADER, location); context.response.getOutputStream().close(); }
From source file:org.openhab.ui.cometvisu.internal.servlet.CometVisuServlet.java
/** * Process the actual request./* www . ja va 2 s. c o m*/ * * @param request * The request to be processed. * @param response * The response to be created. * @param content * Whether the request body should be written (GET) or not * (HEAD). * @throws IOException * If something fails at I/O level. * * @author BalusC * @link * http://balusc.blogspot.com/2009/02/fileservlet-supporting-resume-and * .html */ private void processStaticRequest(File file, HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file // ------------------------------------------------------------ if (file == null) { // Get requested file by path info. String requestedFile = request.getPathInfo(); // Check if file is actually supplied to the request URL. if (requestedFile == null) { // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning // page, or // just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // URL-decode the file name (might contain spaces and on) and // prepare // file object. file = new File(rootFolder, URLDecoder.decode(requestedFile, "UTF-8")); } if (file.equals(rootFolder) || (file.exists() && file.isDirectory())) { file = new File(file, "index.html"); } // Check if file actually exists in filesystem. if (!file.exists()) { // show installation hints if the CometVisu-Clients main index.html is requested but cannot be found if (file.getParentFile().equals(rootFolder) && (file.getName().equalsIgnoreCase("index.html") || file.getName().length() == 0)) { // looking for CometVisu clients index.html file String path = null; File folder = file.isDirectory() ? file : file.getParentFile(); if (folder.exists()) { File index = ClientInstaller.findClientRoot(folder, "index.html"); path = index.exists() ? index.getPath().replaceFirst(rootFolder.getPath() + "/", "") : null; } if (path != null) { // forward to position response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", path + "?" + request.getQueryString()); } else { showInstallationHint(request, response); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; // Validate request headers for caching // --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return // 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 // week. return; } // If-Modified-Since header should be greater than LastModified. If so, // then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 // week. return; } // Validate request headers for resume // ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If // not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range // ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, // then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required // in // 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then // LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws // IAE // if // invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte // range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following // examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 // (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then // return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required // in // 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response // -------------------------------------------------------- // Get content type by file name and set default GZIP support and // content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: // http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding // is supported by // the browser and expand content type with the one and right character // encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content // type is supported by // the browser, then set to inline, else attachment which will pop a // 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client // ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of // GZIP. // So only add it if there is no means of GZIP, else // browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println // methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every // range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); } }
From source file:org.opencms.util.CmsRequestUtil.java
/** * Redirects the response to the target link using a "301 - Moved Permanently" header.<p> * /* w w w. j a v a 2 s .c o m*/ * This implementation will work only on JSP pages in OpenCms that use the default JSP loader implementation.<p> * * @param jsp the OpenCms JSP context * @param target the target link */ public static void redirectPermanently(CmsJspActionElement jsp, String target) { String newTarget = OpenCms.getLinkManager().substituteLink(jsp.getCmsObject(), target, null, true); jsp.getRequest().setAttribute(CmsRequestUtil.ATTRIBUTE_ERRORCODE, new Integer(HttpServletResponse.SC_MOVED_PERMANENTLY)); jsp.getResponse().setHeader(HEADER_CONNECTION, "close"); try { jsp.getResponse().sendRedirect(newTarget); } catch (IOException e) { LOG.error(Messages.get().getBundle().key(Messages.ERR_IOERROR_0), e); // In case of an IOException, we send the redirect ourselves jsp.getResponse().setHeader(HEADER_LOCATION, newTarget); } }
From source file:nl.nn.adapterframework.http.HttpSender.java
public String extractResult(HttpMethod httpmethod, ParameterResolutionContext prc, HttpServletResponse response, String fileName) throws SenderException, IOException { int statusCode = httpmethod.getStatusCode(); boolean ok = false; if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey())) { prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode)); ok = true;/* w ww.j a v a2 s . c om*/ } else { if (statusCode == HttpServletResponse.SC_OK) { ok = true; } else { if (isIgnoreRedirects()) { if (statusCode == HttpServletResponse.SC_MOVED_PERMANENTLY || statusCode == HttpServletResponse.SC_MOVED_TEMPORARILY || statusCode == HttpServletResponse.SC_TEMPORARY_REDIRECT) { ok = true; } } } } if (!ok) { throw new SenderException(getLogPrefix() + "httpstatus " + statusCode + ": " + httpmethod.getStatusText() + " body: " + getResponseBodyAsString(httpmethod)); } if (response == null) { if (fileName == null) { if (isBase64()) { return getResponseBodyAsBase64(httpmethod); } else if (StringUtils.isNotEmpty(getStoreResultAsStreamInSessionKey())) { prc.getSession().put(getStoreResultAsStreamInSessionKey(), new ReleaseConnectionAfterReadInputStream(httpmethod, httpmethod.getResponseBodyAsStream())); return ""; } else if (StringUtils.isNotEmpty(getStoreResultAsByteArrayInSessionKey())) { InputStream is = httpmethod.getResponseBodyAsStream(); prc.getSession().put(getStoreResultAsByteArrayInSessionKey(), IOUtils.toByteArray(is)); return ""; } else if (isMultipartResponse()) { return handleMultipartResponse(httpmethod.getResponseHeader("Content-Type").getValue(), httpmethod.getResponseBodyAsStream(), prc, httpmethod); } else { //return httpmethod.getResponseBodyAsString(); return getResponseBodyAsString(httpmethod); } } else { InputStream is = httpmethod.getResponseBodyAsStream(); File file = new File(fileName); Misc.streamToFile(is, file); return fileName; } } else { streamResponseBody(httpmethod, response); return ""; } }
From source file:org.wyona.yanel.servlet.YanelServlet.java
/** * Check authorization and if not authorized then authenticate. Return null if authorization granted, otherwise return 401 and appropriate response such that client can provide credentials for authentication * * @return Null if access is granted and an authentication response if access is denied */// w w w . j a v a 2s . c o m private HttpServletResponse doAccessControl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // INFO: Get identity, realm, path Identity identity; Realm realm; String pathWithoutQS; try { realm = map.getRealm(request.getServletPath()); /* TBD: Check whether BASIC might be used and if so, then maybe handle things differently (also see https://github.com/wyona/yanel/issues/41) String authorizationHeader = request.getHeader("Authorization"); if (authorizationHeader != null) { if (authorizationHeader.toUpperCase().startsWith("BASIC")) { */ identity = getIdentityFromRequest(request, realm); //log.warn("DEBUG: Identity retrieved from request (for realm '" + realm.getID() + "'): " + identity); pathWithoutQS = map.getPath(realm, request.getServletPath()); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } // INFO: Try Auto-Login if (identity == null || (identity != null && identity.isWorld())) { //log.debug("Not logged in yet, hence try auto login..."); try { if (AutoLogin.tryAutoLogin(request, response, realm)) { log.debug("Auto login successful, hence set identity inside session..."); String username = AutoLogin.getUsername(request); if (username != null) { User user = realm.getIdentityManager().getUserManager().getUser(username); setIdentity(new Identity(user, user.getEmail()), request.getSession(), realm); } else { log.error("Auto login successful, but no username available!"); } } else { //log.debug("No auto login."); } } catch (Exception e) { log.error(e, e); } } // INFO: Check Authorization boolean authorized = false; Usecase usecase = getUsecase(request); try { if (log.isDebugEnabled()) log.debug("Check authorization: realm: " + realm + ", path: " + pathWithoutQS + ", identity: " + identity + ", Usecase: " + usecase.getName()); authorized = realm.getPolicyManager().authorize(pathWithoutQS, request.getQueryString(), identity, usecase); if (log.isDebugEnabled()) log.debug("Check authorization result: " + authorized); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } if (authorized) { if (identity != null && identity.getUsername() != null) { if (identity.getUsername() != null) { if (log.isDebugEnabled()) log.debug("Access for user '" + identity.getUsername() + "' granted: " + getRequestURLQS(request, null, false)); //response.setHeader("Cache-control", "no-cache"); // INFO: Do not allow browsers to cache content for users which are signed in, but we currently do not use this because of performance reasons. One can set the resource property 'yanel:no-cache' on specific pages though in order to prevent caching of protected pages. Related to this see how a timestamp is appened during logout (see doLogout()) } else { if (log.isDebugEnabled()) log.debug("Access for anonymous user (aka WORLD) granted: " + getRequestURLQS(request, null, false)); } } else { if (log.isDebugEnabled()) log.debug("Access for anonymous user (aka WORLD) granted: " + getRequestURLQS(request, null, false)); } return null; // INFO: Return null in order to indicate that access is granted } else { log.warn("Access denied: " + getRequestURLQS(request, null, false) + " (Path of request: " + pathWithoutQS + "; Identity: " + identity + "; Usecase: " + usecase + ")"); // TODO: Implement HTTP BASIC/DIGEST response (see above) // INFO: If request is not via SSL and SSL is configured, then redirect to SSL connection. if (!request.isSecure()) { if (sslPort != null) { log.info("Redirect to SSL ..."); try { URL url = new URL(getRequestURLQS(request, null, false).toString()); url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); if (realm.isProxySet()) { if (realm.getProxySSLPort() >= 0) { log.debug("Use configured port: " + realm.getProxySSLPort()); url = new URL(url.getProtocol(), url.getHost(), new Integer(realm.getProxySSLPort()).intValue(), url.getFile()); } else { log.debug("Use default port: " + url.getDefaultPort()); // NOTE: getDefaultPort depends on the Protocol (e.g. https is 443) url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } } log.info("Redirect to SSL: " + url); response.setHeader("Location", url.toString()); // TODO: Yulup has a bug re TEMPORARY_REDIRECT //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); return response; } catch (Exception e) { log.error(e.getMessage(), e); } } else { log.warn("SSL does not seem to be configured!"); } } else { log.info("This connection is already via SSL."); } if (doAuthenticate(request, response) != null) { log.info( "Access denied and not authenticated correctly yet, hence return response of web authenticator..."); /* NOTE: Such a response can have different reasons: - Either no credentials provided yet and web authenticator is generating a response to fetch credentials - Or authentication failed and web authenticator is resending response to fetch again credentials"); - Or authentication was successful and web authenticator sends a redirect */ // TODO: Check "would be mime type", etc.: if (logAccessIsApplicable(view.getMimeType())) { if (logAccessEnabled) { // INFO: Although authorization has been denied and user first needs to authenticate, let's log the request anyway if (usecase != null && usecase.getName().equals("introspection")) { log.debug("Ignore introspection request: " + getRequestURLQS(request, null, false)); } else { log.info("Access denied and authentication not completed yet, hence let's log request '" + getRequestURLQS(request, null, false) + "'"); doLogAccess(request, response, HttpServletResponse.SC_UNAUTHORIZED, null, null); } } //log.debug("Returned status code: " + response.getStatus()); // INFO: Only supported by servlet api 3.0 and higher return response; } else { try { //log.debug("Authentication was successful for user: " + getIdentity(request, map).getUsername()); } catch (Exception e) { log.error(e.getMessage(), e); } URL url = new URL(getRequestURLQS(request, null, false).toString()); if (sslPort != null) { url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); } // INFO: Hash fragment is set by login screen, e.g. src/resources/login/htdocs/login-screen.xsl String hashFragment = request.getParameter("yanel.login.hash.fragment"); if (hashFragment != null && hashFragment.length() > 0) { log.debug("Hash fragment: " + hashFragment); url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + "#" + hashFragment); } log.warn("DEBUG: Redirect to original request: " + url); //response.sendRedirect(url.toString()); // 302 // TODO: Yulup has a bug re TEMPORARY_REDIRECT (or is the problem that the load balancer is rewritting 302 reponses?!) response.setHeader("Location", url.toString()); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); // 301 //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); // 302 return response; } } }