List of usage examples for javax.servlet.http HttpServletResponse flushBuffer
public void flushBuffer() throws IOException;
From source file:net.sourceforge.fenixedu.presentationTier.Action.scientificCouncil.credits.ViewTeacherCreditsReportDispatchAction.java
public ActionForward exportGlobalToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws FenixServiceException, InvalidPeriodException, ParseException { final String fromExecutionYearID = request.getParameter("fromExecutionYearID"); final String untilExecutionYearID = request.getParameter("untilExecutionYearID"); final String departmentID = request.getParameter("departmentID"); final ExecutionYear beginExecutionYear = FenixFramework.getDomainObject(fromExecutionYearID); final ExecutionYear endExecutionYear = FenixFramework.getDomainObject(untilExecutionYearID); final ExecutionSemester beginExecutionSemester; final ExecutionSemester endExecutionSemester = endExecutionYear.getExecutionSemesterFor(2); if (beginExecutionYear.getPreviousExecutionYear() .equals(ExecutionSemester.readStartExecutionSemesterForCredits().getExecutionYear())) { beginExecutionSemester = ExecutionSemester.readStartExecutionSemesterForCredits(); } else {//from w w w . j a v a 2s . c o m beginExecutionSemester = beginExecutionYear.getPreviousExecutionYear().getExecutionSemesterFor(1); } Set<Department> departments = new TreeSet<Department>(Department.COMPARATOR_BY_NAME); if (departmentID == null) { departments.addAll(rootDomainObject.getDepartmentsSet()); } else { departments.add(FenixFramework.<Department>getDomainObject(departmentID)); } SheetData<Department> data = new SheetData<Department>(departments) { @Override protected void makeLine(Department department) { addCell("Departamento", department.getRealName(), "Total"); Map<ExecutionYear, PeriodCreditsReportDTO> departmentPeriodTotalCredits = null; try { departmentPeriodTotalCredits = ReadDepartmentTotalCreditsByPeriod .run(department.getDepartmentUnit(), beginExecutionSemester, endExecutionSemester); } catch (ParseException e) { logger.error(e.getMessage(), e); } ExecutionYear lastExecutionYear = null; for (ExecutionYear executionYear = beginExecutionSemester.getExecutionYear(); executionYear != null && executionYear.isBeforeOrEquals(endExecutionYear); executionYear = executionYear .getNextExecutionYear()) { PeriodCreditsReportDTO periodCreditsReportDTO = departmentPeriodTotalCredits.get(executionYear); addCell(executionYear.getYear(), (short) 3, "Docentes Carreira", (short) 1, periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getCareerCategoryTeacherCredits(), (short) 1, Formula.SUM_FOOTER, (short) 1); addCell("Restantes Categorias", periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getNotCareerCategoryTeacherCredits(), Formula.SUM_FOOTER); addCell("Saldo Final", periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getCredits(), Formula.SUM_FOOTER); lastExecutionYear = executionYear; } if (lastExecutionYear != null) { PeriodCreditsReportDTO periodCreditsReportDTO = departmentPeriodTotalCredits .get(lastExecutionYear); addCell("N Docentes " + lastExecutionYear.getYear(), (short) 3, "Docentes Carreira", (short) 1, periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getCareerTeachersSize(), (short) 1, Formula.SUM_FOOTER, (short) 1); addCell("Restantes Categorias", periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getNotCareerTeachersSize(), Formula.SUM_FOOTER); addCell("Saldo Final", periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getTeachersSize(), Formula.SUM_FOOTER); addCell("Saldo per capita " + lastExecutionYear.getYear(), (short) 3, "Docentes Carreira", (short) 1, periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getCareerTeachersBalance(), (short) 1, Formula.SUM_FOOTER, (short) 1); addCell("Restantes Categorias", periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getNotCareerTeachersBalance(), Formula.SUM_FOOTER); addCell("Saldo Final", periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getBalance(), Formula.SUM_FOOTER); } } }; try { String filename = "RelatorioCreditos:" + getFileName(Calendar.getInstance().getTime()); final ServletOutputStream writer = response.getOutputStream(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls"); new SpreadsheetBuilder().addSheet("RelatorioCreditos", data).build(WorkbookExportFormat.EXCEL, writer); writer.flush(); response.flushBuffer(); } catch (IOException e) { throw new FenixServiceException(); } return null; }
From source file:org.apache.camel.component.websocket.SignalkWebSocketServlet.java
public void init() throws ServletException { try {/* w w w .jav a2s . co m*/ String bs = getInitParameter("bufferSize"); if (logger.isDebugEnabled()) logger.debug("Upgrade ws, create factory:"); this._webSocketFactory = new WebSocketFactory(this, (bs == null) ? 8192 : Integer.parseInt(bs)) { private WebSocketBuffers _buffers = new WebSocketBuffers(8192); private Map<WebSocketServletConnection, String> sessionMap = new HashMap<WebSocketServletConnection, String>(); public void upgrade(HttpServletRequest request, HttpServletResponse response, WebSocket websocket, String protocol) throws IOException { String sessionId = request.getRequestedSessionId(); if (logger.isDebugEnabled()) logger.debug("Upgrade ws, requested sessionId:" + sessionId); if (StringUtils.isBlank(sessionId)) { sessionId = request.getSession().getId(); if (logger.isDebugEnabled()) logger.debug("Request.sessionId:" + sessionId); } if (StringUtils.isBlank(sessionId)) { sessionId = ((DefaultWebsocket) websocket).getConnectionKey(); if (logger.isDebugEnabled()) logger.debug("Request.wsSessionId:" + sessionId); } if (!("websocket".equalsIgnoreCase(request.getHeader("Upgrade")))) throw new IllegalStateException("!Upgrade:websocket"); if (!("HTTP/1.1".equals(request.getProtocol()))) { throw new IllegalStateException("!HTTP/1.1"); } int draft = request.getIntHeader("Sec-WebSocket-Version"); if (draft < 0) { draft = request.getIntHeader("Sec-WebSocket-Draft"); } int requestedVersion = draft; AbstractHttpConnection http = AbstractHttpConnection.getCurrentConnection(); if (http instanceof BlockingHttpConnection) throw new IllegalStateException("Websockets not supported on blocking connectors"); ConnectedEndPoint endp = (ConnectedEndPoint) http.getEndPoint(); List<String> extensions_requested = new ArrayList<>(); Enumeration<String> e = request.getHeaders("Sec-WebSocket-Extensions"); while (e.hasMoreElements()) { QuotedStringTokenizer tok = new QuotedStringTokenizer((String) e.nextElement(), ","); while (tok.hasMoreTokens()) { extensions_requested.add(tok.nextToken()); } } if (draft < getMinVersion()) draft = 2147483647; WebSocketServletConnection connection; switch (draft) { case -1: case 0: connection = new WebSocketServletConnectionD00(this, websocket, endp, this._buffers, http.getTimeStamp(), (int) getMaxIdleTime(), protocol); break; case 1: case 2: case 3: case 4: case 5: case 6: connection = new WebSocketServletConnectionD06(this, websocket, endp, this._buffers, http.getTimeStamp(), (int) getMaxIdleTime(), protocol); break; case 7: case 8: List<Extension> extensions = initExtensions(extensions_requested, 5, 5, 3); connection = new WebSocketServletConnectionD08(this, websocket, endp, this._buffers, http.getTimeStamp(), (int) getMaxIdleTime(), protocol, extensions, draft); break; case 13: List<Extension> extensions1 = initExtensions(extensions_requested, 5, 5, 3); connection = new WebSocketServletConnectionRFC6455(this, websocket, endp, this._buffers, http.getTimeStamp(), (int) getMaxIdleTime(), protocol, extensions1, draft); break; case 9: case 10: case 11: case 12: default: String versions = "13"; if (getMinVersion() <= 8) versions = new StringBuilder().append(versions).append(", 8").toString(); if (getMinVersion() <= 6) versions = new StringBuilder().append(versions).append(", 6").toString(); if (getMinVersion() <= 0) { versions = new StringBuilder().append(versions).append(", 0").toString(); } response.setHeader("Sec-WebSocket-Version", versions); StringBuilder err = new StringBuilder(); err.append("Unsupported websocket client version specification "); if (requestedVersion >= 0) err.append("[").append(requestedVersion).append("]"); else { err.append("<Unspecified, likely a pre-draft version of websocket>"); } err.append(", configured minVersion [").append(getMinVersion()).append("]"); err.append(", reported supported versions [").append(versions).append("]"); // LOG.warn(err.toString(), new Object[0]); throw new HttpException(400, "Unsupported websocket version specification"); } addConnection(connection); connection.getConnection().setMaxBinaryMessageSize(getMaxBinaryMessageSize()); connection.getConnection().setMaxTextMessageSize(getMaxTextMessageSize()); connection.handshake(request, response, protocol); response.flushBuffer(); connection.fillBuffersFrom(((HttpParser) http.getParser()).getHeaderBuffer()); connection.fillBuffersFrom(((HttpParser) http.getParser()).getBodyBuffer()); String wsSession = ((DefaultWebsocket) websocket).getConnectionKey(); //if(logger.isDebugEnabled())logger.debug("Upgraded session " + request.getSession().getId() + " to ws " + ((DefaultWebsocket) websocket).getConnectionKey()); if (logger.isDebugEnabled()) logger.debug("Upgraded session " + sessionId + " to ws " + wsSession + " from remote ip:" + request.getRemoteAddr()); try { sessionMap.put(connection, wsSession); SubscriptionManagerFactory.getInstance().add(sessionId, wsSession, ConfigConstants.OUTPUT_WS, request.getLocalAddr(), request.getRemoteAddr()); //add default sub, or specific sub here, all instant policy String subscribe = request.getParameter("subscribe"); if (StringUtils.isBlank(subscribe) || "self".equals(subscribe)) { //subscribe to self String sub = "{\"context\":\"vessels.self\",\"subscribe\":[{\"path\":\"*\", \"policy\":\"instant\"}]}"; sendSub(request, sub, wsSession); } else if ("all".equals(subscribe)) { //subscribe to all String sub = "{\"context\":\"vessels.*\",\"subscribe\":[{\"path\":\"*\", \"policy\":\"instant\"}]}"; sendSub(request, sub, wsSession); } else if ("none".equals(subscribe)) { //subscribe to none - do nothing } } catch (Exception e1) { logger.error(e1.getMessage(), e1); throw new IOException(e1); } // LOG.debug("Websocket upgrade {} {} {} {}", new Object[] { request.getRequestURI(), Integer.valueOf(draft), protocol, connection }); request.setAttribute("org.eclipse.jetty.io.Connection", connection); connection.getConnection().sendMessage(Util.getWelcomeMsg().toString()); } private void sendSub(HttpServletRequest request, String sub, String wsSession) throws Exception { Map<String, Object> headers = new HashMap<>(); headers.put(MSG_SRC_IP, request.getRemoteAddr()); headers.put(MSG_SRC_IP_PORT, request.getRemotePort()); if (Util.sameNetwork(request.getLocalAddr(), request.getRemoteAddr())) { headers.put(MSG_TYPE, INTERNAL_IP); } else { headers.put(MSG_TYPE, EXTERNAL_IP); } headers.put(WebsocketConstants.CONNECTION_KEY, wsSession); if (logger.isDebugEnabled()) logger.debug("Sending connection sub:" + sub); producer.sendBodyAndHeaders(RouteManager.SEDA_INPUT, sub, headers); } @Override protected boolean removeConnection(WebSocketServletConnection connection) { //unsubscribe and remove websocket session String wsSession = sessionMap.get(connection); if (logger.isDebugEnabled()) logger.debug("Ended wsSession " + wsSession); try { SubscriptionManagerFactory.getInstance().removeWsSession(wsSession); } catch (Exception e1) { logger.error(e1.getMessage(), e1); } return super.removeConnection(connection); } }; this._webSocketFactory.setMaxTextMessageSize(256 * 1024); this._webSocketFactory.start(); String max = getInitParameter("maxIdleTime"); if (max != null) { this._webSocketFactory.setMaxIdleTime(Integer.parseInt(max)); } max = getInitParameter("maxTextMessageSize"); if (max != null) { this._webSocketFactory.setMaxTextMessageSize(Integer.parseInt(max)); } max = getInitParameter("maxBinaryMessageSize"); if (max != null) { this._webSocketFactory.setMaxBinaryMessageSize(Integer.parseInt(max)); } String min = getInitParameter("minVersion"); if (min != null) this._webSocketFactory.setMinVersion(Integer.parseInt(min)); } catch (ServletException x) { throw x; } catch (Exception x) { throw new ServletException(x); } }
From source file:com.rmn.qa.servlet.StatusServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int refresh = -1; if (request.getParameter("refresh") != null) { try {/* ww w .java2 s .c o m*/ refresh = Integer.parseInt(request.getParameter("refresh")); } catch (NumberFormatException e) { // ignore wrong param } } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); StringBuilder builder = new StringBuilder(); builder.append("<html>"); builder.append("<head>"); if (refresh != -1) { builder.append(String.format("<meta http-equiv='refresh' content='%d' />", refresh)); } builder.append("<title>Grid overview</title>"); builder.append("<style>"); builder.append(".busy {"); builder.append(" opacity : 0.4;"); builder.append("filter: alpha(opacity=40);"); builder.append("}"); builder.append("</style>"); builder.append("</head>"); builder.append("<body>"); builder.append("<H1>Grid Hub "); builder.append(coreVersion).append(coreRevision); builder.append("</H1>"); int chromeThreads = requestMatcher.getNumFreeThreadsForParameters(getRegistry().getAllProxies(), new AutomationRunRequest(StatusServlet.class.getSimpleName(), null, BrowserType.CHROME)); int firefoxThreads = requestMatcher.getNumFreeThreadsForParameters(getRegistry().getAllProxies(), new AutomationRunRequest(StatusServlet.class.getSimpleName(), null, BrowserType.FIREFOX)); int ieThreads = requestMatcher.getNumFreeThreadsForParameters(getRegistry().getAllProxies(), new AutomationRunRequest(StatusServlet.class.getSimpleName(), null, "internetexplorer")); builder.append("<H2>Free Threads - Chrome: ").append(chromeThreads).append(" Firefox: ") .append(firefoxThreads).append(" IE: ").append(ieThreads).append("</H2>"); for (RemoteProxy proxy : getRegistry().getAllProxies()) { StringBuilder localBuilder = new StringBuilder(); localBuilder.append("<fieldset>"); localBuilder.append("<legend>").append(proxy.getClass().getSimpleName()).append("</legend>"); localBuilder.append("listening on ").append(proxy.getRemoteHost()); Object instanceId = proxy.getConfig().custom.get(AutomationConstants.INSTANCE_ID); if (instanceId != null) { AutomationDynamicNode node = AutomationContext.getContext().getNode((String) instanceId); if (node != null) { localBuilder.append("<br>EC2 dynamic node " + node.getInstanceId()); if (!StringUtils.isEmpty(node.getInstanceType())) { localBuilder.append("<br>Instance Type " + node.getInstanceType()); } localBuilder.append("<br>Start time " + node.getStartDate()); localBuilder.append("<br>Current shutdown time ").append(node.getEndDate()); localBuilder.append("<br>Requested test run ").append(node.getUuid()); } } if (((DefaultRemoteProxy) proxy).isDown()) { localBuilder.append("(cannot be reached at the moment)"); } localBuilder.append("<br />"); if (proxy.getTimeOut() > 0) { int inSec = proxy.getTimeOut() / 1000; localBuilder.append("test session time out after ").append(inSec).append(" sec.<br />"); } localBuilder.append("Supports up to <b>").append(proxy.getMaxNumberOfConcurrentTestSessions()) .append("</b> concurrent tests from: <br />"); localBuilder.append(""); for (TestSlot slot : proxy.getTestSlots()) { TestSession session = slot.getSession(); String icon = getIcon(slot.getCapabilities(), proxy); if (icon != null) { localBuilder.append("<img "); localBuilder.append("src='").append(icon).append("' "); } else { localBuilder.append("<a href='#' "); } if (session != null) { localBuilder.append(" class='busy' "); localBuilder.append(" title='").append(session.get("lastCommand")).append("' "); } else { localBuilder.append(" title='").append(slot.getCapabilities()) .append("type=" + slot.getProtocol()).append("' "); } if (icon != null) { localBuilder.append("/>"); } else { localBuilder.append(">"); localBuilder.append(slot.getCapabilities().get(CapabilityType.BROWSER_NAME)); localBuilder.append("</a>"); } } localBuilder.append("</fieldset>"); builder.append(localBuilder); } int numUnprocessedRequests = getRegistry().getNewSessionRequestCount(); if (numUnprocessedRequests > 0) { builder.append(String.format("%d requests waiting for a slot to be free.", numUnprocessedRequests)); } builder.append("<ul>"); for (DesiredCapabilities req : getRegistry().getDesiredCapabilities()) { builder.append("<li>").append(req.asMap()).append("</li>"); } builder.append("</ul>"); if (request.getParameter("config") != null) { builder.append(getConfigInfo(request.getParameter("configDebug") != null)); } else { builder.append("<a href='?config=true&configDebug=true'>view config</a>"); } builder.append("</body>"); builder.append("</html>"); try (InputStream in = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));) { ByteStreams.copy(in, response.getOutputStream()); } finally { response.flushBuffer(); } }
From source file:org.alfresco.web.app.servlet.UploadContentServlet.java
/** * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//* ww w.j a va 2s . c o m*/ protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (logger.isDebugEnabled() == true) { String queryString = req.getQueryString(); logger.debug("Authenticating request to URL: " + req.getRequestURI() + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); } AuthenticationStatus status = servletAuthenticate(req, res, false); if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) { res.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } // Tokenise the URI String uri = req.getRequestURI(); uri = uri.substring(req.getContextPath().length()); StringTokenizer t = new StringTokenizer(uri, "/"); int tokenCount = t.countTokens(); t.nextToken(); // skip servlet name // get or calculate the noderef and filename to download as NodeRef nodeRef = null; String filename = null; QName propertyQName = null; if (tokenCount == 2) { // filename is the only token filename = t.nextToken(); } else if (tokenCount == 4 || tokenCount == 5) { // assume 'workspace' or other NodeRef based protocol for remaining URL // elements StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken()); String id = t.nextToken(); // build noderef from the appropriate URL elements nodeRef = new NodeRef(storeRef, id); if (tokenCount == 5) { // filename is last remaining token filename = t.nextToken(); } // get qualified of the property to get content from - default to // ContentModel.PROP_CONTENT propertyQName = ContentModel.PROP_CONTENT; String property = req.getParameter(ARG_PROPERTY); if (property != null && property.length() != 0) { propertyQName = QName.createQName(property); } } else { logger.debug("Upload URL did not contain all required args: " + uri); res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED); return; } // get the services we need to retrieve the content ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); ContentService contentService = serviceRegistry.getContentService(); PermissionService permissionService = serviceRegistry.getPermissionService(); MimetypeService mimetypeService = serviceRegistry.getMimetypeService(); NodeService nodeService = serviceRegistry.getNodeService(); InputStream is = req.getInputStream(); BufferedInputStream inputStream = new BufferedInputStream(is); // Sort out the mimetype String mimetype = req.getParameter(ARG_MIMETYPE); if (mimetype == null || mimetype.length() == 0) { mimetype = MIMETYPE_OCTET_STREAM; if (filename != null) { MimetypeService mimetypeMap = serviceRegistry.getMimetypeService(); int extIndex = filename.lastIndexOf('.'); if (extIndex != -1) { String ext = filename.substring(extIndex + 1); mimetype = mimetypeService.getMimetype(ext); } } } // Get the encoding String encoding = req.getParameter(ARG_ENCODING); if (encoding == null || encoding.length() == 0) { // Get the encoding ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder(); Charset charset = charsetFinder.getCharset(inputStream, mimetype); encoding = charset.name(); } // Get the locale Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE)); if (locale == null) { locale = I18NUtil.getContentLocale(); if (nodeRef != null) { ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName); if (contentData != null) { locale = contentData.getLocale(); } } } if (logger.isDebugEnabled()) { if (nodeRef != null) { logger.debug("Found NodeRef: " + nodeRef.toString()); } logger.debug("For property: " + propertyQName); logger.debug("File name: " + filename); logger.debug("Mimetype: " + mimetype); logger.debug("Encoding: " + encoding); logger.debug("Locale: " + locale); } // Check that the user has the permissions to write the content if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) { if (logger.isDebugEnabled() == true) { logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString()); } if (logger.isDebugEnabled()) { logger.debug("Returning 403 Forbidden error..."); } res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Try and get the content writer ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true); if (writer == null) { if (logger.isDebugEnabled() == true) { logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString()); } res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED); return; } // Set the mimetype, encoding and locale writer.setMimetype(mimetype); writer.setEncoding(encoding); if (locale != null) { writer.setLocale(locale); } // Stream the content into the repository writer.putContent(inputStream); if (logger.isDebugEnabled() == true) { logger.debug("Content details: " + writer.getContentData().toString()); } // Set return status res.getWriter().write(writer.getContentData().toString()); res.flushBuffer(); if (logger.isDebugEnabled() == true) { logger.debug("UploadContentServlet done"); } }
From source file:net.ymate.module.webproxy.WebProxy.java
@SuppressWarnings("unchecked") public void transmission(HttpServletRequest request, HttpServletResponse response, String url, Type.HttpMethod method) throws Exception { StopWatch _consumeTime = null;//w ww .ja v a 2 s. co m long _threadId = 0; if (_LOG.isDebugEnabled()) { _consumeTime = new StopWatch(); _consumeTime.start(); _threadId = Thread.currentThread().getId(); _LOG.debug("-------------------------------------------------"); _LOG.debug("--> [" + _threadId + "] URL: " + url); } // HttpURLConnection _conn = null; try { if (__moduleCfg.isUseProxy()) { _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy()); } else { _conn = (HttpURLConnection) new URL(url).openConnection(); } _conn.setUseCaches(__moduleCfg.isUseCaches()); _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects()); // boolean _postFlag = Type.HttpMethod.POST.equals(method); boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/"); if (_postFlag) { _conn.setDoOutput(true); _conn.setDoInput(true); _conn.setRequestMethod(method.name()); } if (__moduleCfg.getConnectTimeout() > 0) { _conn.setConnectTimeout(__moduleCfg.getConnectTimeout()); } if (__moduleCfg.getReadTimeout() > 0) { _conn.setReadTimeout(__moduleCfg.getReadTimeout()); } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Method: " + method.name()); _LOG.debug("--> [" + _threadId + "] Request Headers: "); } // Enumeration _header = request.getHeaderNames(); while (_header.hasMoreElements()) { String _name = (String) _header.nextElement(); String _value = request.getHeader(_name); boolean _flag = false; if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type") || __moduleCfg.isTransferHeaderEnabled() && (!__moduleCfg.getTransferHeaderBlackList().isEmpty() && !__moduleCfg.getTransferHeaderBlackList().contains(_name) || !__moduleCfg.getTransferHeaderWhiteList().isEmpty() && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) { _conn.setRequestProperty(_name, _value); _flag = true; } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value); } } _conn.connect(); // if (_postFlag) { DataOutputStream _output = new DataOutputStream(_conn.getOutputStream()); try { if (_multipartFlag) { if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Multipart: TRUE"); } IOUtils.copyLarge(request.getInputStream(), _output); } else { String _charset = request.getCharacterEncoding(); String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset); IOUtils.write(_queryStr, _output, _charset); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Request Parameters: "); Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true, _charset); for (Map.Entry<String, String> _param : _paramsMap.entrySet()) { _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": " + _param.getValue()); } } } _output.flush(); } finally { IOUtils.closeQuietly(_output); } } // int _code = _conn.getResponseCode(); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Code: " + _code); _LOG.debug("--> [" + _threadId + "] Response Headers: "); } // Map<String, List<String>> _headers = _conn.getHeaderFields(); for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) { if (_entry.getKey() != null) { boolean _flag = false; String _values = StringUtils.join(_entry.getValue(), ","); if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type") || __moduleCfg.isTransferHeaderEnabled() && !__moduleCfg.getResponseHeaderWhileList().isEmpty() && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) { response.setHeader(_entry.getKey(), _values); _flag = true; } if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": " + _values); } } } if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) { response.sendError(_code); } else { if (HttpURLConnection.HTTP_OK == _code) { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { if (!_multipartFlag) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody( _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else { IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody"); } } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.flushBuffer(); } else { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.setStatus(_code); response.flushBuffer(); } } } catch (Throwable e) { _LOG.warn("An exception occurred while processing request mapping '" + url + "': ", RuntimeUtils.unwrapThrow(e)); } finally { IOUtils.close(_conn); // if (_LOG.isDebugEnabled()) { if (_consumeTime != null) { _consumeTime.stop(); _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); } _LOG.debug("-------------------------------------------------"); } } }
From source file:com.rr.familyPlanning.ui.importexport.importExportController.java
@RequestMapping(value = "/DLFile", method = { RequestMethod.GET }) public void DLReport(@RequestParam String i, @RequestParam String v, @RequestParam(value = "f", required = true) String f, HttpSession session, HttpServletResponse response) throws Exception { boolean hasPermission = false; /* Get a list of completed surveys the logged in user has access to */ User userDetails = (User) session.getAttribute("userDetails"); /* Get user permissions */ userProgramModules modulePermissions = usermanager.getUserModulePermissions(programId, userDetails.getId(), moduleId);//from w w w .jav a 2s . co m if (userDetails.getRoleId() == 2) { allowImport = true; allowExport = true; allowDelete = true; } else { allowImport = modulePermissions.isAllowImport(); allowExport = modulePermissions.isAllowExport(); allowDelete = modulePermissions.isAllowDelete(); } int importId = 0; programImportLogFileView logFileView = new programImportLogFileView(); logFileView.setSystemUserId(userDetails.getId()); logFileView.setProgramUploadId(importId); logFileView.setViewAction("Access /DLFile - " + f); /** Log Here **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("//DLFile"); ual.setRequestMethod("GET"); ual.setMethodAccessed("DLReport"); ual.setModuleId(moduleId); ual.setRelatedId(importId); ual.setRelatedIdCol("programUploadId"); ual.setProgramId(programId); String miscNotes = "filename:" + f; if (!allowImport) { // no permission logFileView.setProgramUploadId(importId); logFileView.setViewAction("Not Allowed To Import /DLFile"); importmanager.saveProgramImportLogFileView(logFileView); ual.setMiscNotes(miscNotes + "^^^^^No Permission:Not Allowed To Import /DLFile"); usermanager.saveUserActivityLog(ual); throw new Exception("Not Allowed to Access Import - " + importId); } else { if (i != null && v != null) { /* Decrypt the url */ decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); importId = Integer.parseInt(result[0].substring(4)); } if (importId != 0) { /** make sure user is allowed to access this file **/ int userId = 0; if (userDetails.getRoleId() != 2) { userId = userDetails.getId(); } //check user permission to batch if (userDetails.getRoleId() == 2) { hasPermission = true; } else { hasPermission = importmanager.checkImportPermission(importId, null, userId); } if (hasPermission) { programImport pi = importmanager.getProgramImportById(importId, 0); //we grab the file from /importFiles /* f of it = importTypes, user's original file * f of ai = archivesIn, user's converted file * */ String folderName = "importFiles"; String fileExt = pi.getInFileExt(); if (f.equals("ai")) { folderName = "archivesIn"; fileExt = pi.getOutFileExt(); } String filePath = importmanager.getFilePath(programId, folderName); String filePath1 = importmanager.getFilePath(programId, "loadFiles"); String fileName = pi.getAssignedFileName() + "." + fileExt; String fileOut = filePath + pi.getAssignedFileName() + "_dec." + fileExt; File fout = new File(fileOut); try { File file = new File(filePath + fileName); boolean fileExists = false; if (file.exists()) { fileExists = true; } else { file = new File(filePath1 + fileName); filePath = filePath1; if (file.exists()) { fileExists = true; } } if (!fileExists) { ual.setMiscNotes(miscNotes + "^^^^^File is missing:" + filePath + fileName); usermanager.saveUserActivityLog(ual); throw new Exception("Error with File " + filePath + fileName); } else { //decrypt file if (!fout.exists()) { filemanager.decodeTo64(file, fout); } } } catch (Exception e) { try { //update file to error ual.setMiscNotes(miscNotes + "^^^^^File is missing:" + filePath + fileName); usermanager.saveUserActivityLog(ual); throw new Exception("File does not exists " + filePath + fileName); } catch (Exception ex1) { ual.setMiscNotes(miscNotes + "^^^^^File is missing:" + filePath + fileName); usermanager.saveUserActivityLog(ual); throw new Exception("File does not exists " + filePath + fileName + ex1); } } try { // get your file as InputStream InputStream is = new FileInputStream(fileOut); // copy it to response's OutputStream String dlFileName = fileName; if (f.equalsIgnoreCase("it")) { dlFileName = pi.getUploadedFileName(); } String mimeType = "application/octet-stream"; response.setContentType(mimeType); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment;filename=\"" + dlFileName + "\""); org.apache.commons.io.IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); is.close(); if (fout.exists()) { fout.delete(); } } catch (IOException ex) { ual.setMiscNotes(miscNotes + "^^^^^File output errored:" + filePath + fileName); usermanager.saveUserActivityLog(ual); ex.printStackTrace(); System.out .println("Error writing file to output stream. Filename was '{}'" + fileName + ex); } } //we log user logFileView.setProgramUploadId(importId); importmanager.saveProgramImportLogFileView(logFileView); ual.setMiscNotes(miscNotes + "^^^^^Viewed file:" + f); usermanager.saveUserActivityLog(ual); } else { // no permission logFileView.setProgramUploadId(importId); logFileView.setViewAction("Access Denied /DLFile"); importmanager.saveProgramImportLogFileView(logFileView); ual.setMiscNotes(miscNotes + "^^^^^Access Denied /DLFile:" + f); usermanager.saveUserActivityLog(ual); throw new Exception("invalid import file download - " + importId); } } }
From source file:com.cloud.bridge.service.EC2RestServlet.java
protected void doGetOrPost(HttpServletRequest request, HttpServletResponse response) { if (debug) {//w ww . j ava 2s .co m System.out.println("EC2RestServlet.doGetOrPost: javax.servlet.forward.request_uri: " + request.getAttribute("javax.servlet.forward.request_uri")); System.out.println("EC2RestServlet.doGetOrPost: javax.servlet.forward.context_path: " + request.getAttribute("javax.servlet.forward.context_path")); System.out.println("EC2RestServlet.doGetOrPost: javax.servlet.forward.servlet_path: " + request.getAttribute("javax.servlet.forward.servlet_path")); System.out.println("EC2RestServlet.doGetOrPost: javax.servlet.forward.path_info: " + request.getAttribute("javax.servlet.forward.path_info")); System.out.println("EC2RestServlet.doGetOrPost: javax.servlet.forward.query_string: " + request.getAttribute("javax.servlet.forward.query_string")); } String action = request.getParameter("Action"); logRequest(request); // -> unauthenticated calls, should still be done over HTTPS if (action.equalsIgnoreCase("SetUserKeys")) { setUserKeys(request, response); return; } if (action.equalsIgnoreCase("CloudEC2Version")) { cloudEC2Version(request, response); return; } // -> authenticated calls try { if (!authenticateRequest(request, response)) return; if (action.equalsIgnoreCase("AllocateAddress")) allocateAddress(request, response); else if (action.equalsIgnoreCase("AssociateAddress")) associateAddress(request, response); else if (action.equalsIgnoreCase("AttachVolume")) attachVolume(request, response); else if (action.equalsIgnoreCase("AuthorizeSecurityGroupIngress")) authorizeSecurityGroupIngress(request, response); else if (action.equalsIgnoreCase("CreateImage")) createImage(request, response); else if (action.equalsIgnoreCase("CreateSecurityGroup")) createSecurityGroup(request, response); else if (action.equalsIgnoreCase("CreateSnapshot")) createSnapshot(request, response); else if (action.equalsIgnoreCase("CreateVolume")) createVolume(request, response); else if (action.equalsIgnoreCase("DeleteSecurityGroup")) deleteSecurityGroup(request, response); else if (action.equalsIgnoreCase("DeleteSnapshot")) deleteSnapshot(request, response); else if (action.equalsIgnoreCase("DeleteVolume")) deleteVolume(request, response); else if (action.equalsIgnoreCase("DeregisterImage")) deregisterImage(request, response); else if (action.equalsIgnoreCase("DescribeAddresses")) describeAddresses(request, response); else if (action.equalsIgnoreCase("DescribeAvailabilityZones")) describeAvailabilityZones(request, response); else if (action.equalsIgnoreCase("DescribeImageAttribute")) describeImageAttribute(request, response); else if (action.equalsIgnoreCase("DescribeImages")) describeImages(request, response); else if (action.equalsIgnoreCase("DescribeInstanceAttribute")) describeInstanceAttribute(request, response); else if (action.equalsIgnoreCase("DescribeInstances")) describeInstances(request, response); else if (action.equalsIgnoreCase("DescribeSecurityGroups")) describeSecurityGroups(request, response); else if (action.equalsIgnoreCase("DescribeSnapshots")) describeSnapshots(request, response); else if (action.equalsIgnoreCase("DescribeVolumes")) describeVolumes(request, response); else if (action.equalsIgnoreCase("DetachVolume")) detachVolume(request, response); else if (action.equalsIgnoreCase("DisassociateAddress")) disassociateAddress(request, response); else if (action.equalsIgnoreCase("ModifyImageAttribute")) modifyImageAttribute(request, response); else if (action.equalsIgnoreCase("RebootInstances")) rebootInstances(request, response); else if (action.equalsIgnoreCase("RegisterImage")) registerImage(request, response); else if (action.equalsIgnoreCase("ReleaseAddress")) releaseAddress(request, response); else if (action.equalsIgnoreCase("ResetImageAttribute")) resetImageAttribute(request, response); else if (action.equalsIgnoreCase("RevokeSecurityGroupIngress")) revokeSecurityGroupIngress(request, response); else if (action.equalsIgnoreCase("RunInstances")) runInstances(request, response); else if (action.equalsIgnoreCase("StartInstances")) startInstances(request, response); else if (action.equalsIgnoreCase("StopInstances")) stopInstances(request, response); else if (action.equalsIgnoreCase("TerminateInstances")) terminateInstances(request, response); else if (action.equalsIgnoreCase("SetCertificate")) setCertificate(request, response); else if (action.equalsIgnoreCase("DeleteCertificate")) deleteCertificate(request, response); else if (action.equalsIgnoreCase("SetOfferMapping")) setOfferMapping(request, response); else if (action.equalsIgnoreCase("DeleteOfferMapping")) deleteOfferMapping(request, response); else if (action.equalsIgnoreCase("CreateKeyPair")) createKeyPair(request, response); else if (action.equalsIgnoreCase("ImportKeyPair")) importKeyPair(request, response); else if (action.equalsIgnoreCase("DeleteKeyPair")) deleteKeyPair(request, response); else if (action.equalsIgnoreCase("DescribeKeyPairs")) describeKeyPairs(request, response); else if (action.equalsIgnoreCase("GetPasswordData")) getPasswordData(request, response); else { logger.error("Unsupported action " + action); throw new EC2ServiceException(ClientError.Unsupported, "This operation is not available"); } } catch (EC2ServiceException e) { response.setStatus(e.getErrorCode()); if (e.getCause() != null && e.getCause() instanceof AxisFault) faultResponse(response, ((AxisFault) e.getCause()).getFaultCode().getLocalPart(), e.getMessage()); else { logger.error("EC2ServiceException: " + e.getMessage(), e); endResponse(response, e.toString()); } } catch (PermissionDeniedException e) { logger.error("Unexpected exception: " + e.getMessage(), e); response.setStatus(403); endResponse(response, "Access denied"); } catch (Exception e) { logger.error("Unexpected exception: " + e.getMessage(), e); response.setStatus(500); endResponse(response, e.toString()); } finally { try { response.flushBuffer(); } catch (IOException e) { logger.error("Unexpected exception " + e.getMessage(), e); } } }
From source file:lucee.runtime.net.rpc.server.RPCServer.java
/** * Process a POST to the servlet by handing it off to the Axis Engine. * Here is where SOAP messages are received * @param req posted request/*from ww w. jav a 2 s . c om*/ * @param res respose * @throws ServletException trouble * @throws IOException different trouble */ public void doPost(HttpServletRequest req, HttpServletResponse res, Component component) throws ServletException, IOException { long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0; String soapAction = null; MessageContext msgContext = null; Message rspMsg = null; String contentType = null; InputStream is = null; try { AxisEngine engine = getEngine(); if (engine == null) { // !!! should return a SOAP fault... ServletException se = new ServletException(Messages.getMessage("noEngine00")); log.debug("No Engine!", se); throw se; } res.setBufferSize(1024 * 8); // provide performance boost. /** get message context w/ various properties set */ msgContext = createMessageContext(engine, req, res, component); ComponentController.set(msgContext); // ? OK to move this to 'getMessageContext', // ? where it would also be picked up for 'doGet()' ? if (securityProvider != null) { if (isDebug) { log.debug("securityProvider:" + securityProvider); } msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider); } is = req.getInputStream(); Message requestMsg = new Message(is, false, req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE), req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION)); // Transfer HTTP headers to MIME headers for request message. MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders(); for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) { String headerName = (String) e.nextElement(); for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements();) { String headerValue = (String) f.nextElement(); requestMimeHeaders.addHeader(headerName, headerValue); } } if (isDebug) { log.debug("Request Message:" + requestMsg); /* Set the request(incoming) message field in the context */ /**********************************************************/ } msgContext.setRequestMessage(requestMsg); String url = HttpUtils.getRequestURL(req).toString().toLowerCase(); msgContext.setProperty(MessageContext.TRANS_URL, url); // put character encoding of request to message context // in order to reuse it during the whole process. try { String reqEnc = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); if (reqEnc != null) msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, reqEnc); } catch (SOAPException e1) { } try { /** * Save the SOAPAction header in the MessageContext bag. * This will be used to tell the Axis Engine which service * is being invoked. This will save us the trouble of * having to parse the Request message - although we will * need to double-check later on that the SOAPAction header * does in fact match the URI in the body. */ // (is this last stmt true??? (I don't think so - Glen)) /********************************************************/ soapAction = getSoapAction(req); if (soapAction != null) { msgContext.setUseSOAPAction(true); msgContext.setSOAPActionURI(soapAction); } // Create a Session wrapper for the HTTP session. // These can/should be pooled at some point. // (Sam is Watching! :-) msgContext.setSession(new AxisHttpSession(req)); if (tlog.isDebugEnabled()) { t1 = System.currentTimeMillis(); } /* Invoke the Axis engine... */ /*****************************/ if (isDebug) { log.debug("Invoking Axis Engine."); //here we run the message by the engine } //msgContext.setProperty("disablePrettyXML", "false"); engine.invoke(msgContext); if (isDebug) { log.debug("Return from Axis Engine."); } if (tlog.isDebugEnabled()) { t2 = System.currentTimeMillis(); } rspMsg = msgContext.getResponseMessage(); // We used to throw exceptions on null response messages. // They are actually OK in certain situations (asynchronous // services), so fall through here and return an ACCEPTED // status code below. Might want to install a configurable // error check for this later. } catch (AxisFault fault) { //log and sanitize processAxisFault(fault); configureResponseFromAxisFault(res, fault); rspMsg = msgContext.getResponseMessage(); if (rspMsg == null) { rspMsg = new Message(fault); ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext); } } catch (Throwable t) { if (t instanceof InvocationTargetException) t = ((InvocationTargetException) t).getTargetException(); // Exception if (t instanceof Exception) { Exception e = (Exception) t; //other exceptions are internal trouble rspMsg = msgContext.getResponseMessage(); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); rspMsg = convertExceptionToAxisFault(e, rspMsg); ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext); } // throwable else { logException(t); //other exceptions are internal trouble rspMsg = msgContext.getResponseMessage(); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); rspMsg = new Message(new AxisFault(t.toString(), t)); ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext); } } } catch (AxisFault fault) { processAxisFault(fault); configureResponseFromAxisFault(res, fault); rspMsg = msgContext.getResponseMessage(); if (rspMsg == null) { rspMsg = new Message(fault); ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext); } } finally { IOUtil.closeEL(is); } if (tlog.isDebugEnabled()) { t3 = System.currentTimeMillis(); } // Send response back along the wire... if (rspMsg != null) { // Transfer MIME headers to HTTP headers for response message. MimeHeaders responseMimeHeaders = rspMsg.getMimeHeaders(); for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader responseMimeHeader = (MimeHeader) i.next(); res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue()); } // synchronize the character encoding of request and response String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); if (responseEncoding != null) { try { rspMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding); } catch (SOAPException e) { } } //determine content type from message response contentType = rspMsg.getContentType(msgContext.getSOAPConstants()); if (isDebug) log.debug("Returned Content-Type:" + contentType); // write result to response stream try { res.setContentType(contentType); rspMsg.writeTo(res.getOutputStream()); } catch (SOAPException e) { logException(e); } if (!res.isCommitted()) res.flushBuffer(); // Force it right now. } else { // No content, so just indicate accepted res.setStatus(202); } if (isDebug) { log.debug("Response sent."); log.debug("Exit: doPost()"); } if (tlog.isDebugEnabled()) { t4 = System.currentTimeMillis(); tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post=" + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "." + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName())); } }
From source file:org.ejbca.ui.web.pub.AutoEnrollServlet.java
/** * Recievies the request.//from w w w .j ava 2 s. co m */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.trace(">doPost"); try { AuthenticationToken internalAdmin = new AlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("AutoEnrollServlet: " + request.getRemoteAddr())); //Admin internalAdmin = Admin.getInternalAdmin(); GlobalConfiguration globalConfiguration = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); // Make sure we allow use of this Servlet if (!globalConfiguration.getAutoEnrollUse()) { log.info("Unauthorized access attempt from " + request.getRemoteAddr()); response.getOutputStream().println("Not allowed."); return; } int caid = globalConfiguration.getAutoEnrollCA(); if (caid == GlobalConfiguration.AUTOENROLL_DEFAULT_CA) { log.info("Configure a proper CA to use with enroll."); response.getOutputStream().println("Configure a proper CA to use with enroll."); return; } boolean debugRequest = "true".equalsIgnoreCase(request.getParameter("debug")); String debugInfo = ""; RequestHelper.setDefaultCharacterEncoding(request); if (debugRequest) { debugInfo += "getAttributeNames:\n"; Enumeration<?> enumeration = request.getAttributeNames(); while (enumeration.hasMoreElements()) { String temp = enumeration.nextElement().toString(); debugInfo += temp + " = " + request.getAttribute(temp) + "\n"; } debugInfo += "\ngetParameterNames:\n"; enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String temp = enumeration.nextElement().toString(); debugInfo += temp + " = " + request.getParameter(temp) + "\n"; } debugInfo += "\ngetHeaderNames:\n"; enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String temp = enumeration.nextElement().toString(); debugInfo += temp + " = " + request.getHeader(temp) + "\n"; } debugInfo += "Remote address: " + request.getRemoteAddr() + "\n"; log.info(debugInfo); } byte[] result = null; String requestData = MSCertTools.extractRequestFromRawData(request.getParameter("request")); if (requestData == null) { response.getOutputStream().println("No request supplied.."); return; } log.info("Got request: " + requestData); // The next line expects apache to forward the kerberos-authenticated user as X-Remote-User" String remoteUser = request.getHeader("X-Remote-User"); String usernameShort = StringTools.stripUsername(remoteUser.substring(0, remoteUser.indexOf("@"))) .replaceAll("/", ""); if (remoteUser == null || "".equals(remoteUser) || "(null)".equals(remoteUser)) { response.getOutputStream().println("X-Remote-User was not supplied.."); return; } MSPKCS10RequestMessage req = null; String certificateTemplate = null; String command = request.getParameter("command"); if (command != null && "status".equalsIgnoreCase(command)) { response.getOutputStream().println(returnStatus(internalAdmin, "Autoenrolled-" + usernameShort + "-" + request.getParameter("template"))); return; } else { // Default command "request" } req = new MSPKCS10RequestMessage(Base64.decode(requestData.getBytes())); certificateTemplate = req.getMSRequestInfoTemplateName(); int templateIndex = MSCertTools.getTemplateIndex(certificateTemplate); /* TODO: Lookup requesting entity in AD here to verify that only Machines request Machine Certificates etc.. Also check permissions like who is allowed to enroll for what if possible. */ // Create or edit a user "Autoenrolled-Username-Templatename" String username = "Autoenrolled-" + usernameShort + "-" + certificateTemplate; log.info("Got autoenroll request from " + remoteUser + " (" + username + ") for a " + certificateTemplate + "-certificate."); String fetchedSubjectDN = null; if (MSCertTools.isRequired(templateIndex, MSCertTools.GET_SUBJECTDN_FROM_AD, 0)) { fetchedSubjectDN = ActiveDirectoryTools.getUserDNFromActiveDirectory(globalConfiguration, usernameShort); } int certProfileId = MSCertTools.getOrCreateCertificateProfile(internalAdmin, templateIndex, certificateProfileSession); int endEntityProfileId; try { endEntityProfileId = MSCertTools.getOrCreateEndEndtityProfile(internalAdmin, templateIndex, certProfileId, caid, usernameShort, fetchedSubjectDN, raAdminSession, endEntityProfileSession); } catch (EndEntityProfileNotFoundException e) { String msg = "Could not retrieve required information from AD."; log.error(msg, e); response.getOutputStream().println(msg); return; } catch (IllegalArgumentException e) { String msg = "Could not retrieve required information from AD."; log.error(msg, e); response.getOutputStream().println(msg); return; } // Create user // The CA needs to use non-LDAP order and we need to have the SAN like "CN=Users, CN=Username, DC=com, DC=company".. why?? // TODO: fix this here.. or is this an general order issue? String subjectDN = fetchedSubjectDN; if (subjectDN == null) { if (MSCertTools.isRequired(templateIndex, DnComponents.COMMONNAME, 0)) { subjectDN = "CN=" + usernameShort; } } String subjectAN = ""; if (MSCertTools.isRequired(templateIndex, DnComponents.UPN, 0)) { subjectAN += (subjectAN.length() == 0 ? "" : ",") + "UPN=" + remoteUser; } if (MSCertTools.isRequired(templateIndex, DnComponents.GUID, 0)) { String reqGUID = req.getMSRequestInfoSubjectAltnames()[0]; subjectAN += (subjectAN.length() == 0 ? "" : ",") + "GUID=" + reqGUID; } if (MSCertTools.isRequired(templateIndex, DnComponents.DNSNAME, 0)) { String reqDNS = req.getMSRequestInfoSubjectAltnames()[1]; subjectAN += (subjectAN.length() == 0 ? "" : ",") + "DNSNAME=" + reqDNS; } log.info("sdn=" + subjectDN + ", san=" + subjectAN); debugInfo += "\nsdn=" + subjectDN + ", san=" + subjectAN + "\n"; EndEntityInformation userData = new EndEntityInformation(username, subjectDN, caid, subjectAN, null, EndEntityConstants.STATUS_NEW, new EndEntityType(EndEntityTypes.ENDUSER), endEntityProfileId, certProfileId, new Date(), new Date(), SecConst.TOKEN_SOFT_BROWSERGEN, 0, null); String password = PasswordGeneratorFactory .getInstance(PasswordGeneratorFactory.PASSWORDTYPE_LETTERSANDDIGITS).getNewPassword(8, 8); userData.setPassword(password); try { if (endEntityManagementSession.existsUser(username)) { endEntityManagementSession.changeUser(internalAdmin, userData, true); } else { endEntityManagementSession.addUser(internalAdmin, userData, true); } } catch (Exception e) { log.error("Could not add user " + username, e); } Certificate cert = null; debugInfo += "Request: " + requestData + "\n"; req.setUsername(username); req.setPassword(password); ResponseMessage resp; try { resp = signSession.createCertificate(internalAdmin, req, X509ResponseMessage.class, null); cert = CertTools.getCertfromByteArray(resp.getResponseMessage()); result = signSession.createPKCS7(internalAdmin, cert, true); debugInfo += "Resulting cert: " + new String(Base64.encode(result, true)) + "\n"; } catch (Exception e) { log.error("Noooo!!! ", e); response.getOutputStream().println("An error has occurred."); return; } if (debugRequest) { response.getOutputStream().println(StringEscapeUtils.escapeJavaScript(debugInfo)); } else { // Output the certificate ServletOutputStream os = response.getOutputStream(); os.print(RequestHelper.BEGIN_PKCS7_WITH_NL); os.print(new String(Base64.encode(result, true))); os.print(RequestHelper.END_PKCS7_WITH_NL); response.flushBuffer(); log.info("Sent cert to client"); } } catch (AuthorizationDeniedException e1) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e1.getMessage()); } log.trace("<doPost"); }
From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Post request/*from www .ja va 2s .c om*/ ***************************************************************************/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { boolean checkedContent = false; boolean legend = false; String strErrorMessage = ""; String serverUrl = request.getParameter("url"); log.info("POST param serverUrl: " + serverUrl); if (serverUrl.startsWith("legend")) { serverUrl = serverUrl.replace("legend", ""); serverUrl = serverUrl.replace("?", "&"); serverUrl = serverUrl.replaceFirst("&", "?"); legend = true; } serverUrl = checkTypeRequest(serverUrl); // log.info("serverUrl ckecked: " + serverUrl); if (!serverUrl.equals("ERROR")) { if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { PostMethod httppost = null; try { if (log.isDebugEnabled()) { Enumeration<?> e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getHeader(name); log.debug("request header:" + name + ":" + value); } } HttpClient client = new HttpClient(); httppost = new PostMethod(serverUrl); // PATH httppost.setDoAuthentication(false); httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // FIN_PATH // PATH_MAPEAEDITA_SECURITY - AP // PATCH_TICKET_MJM-20112405-POST String authorizationValue = request.getHeader(AUTHORIZATION); // ADD_SECURITY_20091210 if (authorizationValue == null) { // The 'Authorization' header must be in this form -> // Authorization: Basic <encodedLogin> // 'encodedLogin' is a string in the form 'user:pass' // that has been encoded by way of the Base64 algorithm. // More info on this can be found at // http://en.wikipedia.org/wiki/Basic_access_authentication String user = (String) request.getSession().getAttribute("user"); String pass = (String) request.getSession().getAttribute("pass"); if (user != null && pass != null) { String userAndPass = user + ":" + pass; String encodedLogin = new String( org.apache.commons.codec.binary.Base64.encodeBase64(userAndPass.getBytes())); httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin); } else { // MJM - 20110520 String ticketParameter = request.getParameter("ticket"); if (ticketParameter != null) { ticketParameter = ticketParameter.trim(); if (!ticketParameter.isEmpty()) { Ticket ticket = TicketFactory.createInstance(); try { Map<String, String> props = ticket.getProperties(ticketParameter); user = props.get("user"); pass = props.get("pass"); String userAndPass = user + ":" + pass; String encodedLogin = new String(org.apache.commons.codec.binary.Base64 .encodeBase64(userAndPass.getBytes())); httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin); } catch (Exception e) { log.info("-------------------------------------------"); log.info("EXCEPCTION THROWED BY PROXYREDIRECT CLASS"); log.info("METHOD: doPost"); log.info("TICKET VALUE: " + ticketParameter); log.info("-------------------------------------------"); } } } } } else { httppost.addRequestHeader(AUTHORIZATION, authorizationValue); } // FIN_PATH_TICKET_MJM-20112405-POST // FIN_PATH_MAPEAEDITA_SECURITY - AP String body = inputStreamAsString(request.getInputStream()); StringRequestEntity bodyEntity = new StringRequestEntity(body, null, null); if (0 == httppost.getParameters().length) { log.debug("No Name/Value pairs found ... pushing as received"); // PATCH httppost.setRequestEntity(bodyEntity); // PATCH } if (log.isDebugEnabled()) { log.debug("Body = " + body); NameValuePair[] nameValuePairs = httppost.getParameters(); log.debug("NameValuePairs found: " + nameValuePairs.length); for (int i = 0; i < nameValuePairs.length; ++i) { log.debug("parameters:" + nameValuePairs[i].toString()); } } if (!legend) client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); if (soap) { httppost.addRequestHeader("SOAPAction", serverUrl); } client.executeMethod(httppost); // PATH_FOLLOW_REDIRECT_POST int j = 0; String redirectLocation; Header locationHeader = httppost.getResponseHeader("location"); while (locationHeader != null && j < numMaxRedirects) { redirectLocation = locationHeader.getValue(); // AGG 20111304 Aadimos el cuerpo de la peticin POST a // la nueva peticin redirigida // String bodyPost = httppost.getResponseBodyAsString(); StringRequestEntity bodyEntityPost = new StringRequestEntity(body, null, null); httppost.releaseConnection(); httppost = new PostMethod(redirectLocation); // AGG 20110912 Aadidas cabeceras peticin SOAP if (redirectLocation.toLowerCase().contains("wsdl")) { redirectLocation = serverUrl.replace("?wsdl", ""); httppost.addRequestHeader("SOAPAction", redirectLocation); httppost.addRequestHeader("Content-type", "text/xml"); } httppost.setRequestEntity(bodyEntityPost); client.executeMethod(httppost); locationHeader = httppost.getResponseHeader("location"); j++; } log.info("Number of followed redirections: " + j); if (locationHeader != null && j == numMaxRedirects) { log.error("The maximum number of redirects (" + numMaxRedirects + ") is exceed."); } // FIN_PATH_FOLLOW_REDIRECT_POST if (log.isDebugEnabled()) { Header[] responseHeaders = httppost.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; ++i) { String headerName = responseHeaders[i].getName(); String headerValue = responseHeaders[i].getValue(); log.debug("responseHeaders:" + headerName + "=" + headerValue); } } // dump response to out if (httppost.getStatusCode() == HttpStatus.SC_OK) { // PATH_SECURITY_PROXY - AG Header[] respHeaders = httppost.getResponseHeaders(); int compSize = httppost.getResponseBody().length; ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders)); String headersString = headerList.toString(); checkedContent = checkContent(headersString, compSize, serverUrl); // FIN_PATH_SECURITY_PROXY - AG if (checkedContent == true) { /* * checks if it has requested an getfeatureinfo to modify the response content * type. */ String requesteredUrl = request.getParameter("url"); if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("text/plain"); } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("application/gml+xml"); } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("text/html"); } else if (requesteredUrl.toLowerCase().contains("mapeaop=geosearch") || requesteredUrl.toLowerCase().contains("mapeaop=geoprint")) { response.setContentType("application/json"); } else { response.setContentType("text/xml"); } if (legend) { String responseBody = httppost.getResponseBodyAsString(); if (responseBody.contains("ServiceExceptionReport") && serverUrl.contains("LegendGraphic")) { response.sendRedirect("Componente/img/blank.gif"); } else { response.setContentLength(responseBody.length()); PrintWriter out = response.getWriter(); out.print(responseBody); response.flushBuffer(); } } else { // Patch_AGG 20112505 Prevents IE cache if (request.getProtocol().compareTo("HTTP/1.0") == 0) { response.setHeader("Pragma", "no-cache"); } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) { response.setHeader("Cache-Control", "no-cache"); } response.setDateHeader("Expires", -1); // END patch // Copy request to response InputStream st = httppost.getResponseBodyAsStream(); final ServletOutputStream sos = response.getOutputStream(); IOUtils.copy(st, sos); } } else { strErrorMessage += errorType; log.error(strErrorMessage); } } else if (httppost.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); response.addHeader(WWW_AUTHENTICATE, httppost.getResponseHeader(WWW_AUTHENTICATE).getValue()); } else { strErrorMessage = "Unexpected failure: ".concat(httppost.getStatusLine().toString()) .concat(" ").concat(httppost.getResponseBodyAsString()); log.error("Unexpected failure: " + httppost.getStatusLine().toString()); } httppost.releaseConnection(); // AGG 20110927 Avoid Throwable (change it with exceptions) } catch (Exception e) { log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e); } finally { if (httppost != null) { httppost.releaseConnection(); } } } else { strErrorMessage += "Only HTTP(S) protocol supported"; log.error("Only HTTP(S) protocol supported"); // throw new // ServletException("only HTTP(S) protocol supported"); } } // There are errors. if (!strErrorMessage.equals("") || serverUrl.equals("ERROR")) { if (strErrorMessage.equals("") == true) { strErrorMessage = "Error en el parametro url de entrada"; } // String errorXML = strErrorMessage; String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>" + strErrorMessage + "</descripcion></error>"; response.setContentType("text/xml"); try { PrintWriter out = response.getWriter(); out.print(errorXML); response.flushBuffer(); } catch (Exception e) { log.error(e); } } log.info("-------- End POST method --------"); }