List of usage examples for javax.servlet.http HttpServletResponse flushBuffer
public void flushBuffer() throws IOException;
From source file:io.wittmann.jiralist.servlet.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//* w w w .j a va 2s . co m*/ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { long requestId = requestCounter++; String proxyTo = "https://issues.jboss.org/rest/api/2"; if (req.getHeader("X-Proxy-To") != null) { proxyTo = req.getHeader("X-Proxy-To"); } String url = proxyTo + req.getPathInfo(); if (req.getQueryString() != null) { url += "?" + req.getQueryString(); } System.out.println("[" + requestId + "]: Proxying to: " + url); boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put"); URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); if (isWrite) { remoteConn.setDoOutput(true); } remoteConn.setRequestMethod(req.getMethod()); String auth = req.getHeader("Authorization"); if (auth != null) { remoteConn.setRequestProperty("Authorization", auth); } String ct = req.getHeader("Content-Type"); if (ct != null) { remoteConn.setRequestProperty("Content-Type", ct); } String cl = req.getHeader("Content-Length"); if (cl != null) { remoteConn.setRequestProperty("Content-Length", cl); } String accept = req.getHeader("Accept"); if (accept != null) { remoteConn.setRequestProperty("Accept", accept); } System.out.println("[" + requestId + "]: Request Info:"); System.out.println("[" + requestId + "]: Method: " + req.getMethod()); System.out.println("[" + requestId + "]: Has auth: " + (auth != null)); System.out.println("[" + requestId + "]: Content-Type: " + ct); System.out.println("[" + requestId + "]: Content-Length: " + cl); if (isWrite) { InputStream requestIS = null; OutputStream remoteOS = null; try { requestIS = req.getInputStream(); remoteOS = remoteConn.getOutputStream(); IOUtils.copy(requestIS, remoteOS); remoteOS.flush(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); return; } finally { IOUtils.closeQuietly(requestIS); IOUtils.closeQuietly(remoteOS); } } InputStream remoteIS = null; OutputStream responseOS = null; int responseCode = remoteConn.getResponseCode(); System.out.println("[" + requestId + "]: Response Info:"); System.out.println("[" + requestId + "]: Code: " + responseCode); if (responseCode == 400) { remoteIS = remoteConn.getInputStream(); responseOS = System.out; IOUtils.copy(remoteIS, responseOS); IOUtils.closeQuietly(remoteIS); resp.sendError(400, "Error 400"); } else { try { Map<String, List<String>> headerFields = remoteConn.getHeaderFields(); for (String headerName : headerFields.keySet()) { if (headerName == null) { continue; } if (EXCLUDE_HEADERS.contains(headerName)) { continue; } String headerValue = remoteConn.getHeaderField(headerName); resp.setHeader(headerName, headerValue); System.out.println("[" + requestId + "]: " + headerName + " : " + headerValue); } resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); int bytesCopied = IOUtils.copy(remoteIS, responseOS); System.out.println("[" + requestId + "]: Bytes Proxied: " + bytesCopied); resp.flushBuffer(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } } }
From source file:org.jasig.cas.support.pac4j.web.flow.ClientBackChannelAction.java
/** * logout POST from remote server (server-->server) * CAS: post logout from server is mapped to /login?clientname= (here) * SAML: post logout from server is mapped to /logout?action=SingleLogout (logout webflow) */// w ww.ja va 2 s .com @Override protected Event doExecute(final RequestContext context) throws Exception { final HttpServletRequest request = WebUtils.getHttpServletRequest(context); final HttpServletResponse response = WebUtils.getHttpServletResponse(context); final WebContext webContext = new J2EContext(request, response); log(request); String clientName = request.getParameter("client_name"); if (clientName == null) { clientName = (String) request.getAttribute("client_name"); } Object client = null; if (StringUtils.isNotBlank(clientName)) { // get pac4j client client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName); if (client instanceof Saml2ClientWrapper) { //do nothing: works with the slo logout mapped saml service on logout?action=SingleLogout return success(); } if (client instanceof CasClientWrapper) { CasClientWrapper clientWrapper = (CasClientWrapper) client; //remote cas ClientBackChannelAction if (CasClientWrapper.isLogoutRequest(request)) { final String token = CasClientWrapper.getST(request); logger.debug("destroy TGT with an external ST: " + token); if (CommonUtils.isNotBlank(token)) { Collection<Ticket> ticketCollection = this.ticketRegistry.getTickets(); logger.debug("CAS ticketCollection.size: " + ticketCollection.size()); for (Ticket ticket : ticketCollection) { if (ticket instanceof TicketGrantingTicket) { TicketGrantingTicket ticketGrantingTicket = (TicketGrantingTicket) ticket; String tgtId = ticketGrantingTicket.getId(); logger.debug("check for ticket.id: " + tgtId); org.jasig.cas.authentication.Authentication authentication = ticketGrantingTicket .getAuthentication(); if (authentication != null) { String clientNameStored = authentication.getAttributes().get("clientName") .toString(); if (clientNameStored.equals(clientName)) { logger.debug("client confirmed: " + clientName); //get external auth org.springframework.security.core.Authentication externalAuth = null; externalAuth = (org.springframework.security.core.Authentication) ClientLogoutAction .getExtAuthentication(authentication); if (externalAuth != null) { String extCredentials = (String) externalAuth.getCredentials(); if (extCredentials.equals(token)) { logger.debug("token confirmed for tgtId: " + tgtId); //should do some LT validation from remote server ? //destroy the TGT and all his ST !!! NOT WORKING List<LogoutRequest> logoutRequests = this.centralAuthenticationService .destroyTicketGrantingTicket(tgtId); //reply logger.debug("... stop flow and respond to remote server"); webContext.setResponseStatus(HttpConstants.OK); webContext.writeResponseContent( token + " was authenticated with tgtId: " + tgtId); response.flushBuffer(); final ExternalContext externalContext = ExternalContextHolder .getExternalContext(); externalContext.recordResponseComplete(); return new Event(this, "stop"); } } } } } } //not authenticated token webContext.setResponseStatus(HttpConstants.OK); webContext.writeResponseContent(token + " was not authenticated"); response.flushBuffer(); final ExternalContext externalContext = ExternalContextHolder.getExternalContext(); externalContext.recordResponseComplete(); return new Event(this, "stop"); } } } } return success(); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.ViewAllRoomsSchedulesDA.java
public ActionForward downloadShiftAttendence(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final ExecutionSemester executionSemester = getExecutionSemester(request); final String executionYear = executionSemester.getExecutionYear().getYear(); final Spreadsheet spreadsheet = new Spreadsheet("ShiftAttendenceMap"); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionCourse")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionDegree")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift.schedule")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.lesson.room")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.number.students.enrolled")); for (final ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) { final StringBuilder executionDegreeBuilder = new StringBuilder(); for (final ExecutionDegree executionDegree : executionCourse.getExecutionDegrees()) { if (executionDegreeBuilder.length() > 0) { executionDegreeBuilder.append("\n"); }/*from w w w .j av a2 s . c om*/ executionDegreeBuilder.append(executionDegree.getDegree().getSigla()); } final StringBuilder emailBuilder = new StringBuilder(); for (final Professorship professorship : executionCourse.getProfessorshipsSet()) { if (emailBuilder.length() > 0) { emailBuilder.append("\n"); } emailBuilder.append(professorship.getPerson().getEmailForSendingEmails()); } for (final CourseLoad courseLoad : executionCourse.getCourseLoadsSet()) { for (final Shift shift : courseLoad.getShiftsSet()) { final Row row = spreadsheet.addRow(); final StringBuilder roomBuilder = new StringBuilder(); final StringBuilder scheduleBuilder = new StringBuilder(); if (!shift.getAssociatedLessonsSet().isEmpty()) { for (Iterator<Lesson> iterator = shift.getAssociatedLessonsSet().iterator(); iterator .hasNext();) { Lesson lesson = iterator.next(); scheduleBuilder.append(WeekDay.getWeekDay(lesson.getDiaSemana()).getLabelShort()); scheduleBuilder.append(" "); scheduleBuilder.append(lesson.getBeginHourMinuteSecond().toString("HH:mm")); scheduleBuilder.append(" - "); scheduleBuilder.append(lesson.getEndHourMinuteSecond().toString("HH:mm")); if (lesson.hasSala()) { roomBuilder.append(lesson.getSala().getName()); } if (iterator.hasNext()) { scheduleBuilder.append(" ; "); roomBuilder.append(" ; "); } } } row.setCell(shift.getNome()); row.setCell(executionCourse.getName()); row.setCell(executionDegreeBuilder.toString()); row.setCell(scheduleBuilder.toString().replace(';', '\n')); row.setCell(roomBuilder.toString().replace(';', '\n')); row.setCell(shift.getStudentsSet().size()); } } } response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=shiftAttendenceMap" + executionYear.replace('/', '_') + "_" + executionSemester.getSemester() + ".xls"); final ServletOutputStream writer = response.getOutputStream(); spreadsheet.exportToXLSSheet(writer); writer.flush(); response.flushBuffer(); return null; }
From source file:com.rr.wabshs.ui.reports.reportController.java
@RequestMapping(value = "/DLReport", method = { RequestMethod.GET }) public void DLReport(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletResponse response) throws Exception { Integer reportRequestId = 0;/*from ww w .j a va2 s. c om*/ reportView rv = new reportView(); boolean canViewReport = false; if (session.getAttribute("userDetails") != null) { User userDetails = (User) session.getAttribute("userDetails"); //1 decrpt and get the reportId decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); reportRequestId = Integer.parseInt(result[0].substring(4)); rv.setReportRequestId(reportRequestId); rv.setReportAction("Accessed report link"); rv.setSystemUserId(userDetails.getId()); reportmanager.saveReportView(rv); //now we get the report details reportRequest rr = reportmanager.getReportRequestById(reportRequestId); if (rr != null) { //we check permission and program if (userDetails.getRoleId() == 3 && rr.getSystemUserId() == userDetails.getId() && rr.getProgramId() == programId) { canViewReport = true; } else if (userDetails.getRoleId() != 3 && rr.getProgramId() == programId) { canViewReport = true; } } //we log them, grab report for them to download //if report doesn't exist we send them back to list with a message if (!canViewReport) { rv = new reportView(); rv.setReportRequestId(reportRequestId); rv.setSystemUserId(userDetails.getId()); rv.setReportAction("User does not have permission to view report"); reportmanager.saveReportView(rv); throw new Exception("user does not have permission - " + reportRequestId); } else { //generate the report for user to download //need to get report path String filePath = reportmanager.getReportPath(programId); String fileName = rr.getReportFileName(); try { File f = new File(filePath + fileName); if (!f.exists()) { throw new Exception("Error with File " + filePath + fileName); } } catch (Exception e) { try { //update file to error rr.setStatusId(5); reportmanager.updateReportRequest(rr); throw new Exception("File does not exists " + filePath + fileName); } catch (Exception ex1) { throw new Exception("File does not exists " + filePath + fileName + ex1); } } try { // get your file as InputStream InputStream is = new FileInputStream(filePath + fileName); // copy it to response's OutputStream /** //change report name SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HHmmss"); Date currentDate = new Date(); String formattedDateasString = df.format(currentDate.getTime()); //get extension int iDot = fileName.lastIndexOf("."); String fileExt = fileName.substring(iDot); String dlFileName = formattedDateasString+ fileExt; **/ String mimeType = "application/octet-stream"; response.setContentType(mimeType); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); org.apache.commons.io.IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); is.close(); rv = new reportView(); rv.setSystemUserId(userDetails.getId()); rv.setReportRequestId(reportRequestId); rv.setReportAction("Viewed Report"); reportmanager.saveReportView(rv); //update status if (rr.getStatusId() == 3) { rr.setStatusId(4); reportmanager.updateReportRequest(rr); } } catch (IOException ex) { ex.printStackTrace(); System.out.println("Error writing file to output stream. Filename was '{}'" + fileName + ex); try { //update file to error rr.setStatusId(5); reportmanager.updateReportRequest(rr); throw new Exception("Error with File " + filePath + fileName + ex); } catch (Exception e) { throw new Exception("Error with File " + filePath + fileName + ex); } } } } else { //someone somehow got to this link, we just log //we log who is accessing //now we have report id, we check to see which program it belongs to and if the user has permission rv.setReportRequestId(reportRequestId); rv.setReportAction("Accessed report link - no user session found"); reportmanager.saveReportView(rv); throw new Exception("invalid report download - " + reportRequestId); } }
From source file:org.bonitasoft.console.common.server.servlet.ResourceServlet.java
/** * Get resource file/* www . jav a 2s .c om*/ * * @param request * @param response * @param resourceName * @param fileName * @throws ServletException * @throws UnsupportedEncodingException */ protected void getResourceFile(final HttpServletRequest request, final HttpServletResponse response, String resourceName, String fileName) throws ServletException, UnsupportedEncodingException { byte[] content = null; String contentType = null; if (resourceName == null) { final String errorMessage = "Error while using the servlet to get a resource: the parameter " + getResourceParameterName() + " is null."; if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, errorMessage); } throw new ServletException(errorMessage); } if (fileName == null) { final String errorMessage = "Error while using the servlet to get a resource: the parameter " + LOCATION_PARAM + " is null."; if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, errorMessage); } throw new ServletException(errorMessage); } resourceName = URLDecoder.decode(resourceName, "UTF-8"); fileName = URLDecoder.decode(fileName, "UTF-8"); response.setCharacterEncoding("UTF-8"); final File resourcesParentFolder = getResourcesParentFolder(request); final String subFolderName = getSubFolderName(); String subFolderSuffix; if (subFolderName != null) { subFolderSuffix = File.separator + subFolderName; } else { subFolderSuffix = ""; } try { final File resourceFolder = new File(resourcesParentFolder, resourceName + subFolderSuffix); final File file = new File(resourceFolder, fileName); final BonitaHomeFolderAccessor tenantFolder = new BonitaHomeFolderAccessor(); if (!tenantFolder.isInFolder(resourceFolder, resourcesParentFolder)) { throw new ServletException("For security reasons, access to this file paths" + resourceFolder.getAbsolutePath() + " is restricted."); } if (!tenantFolder.isInFolder(file, resourceFolder)) { throw new ServletException("For security reasons, access to this file paths" + file.getAbsolutePath() + " is restricted."); } final String lowerCaseFileName = fileName.toLowerCase(); if (lowerCaseFileName.endsWith(".jpg")) { contentType = "image/jpeg"; } else if (lowerCaseFileName.endsWith(".jpeg")) { contentType = "image/jpeg"; } else if (lowerCaseFileName.endsWith(".gif")) { contentType = "image/gif"; } else if (lowerCaseFileName.endsWith(".png")) { contentType = "image/png"; } else if (lowerCaseFileName.endsWith(".css") || lowerCaseFileName.endsWith(".less")) { contentType = "text/css"; } else if (lowerCaseFileName.endsWith(".js")) { contentType = "application/x-javascript"; } else if (lowerCaseFileName.endsWith(".html")) { contentType = "text/html; charset=UTF-8"; } else if (lowerCaseFileName.endsWith(".htc")) { contentType = "text/x-component"; } else if (lowerCaseFileName.endsWith(".svg")) { contentType = "image/svg+xml"; } else if (lowerCaseFileName.endsWith(".eot")) { contentType = "application/vnd.ms-fontobject"; } else if (lowerCaseFileName.endsWith(".woff")) { contentType = "application/x-font-woff"; } else if (lowerCaseFileName.endsWith(".ttf")) { contentType = "application/x-font-ttf"; } else if (lowerCaseFileName.endsWith(".otf")) { contentType = "application/x-font-opentype"; } else { final FileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap(); contentType = mimetypesFileTypeMap.getContentType(file); } if (contentType == null) { contentType = "application/octet-stream"; } content = FileUtils.readFileToByteArray(file); response.setContentType(contentType); response.setContentLength(content.length); response.setBufferSize(content.length); final OutputStream out = response.getOutputStream(); out.write(content, 0, content.length); response.flushBuffer(); out.close(); } catch (final IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "Error while generating the response.", e); } throw new ServletException(e.getMessage(), e); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.ViewAllRoomsSchedulesDA.java
public ActionForward downloadScheduleList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final ExecutionSemester executionSemester = getExecutionSemester(request); final Integer semester = executionSemester.getSemester(); final String executionYear = executionSemester.getExecutionYear().getYear(); final Spreadsheet spreadsheet = new Spreadsheet("ScheduleMap"); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionPeriod")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionYear")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionCourse")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.executionDegree")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.curricular.year")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift.schedule")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.shift.schedule.hasAllocatedRooms")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.teacher.emails")); spreadsheet.setHeader(BundleUtil.getString(Bundle.APPLICATION, "label.comments")); for (final ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) { final StringBuilder executionDegreeBuilder = new StringBuilder(); for (final ExecutionDegree executionDegree : executionCourse.getExecutionDegrees()) { if (executionDegreeBuilder.length() > 0) { executionDegreeBuilder.append("\n"); }/* w w w .java2 s. c o m*/ executionDegreeBuilder.append(executionDegree.getDegree().getSigla()); } final StringBuilder emailBuilder = new StringBuilder(); for (final Professorship professorship : executionCourse.getProfessorshipsSet()) { if (emailBuilder.length() > 0) { emailBuilder.append("\n"); } emailBuilder.append(professorship.getPerson().getEmailForSendingEmails()); } for (final CourseLoad courseLoad : executionCourse.getCourseLoadsSet()) { for (final Shift shift : courseLoad.getShiftsSet()) { final Set<Integer> curricularYears = new TreeSet<Integer>(); for (final SchoolClass schoolClass : shift.getAssociatedClassesSet()) { curricularYears.add(schoolClass.getAnoCurricular()); } final StringBuilder curricularYearBuilder = new StringBuilder(); for (final Integer curricularYear : curricularYears) { if (curricularYearBuilder.length() > 0) { curricularYearBuilder.append(", "); } curricularYearBuilder.append(curricularYear); } final Row row = spreadsheet.addRow(); row.setCell(semester); row.setCell(executionYear); row.setCell(executionCourse.getName()); row.setCell(executionDegreeBuilder.toString()); row.setCell(curricularYearBuilder.toString()); row.setCell(shift.getNome()); row.setCell(shift.getLessonPresentationString().replace(';', '\n')); row.setCell(hasRoomsAttributed(shift)); row.setCell(emailBuilder.toString()); row.setCell(shift.getComment() == null ? "" : shift.getComment()); } } } response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=scheduleMap" + executionYear.replace('/', '_') + "_" + executionSemester.getSemester() + ".xls"); final ServletOutputStream writer = response.getOutputStream(); spreadsheet.exportToXLSSheet(writer); writer.flush(); response.flushBuffer(); return null; }
From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java
/** * Process a type 3 NTLM message//from w ww . j a v a 2s . c o m * * @param type3Msg Type3NTLMMessage * @param req HttpServletRequest * @param res HttpServletResponse * @param session HttpSession * @param chain FilterChain * @exception IOException * @exception ServletException */ private void processType3(Type3NTLMMessage type3Msg, HttpServletRequest req, HttpServletResponse res, HttpSession session, FilterChain chain) throws IOException, ServletException { if (logger.isDebugEnabled()) logger.debug("Received type3 " + type3Msg); // Get the existing NTLM details NTLMLogonDetails ntlmDetails = (NTLMLogonDetails) session.getAttribute(NTLM_AUTH_DETAILS); String userId = AuthenticationUtil.getUserId(req); // Get the NTLM logon details String userName = type3Msg.getUserName(); String workstation = type3Msg.getWorkstation(); String domain = type3Msg.getDomain(); boolean authenticated = false; // Check if we are using cached details for the authentication if (userId != null && ntlmDetails != null && ntlmDetails.hasNTLMHashedPassword()) { // Check if the received NTLM hashed password matches the cached password byte[] ntlmPwd = type3Msg.getNTLMHash(); byte[] cachedPwd = ntlmDetails.getNTLMHashedPassword(); if (ntlmPwd != null) { if (ntlmPwd.length == cachedPwd.length) { authenticated = true; for (int i = 0; i < ntlmPwd.length; i++) { if (ntlmPwd[i] != cachedPwd[i]) { authenticated = false; break; } } } } if (logger.isDebugEnabled()) logger.debug("Using cached NTLM hash, authenticated = " + authenticated); if (!authenticated) { restartAuthProcess(session, req, res, AUTH_NTLM); } else { // Allow the user to access the requested page chain.doFilter(req, res); } } else { try { Connector conn = this.connectorService.getConnector(this.endpoint, session); ConnectorContext ctx = new ConnectorContext(null, getConnectionHeaders(conn)); Response remoteRes = conn.call("/touch", ctx, req, null); if (Status.STATUS_UNAUTHORIZED == remoteRes.getStatus().getCode()) { String authHdr = remoteRes.getStatus().getHeaders().get(HEADER_WWWAUTHENTICATE); if (authHdr.equals(AUTH_NTLM)) { // authentication failed on repo side - being login process again // check for "chrome" since Chrome user-agent contains a Safari version String userAgent = req.getHeader("user-agent"); if (userAgent != null && userAgent.indexOf("Safari") != -1 && userAgent.indexOf("Chrome") == -1) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); final PrintWriter out = res.getWriter(); out.println("<html><head></head>"); out.println( "<body><p>Login authentication failed. Please close and re-open Safari to try again.</p>"); out.println("</body></html>"); out.close(); } else { restartAuthProcess(session, req, res, authHdr); } res.flushBuffer(); } else { if (logger.isDebugEnabled()) logger.debug("Unexpected response from repository: WWW-Authenticate:" + authHdr); redirectToLoginPage(req, res); } } else if (Status.STATUS_OK == remoteRes.getStatus().getCode() || Status.STATUS_TEMPORARY_REDIRECT == remoteRes.getStatus().getCode()) { // // NTLM login successful - Update the NTLM logon details in the session // if (ntlmDetails == null) { // No cached NTLM details ntlmDetails = new NTLMLogonDetails(userName, workstation, domain, false, null); ntlmDetails.setNTLMHashedPassword(type3Msg.getNTLMHash()); session.setAttribute(NTLM_AUTH_DETAILS, ntlmDetails); if (logger.isDebugEnabled()) logger.debug("No cached NTLM details, created"); } else { // Update the cached NTLM details ntlmDetails.setDetails(userName, workstation, domain, false, null); ntlmDetails.setNTLMHashedPassword(type3Msg.getNTLMHash()); if (logger.isDebugEnabled()) logger.debug("Updated cached NTLM details"); } if (logger.isDebugEnabled()) logger.debug("User logged on via NTLM, " + ntlmDetails); setExternalAuthSession(session); onSuccess(req, res, session, userName); // Allow the user to access the requested page chain.doFilter(req, res); } else { if (logger.isDebugEnabled()) logger.debug("Unexpected response from repository: " + remoteRes.getStatus().getMessage()); redirectToLoginPage(req, res); } } catch (ConnectorServiceException cse) { throw new PlatformRuntimeException("Incorrectly configured endpoint: " + this.endpoint); } } }
From source file:org.openmrs.module.errorlogging.web.controller.ViewErrorLoggingController.java
@RequestMapping(value = "/module/errorlogging/viewExceptionLogs.json", method = RequestMethod.POST) public void showErrors(HttpServletRequest request, HttpServletResponse response) { JSONObject json = new JSONObject(); JSONArray data = new JSONArray(); String username = processString(String.valueOf(request.getParameter("username"))); String excClass = processString(String.valueOf(request.getParameter("excClass"))); String excMessage = processString(String.valueOf(request.getParameter("excMessage"))); String excOpenMRSVersion = processString(String.valueOf(request.getParameter("excOpenMRSVersion"))); String excFileName = processString(String.valueOf(request.getParameter("excFileName"))); String excMethodName = processString(String.valueOf(request.getParameter("excMethodName"))); Integer excLineNum = processInteger(request.getParameter("excLineNum")); Integer excFrequency = processInteger(request.getParameter("excFrequency")); Date startDateTime = getDateTime( processString(String.valueOf(request.getParameter("startDateTimeString")))); Date endDateTime = getDateTime(processString(String.valueOf(request.getParameter("endDateTimeString")))); String sEcho = request.getParameter("sEcho"); Integer start = Integer.valueOf(request.getParameter("iDisplayStart")); Integer length = Integer.valueOf(request.getParameter("iDisplayLength")); ExceptionLogService exceptionLogService = Context.getService(ExceptionLogService.class); List<ExceptionLog> exceptionLogs = exceptionLogService.getExceptionLogs(username, excClass, excMessage, excOpenMRSVersion, excFileName, excMethodName, excLineNum, excFrequency, startDateTime, endDateTime, start, length);/* www. ja v a 2 s .c o m*/ Integer count = exceptionLogService.getCountOfExceptionLogs(username, excClass, excMessage, excOpenMRSVersion, excFileName, excMethodName, excLineNum, excFrequency, startDateTime, endDateTime); response.setContentType("application/json"); if (excFrequency != null) { for (ExceptionLog exLog : exceptionLogs) { JSONArray excLog = new JSONArray(); List<ExceptionLog> exceptionLogsFr = exceptionLogService.getExceptionLogs(null, exLog.getExceptionClass(), exLog.getExceptionMessage(), exLog.getOpenmrsVersion(), exLog.getExceptionLogDetail().getFileName(), exLog.getExceptionLogDetail().getMethodName(), exLog.getExceptionLogDetail().getLineNumber(), null, null, null, 0, 1); excLog.put(exceptionLogsFr.get(0).getExceptionLogId()); excLog.put(exceptionLogsFr.get(0).getExceptionClass()); excLog.put(processNullString(exceptionLogsFr.get(0).getExceptionMessage())); excLog.put(exceptionLogsFr.get(0).getOpenmrsVersion()); excLog.put(""); excLog.put(""); if (exceptionLogsFr.get(0).getExceptionLogDetail() != null) { excLog.put("View"); } else { excLog.put(""); } if (exceptionLogsFr.get(0).getExceptionRootCause() != null) { excLog.put("View"); } else { excLog.put(""); } excLog.put("Report"); data.put(excLog); } } else { for (ExceptionLog exLog : exceptionLogs) { JSONArray excLog = new JSONArray(); excLog.put(exLog.getExceptionLogId()); excLog.put(exLog.getExceptionClass()); excLog.put(processNullString(exLog.getExceptionMessage())); excLog.put(exLog.getOpenmrsVersion()); excLog.put(getFormattedExceptionDateTime(exLog.getExceptionDateTime())); excLog.put(exLog.getUser().getUsername()); if (exLog.getExceptionLogDetail() != null) { excLog.put("View"); } else { excLog.put(""); } if (exLog.getExceptionRootCause() != null) { excLog.put("View"); } else { excLog.put(""); } excLog.put("Report"); data.put(excLog); } } try { json.put("aaData", data); json.put("iTotalRecords", count); json.put("iTotalDisplayRecords", count); json.put("iDisplayLength", length); json.put("sEcho", sEcho); response.getWriter().print(json); response.flushBuffer(); } catch (Exception e) { log.error("Error has occurred while creating json response", e); } }
From source file:com.openmeap.services.ApplicationManagementServlet.java
private Result handleArchiveDownload(HttpServletRequest request, HttpServletResponse response) { Result res = new Result(); Error err = new Error(); res.setError(err);/* w w w . j a va 2s . c om*/ GlobalSettings settings = modelManager.getGlobalSettings(); Map properties = this.getServicesWebProperties(); String nodeKey = (String) properties.get("clusterNodeUrlPrefix"); ClusterNode clusterNode = settings.getClusterNode(nodeKey); if (nodeKey == null || clusterNode == null) { // TODO: create a configuration error code err.setCode(ErrorCode.UNDEFINED); err.setMessage("A configuration is missing. Please consult the error logs."); logger.error( "For each node in the cluster, the property or environment variable OPENMEAP_CLUSTER_NODE_URL_PREFIX must match the \"Service Url Prefix\" value configured in the administrative interface. This value is currently " + nodeKey + "."); return res; } String pathValidation = clusterNode.validateFileSystemStoragePathPrefix(); if (pathValidation != null) { err.setCode(ErrorCode.UNDEFINED); err.setMessage("A configuration is missing. Please consult the error logs."); logger.error( "There is an issue with the location at \"File-system Storage Prefix\". " + pathValidation); return res; } String hash = request.getParameter(UrlParamConstants.APPARCH_HASH); String hashAlg = request.getParameter(UrlParamConstants.APPARCH_HASH_ALG); String fileName = null; if (hash == null || hashAlg == null) { // look in the apps directory for the archive specified String appName = request.getParameter(UrlParamConstants.APP_NAME); String versionId = request.getParameter(UrlParamConstants.APP_VERSION); ApplicationVersion appVersion = modelManager.getModelService().findAppVersionByNameAndId(appName, versionId); if (appVersion == null) { String mesg = "The application version " + versionId + " was not found for application " + appName; err.setCode(ErrorCode.APPLICATION_VERSION_NOTFOUND); err.setMessage(mesg); logger.warn(mesg); return res; } String auth = request.getParameter(UrlParamConstants.AUTH_TOKEN); com.openmeap.model.dto.Application app = appVersion.getApplication(); try { if (auth == null || !AuthTokenProvider.validateAuthToken(app.getProxyAuthSalt(), auth)) { err.setCode(ErrorCode.AUTHENTICATION_FAILURE); err.setMessage("The \"auth\" token presented is not recognized, missing, or empty."); return res; } } catch (DigestException e) { throw new GenericRuntimeException(e); } hash = appVersion.getArchive().getHash(); hashAlg = appVersion.getArchive().getHashAlgorithm(); fileName = app.getName() + " - " + appVersion.getIdentifier(); } else { fileName = hashAlg + "-" + hash; } File file = ApplicationArchive.getFile(clusterNode.getFileSystemStoragePathPrefix(), hashAlg, hash); if (!file.exists()) { String mesg = "The application archive with " + hashAlg + " hash " + hash + " was not found."; // TODO: create an enumeration for this error err.setCode(ErrorCode.UNDEFINED); err.setMessage(mesg); logger.warn(mesg); return res; } try { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(file.toURL().toString()); response.setContentType(mimeType); response.setContentLength(Long.valueOf(file.length()).intValue()); URLCodec codec = new URLCodec(); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".zip\";"); InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); outputStream = response.getOutputStream(); Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream); } finally { if (inputStream != null) { inputStream.close(); } //if(outputStream!=null) {outputStream.close();} } response.flushBuffer(); } catch (FileNotFoundException e) { logger.error("Exception {}", e); } catch (IOException ioe) { logger.error("Exception {}", ioe); } return null; }
From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java
/** * If the pv is hosted on another appliance, proxy retrieval requests from that appliance * We expect to return immediately after this method. * @param req//ww w. ja va 2 s . c o m * @param resp * @param pvName * @param useChunkedEncoding * @param dataRetrievalURLForPV * @throws IOException */ private void proxyRetrievalRequest(HttpServletRequest req, HttpServletResponse resp, String pvName, boolean useChunkedEncoding, String dataRetrievalURLForPV) throws IOException { try { // TODO add some intelligent business logic to determine if redirect/proxy. // It may be beneficial to support both and choose based on where the client in calling from or perhaps from a header? boolean redirect = false; if (redirect) { logger.debug("Data for pv " + pvName + "is elsewhere. Redirecting to appliance " + dataRetrievalURLForPV); URI redirectURI = new URI(dataRetrievalURLForPV + "/" + req.getPathInfo()); String redirectURIStr = redirectURI.normalize().toString() + "?" + req.getQueryString(); logger.debug("URI for redirect is " + redirectURIStr); resp.sendRedirect(redirectURIStr); return; } else { logger.debug("Data for pv " + pvName + "is elsewhere. Proxying appliance " + dataRetrievalURLForPV); URI redirectURI = new URI(dataRetrievalURLForPV + "/" + req.getPathInfo()); String redirectURIStr = redirectURI.normalize().toString() + "?" + req.getQueryString(); logger.debug("URI for proxying is " + redirectURIStr); // if(useChunkedEncoding) { // resp.addHeader("Transfer-Encoding", "chunked"); // } CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet getMethod = new HttpGet(redirectURIStr); getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ try (CloseableHttpResponse response = httpclient.execute(getMethod)) { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); HashSet<String> proxiedHeaders = new HashSet<String>(); proxiedHeaders.addAll(Arrays.asList(MimeResponse.PROXIED_HEADERS)); Header[] headers = response.getAllHeaders(); for (Header header : headers) { if (proxiedHeaders.contains(header.getName())) { logger.debug("Adding headerName " + header.getName() + " and value " + header.getValue() + " when proxying request"); resp.addHeader(header.getName(), header.getValue()); } } if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); try (OutputStream os = resp.getOutputStream(); InputStream is = new BufferedInputStream(entity.getContent())) { byte buf[] = new byte[10 * 1024]; int bytesRead = is.read(buf); while (bytesRead > 0) { os.write(buf, 0, bytesRead); resp.flushBuffer(); bytesRead = is.read(buf); } } } else { throw new IOException("HTTP response did not have an entity associated with it"); } } else { logger.error("Invalid status code " + response.getStatusLine().getStatusCode() + " when connecting to URL " + redirectURIStr + ". Sending the errorstream across"); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { try (InputStream is = new BufferedInputStream(response.getEntity().getContent())) { byte buf[] = new byte[10 * 1024]; int bytesRead = is.read(buf); while (bytesRead > 0) { os.write(buf, 0, bytesRead); bytesRead = is.read(buf); } } resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.sendError(response.getStatusLine().getStatusCode(), new String(os.toByteArray())); } } } } return; } catch (URISyntaxException ex) { throw new IOException(ex); } }