List of usage examples for javax.servlet.http HttpServletRequest getRemotePort
public int getRemotePort();
From source file:org.apache.camel.component.websocket.SignalkWebSocketServlet.java
public void init() throws ServletException { try {/*from w ww.j a v a2 s. c o 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:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java
/** {@inheritDoc} */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String prevThreadName = Thread.currentThread().getName(); try {//from w w w.ja va 2 s .c o m Thread.currentThread().setName(contextPath); HttpServletRequest rqst = (HttpServletRequest) request; HttpServletResponse rsp = (HttpServletResponse) response; if (LOG.isDebugEnabled()) { StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/") .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort()); b.append("\n The Scheme is " + rqst.getScheme()); b.append("\n The Path Info is " + rqst.getPathInfo()); b.append("\n The Translated Path Info is " + rqst.getPathTranslated()); b.append("\n The Context Path is " + rqst.getContextPath()); b.append("\n The Query String is " + rqst.getQueryString()); b.append("\n The Request URI is " + rqst.getRequestURI()); b.append("\n The Request URL is " + rqst.getRequestURL()); b.append("\n The Servlet Path is " + rqst.getServletPath()); LOG.debug(b.toString()); } LdapRoleEntry ldapent = new LdapRoleEntry(); // check ip address String userIp = rqst.getRemoteAddr(); try { boolean isAuthorized = getLdapRoleEntryFromUserIp(userIp, ldapent); if (!isAuthorized) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "IP " + userIp + " is not authorized to access"); return; } } catch (NamingException ne) { throw new IOException("NamingException while searching ldap" + ne.toString()); } // since we cannot pass ugi object cross context as they are from // different classloaders in different war file, we have to use String attribute. rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ldapent.userId); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.paths", ldapent.paths); LOG.info("User: " + ldapent.userId + " Request: " + rqst.getPathInfo() + " From: " + rqst.getRemoteAddr()); chain.doFilter(request, response); } finally { Thread.currentThread().setName(prevThreadName); } }
From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java
/** {@inheritDoc} */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest rqst = (HttpServletRequest) request; HttpServletResponse rsp = (HttpServletResponse) response; if (LOG.isDebugEnabled()) { StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/") .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort()); @SuppressWarnings("unchecked") Enumeration<String> e = rqst.getAttributeNames(); for (; e.hasMoreElements();) { String attribute = e.nextElement(); b.append("\n " + attribute + " => " + rqst.getAttribute(attribute)); }/*w ww . j av a 2 s . co m*/ X509Certificate[] userCerts = (X509Certificate[]) rqst .getAttribute("javax.servlet.request.X509Certificate"); if (userCerts != null) for (X509Certificate cert : userCerts) b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName()); b.append("\n The Scheme is " + rqst.getScheme()); b.append("\n The Auth Type is " + rqst.getAuthType()); b.append("\n The Path Info is " + rqst.getPathInfo()); b.append("\n The Translated Path Info is " + rqst.getPathTranslated()); b.append("\n The Context Path is " + rqst.getContextPath()); b.append("\n The Query String is " + rqst.getQueryString()); b.append("\n The Remote User is " + rqst.getRemoteUser()); b.append("\n The User Principal is " + rqst.getUserPrincipal()); b.append("\n The Request URI is " + rqst.getRequestURI()); b.append("\n The Request URL is " + rqst.getRequestURL()); b.append("\n The Servlet Path is " + rqst.getServletPath()); LOG.debug(b.toString()); } boolean unitTest = false; if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null) unitTest = true; if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) { boolean isAuthorized = false; X509Certificate[] certs = (X509Certificate[]) rqst .getAttribute("javax.servlet.request.X509Certificate"); if (unitTest) { try { LOG.debug("==> Entering https unit test"); String SslPath = rqst.getParameter("SslPath"); InputStream inStream = new FileInputStream(SslPath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); certs = new X509Certificate[] { cert }; } catch (Exception e) { // do nothing here } } if (certs == null || certs.length == 0) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received"); LOG.info("No Client SSL certificate received"); return; } for (X509Certificate cert : certs) { try { cert.checkValidity(); } catch (CertificateExpiredException e) { LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired"); return; } catch (CertificateNotYetValidException e) { LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid"); return; } } String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*"); String userID = null; for (String s : tokens) { if (s.startsWith("CN=")) { userID = s; break; } } if (userID == null || userID.length() < 4) { LOG.info("Can't retrieve user ID from SSL certificate"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate"); return; } userID = userID.substring(3); String servletPath = rqst.getServletPath(); if (unitTest) { servletPath = rqst.getParameter("TestSevletPathInfo"); LOG.info("this is for unit test purpose only"); } if (HFTP_PATTERN.matcher(servletPath).matches()) { // request is an HSFTP request if (FILEPATH_PATTERN.matcher(servletPath).matches()) { // file path as part of the URL isAuthorized = checkPath(userID, certs[0], rqst.getPathInfo() != null ? rqst.getPathInfo() : "/"); } else { // file path is stored in "filename" parameter isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename")); } } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) { Configuration conf = new Configuration(false); conf.addResource("hdfsproxy-default.xml"); Map<String, Set<Path>> permsMap = getPermMap(conf); Map<String, Set<BigInteger>> certsMap = getCertsMap(conf); if (permsMap == null || certsMap == null) { LOG.warn("Permission files reloading failed"); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Permission files reloading failed"); return; } ProxyFilter.permsMap = permsMap; ProxyFilter.certsMap = certsMap; LOG.info("User permissions and user certs files reloaded"); rsp.setStatus(HttpServletResponse.SC_OK); return; } if (!isAuthorized) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access"); return; } // request is authorized, set ugi for servlets UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID); rqst.setAttribute("authorized.ugi", ugi); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID); } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes String ugi = rqst.getParameter("ugi"); if (ugi != null) { rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi)); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]); } } chain.doFilter(request, response); }
From source file:org.apache.nifi.processors.standard.servlets.ListenHTTPServlet.java
@Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final ProcessContext context = processContext; ProcessSessionFactory sessionFactory; do {//from w w w .j a v a 2 s .c om sessionFactory = sessionFactoryHolder.get(); if (sessionFactory == null) { try { Thread.sleep(10); } catch (final InterruptedException e) { } } } while (sessionFactory == null); final ProcessSession session = sessionFactory.createSession(); FlowFile flowFile = null; String holdUuid = null; String foundSubject = null; try { final long n = filesReceived.getAndIncrement() % FILES_BEFORE_CHECKING_DESTINATION_SPACE; if (n == 0 || !spaceAvailable.get()) { if (context.getAvailableRelationships().isEmpty()) { spaceAvailable.set(false); if (logger.isDebugEnabled()) { logger.debug("Received request from " + request.getRemoteHost() + " but no space available; Indicating Service Unavailable"); } response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } else { spaceAvailable.set(true); } } response.setHeader("Content-Type", MediaType.TEXT_PLAIN); final boolean contentGzipped = Boolean.parseBoolean(request.getHeader(GZIPPED_HEADER)); final X509Certificate[] certs = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); foundSubject = DEFAULT_FOUND_SUBJECT; if (certs != null && certs.length > 0) { for (final X509Certificate cert : certs) { foundSubject = cert.getSubjectDN().getName(); if (authorizedPattern.matcher(foundSubject).matches()) { break; } else { logger.warn("Rejecting transfer attempt from " + foundSubject + " because the DN is not authorized, host=" + request.getRemoteHost()); response.sendError(HttpServletResponse.SC_FORBIDDEN, "not allowed based on dn"); return; } } } final String destinationVersion = request.getHeader(PROTOCOL_VERSION_HEADER); Integer protocolVersion = null; if (destinationVersion != null) { try { protocolVersion = Integer.valueOf(destinationVersion); } catch (final NumberFormatException e) { // Value was invalid. Treat as if the header were missing. } } final boolean destinationIsLegacyNiFi = (protocolVersion == null); final boolean createHold = Boolean.parseBoolean(request.getHeader(FLOWFILE_CONFIRMATION_HEADER)); final String contentType = request.getContentType(); final InputStream unthrottled = contentGzipped ? new GZIPInputStream(request.getInputStream()) : request.getInputStream(); final InputStream in = (streamThrottler == null) ? unthrottled : streamThrottler.newThrottledInputStream(unthrottled); if (logger.isDebugEnabled()) { logger.debug("Received request from " + request.getRemoteHost() + ", createHold=" + createHold + ", content-type=" + contentType + ", gzip=" + contentGzipped); } final AtomicBoolean hasMoreData = new AtomicBoolean(false); final FlowFileUnpackager unpackager; if (APPLICATION_FLOW_FILE_V3.equals(contentType)) { unpackager = new FlowFileUnpackagerV3(); } else if (APPLICATION_FLOW_FILE_V2.equals(contentType)) { unpackager = new FlowFileUnpackagerV2(); } else if (APPLICATION_FLOW_FILE_V1.equals(contentType)) { unpackager = new FlowFileUnpackagerV1(); } else { unpackager = null; } final Set<FlowFile> flowFileSet = new HashSet<>(); do { final long startNanos = System.nanoTime(); final Map<String, String> attributes = new HashMap<>(); flowFile = session.create(); flowFile = session.write(flowFile, new OutputStreamCallback() { @Override public void process(final OutputStream rawOut) throws IOException { try (final BufferedOutputStream bos = new BufferedOutputStream(rawOut, 65536)) { if (unpackager == null) { IOUtils.copy(in, bos); hasMoreData.set(false); } else { attributes.putAll(unpackager.unpackageFlowFile(in, bos)); if (destinationIsLegacyNiFi) { if (attributes.containsKey("nf.file.name")) { // for backward compatibility with old nifi... attributes.put(CoreAttributes.FILENAME.key(), attributes.remove("nf.file.name")); } if (attributes.containsKey("nf.file.path")) { attributes.put(CoreAttributes.PATH.key(), attributes.remove("nf.file.path")); } } hasMoreData.set(unpackager.hasMoreData()); } } } }); final long transferNanos = System.nanoTime() - startNanos; final long transferMillis = TimeUnit.MILLISECONDS.convert(transferNanos, TimeUnit.NANOSECONDS); // put metadata on flowfile final String nameVal = request.getHeader(CoreAttributes.FILENAME.key()); if (StringUtils.isNotBlank(nameVal)) { attributes.put(CoreAttributes.FILENAME.key(), nameVal); } // put arbitrary headers on flow file for (Enumeration<String> headerEnum = request.getHeaderNames(); headerEnum.hasMoreElements();) { String headerName = headerEnum.nextElement(); if (headerPattern != null && headerPattern.matcher(headerName).matches()) { String headerValue = request.getHeader(headerName); attributes.put(headerName, headerValue); } } String sourceSystemFlowFileIdentifier = attributes.get(CoreAttributes.UUID.key()); if (sourceSystemFlowFileIdentifier != null) { sourceSystemFlowFileIdentifier = "urn:nifi:" + sourceSystemFlowFileIdentifier; // If we receveied a UUID, we want to give the FlowFile a new UUID and register the sending system's // identifier as the SourceSystemFlowFileIdentifier field in the Provenance RECEIVE event attributes.put(CoreAttributes.UUID.key(), UUID.randomUUID().toString()); } flowFile = session.putAllAttributes(flowFile, attributes); session.getProvenanceReporter().receive(flowFile, request.getRequestURL().toString(), sourceSystemFlowFileIdentifier, "Remote DN=" + foundSubject, transferMillis); flowFile = session.putAttribute(flowFile, "restlistener.remote.source.host", request.getRemoteHost()); flowFile = session.putAttribute(flowFile, "restlistener.remote.user.dn", foundSubject); flowFileSet.add(flowFile); if (holdUuid == null) { holdUuid = flowFile.getAttribute(CoreAttributes.UUID.key()); } } while (hasMoreData.get()); if (createHold) { String uuid = (holdUuid == null) ? UUID.randomUUID().toString() : holdUuid; if (flowFileMap.containsKey(uuid)) { uuid = UUID.randomUUID().toString(); } final FlowFileEntryTimeWrapper wrapper = new FlowFileEntryTimeWrapper(session, flowFileSet, System.currentTimeMillis()); FlowFileEntryTimeWrapper previousWrapper; do { previousWrapper = flowFileMap.putIfAbsent(uuid, wrapper); if (previousWrapper != null) { uuid = UUID.randomUUID().toString(); } } while (previousWrapper != null); response.setStatus(HttpServletResponse.SC_SEE_OTHER); final String ackUri = "/" + basePath + "/holds/" + uuid; response.addHeader(LOCATION_HEADER_NAME, ackUri); response.addHeader(LOCATION_URI_INTENT_NAME, LOCATION_URI_INTENT_VALUE); response.getOutputStream().write(ackUri.getBytes("UTF-8")); if (logger.isDebugEnabled()) { logger.debug( "Ingested {} from Remote Host: [{}] Port [{}] SubjectDN [{}]; placed hold on these {} files with ID {}", new Object[] { flowFileSet, request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFileSet.size(), uuid }); } } else { response.setStatus(HttpServletResponse.SC_OK); logger.info( "Received from Remote Host: [{}] Port [{}] SubjectDN [{}]; transferring to 'success' {}", new Object[] { request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFile }); session.transfer(flowFileSet, ListenHTTP.RELATIONSHIP_SUCCESS); session.commit(); } } catch (final Throwable t) { session.rollback(); if (flowFile == null) { logger.error("Unable to receive file from Remote Host: [{}] SubjectDN [{}] due to {}", new Object[] { request.getRemoteHost(), foundSubject, t }); } else { logger.error("Unable to receive file {} from Remote Host: [{}] SubjectDN [{}] due to {}", new Object[] { flowFile, request.getRemoteHost(), foundSubject, t }); } response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.toString()); } }
From source file:org.apache.nifi.web.api.DataTransferResource.java
private Peer constructPeer(final HttpServletRequest req, final InputStream inputStream, final OutputStream outputStream, final String portId, final String transactionId) { String clientHostName = req.getRemoteHost(); try {/*ww w . j a va 2 s. co m*/ // req.getRemoteHost returns IP address, try to resolve hostname to be consistent with RAW protocol. final InetAddress clientAddress = InetAddress.getByName(clientHostName); clientHostName = clientAddress.getHostName(); } catch (UnknownHostException e) { logger.info("Failed to resolve client hostname {}, due to {}", clientHostName, e.getMessage()); } final int clientPort = req.getRemotePort(); final PeerDescription peerDescription = new PeerDescription(clientHostName, clientPort, req.isSecure()); final NiFiUser user = NiFiUserUtils.getNiFiUser(); final String userDn = user == null ? null : user.getIdentity(); final HttpServerCommunicationsSession commSession = new HttpServerCommunicationsSession(inputStream, outputStream, transactionId, userDn); boolean useCompression = false; final String useCompressionStr = req.getHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION); if (!isEmpty(useCompressionStr) && Boolean.valueOf(useCompressionStr)) { useCompression = true; } final String requestExpiration = req.getHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION); final String batchCount = req.getHeader(HANDSHAKE_PROPERTY_BATCH_COUNT); final String batchSize = req.getHeader(HANDSHAKE_PROPERTY_BATCH_SIZE); final String batchDuration = req.getHeader(HANDSHAKE_PROPERTY_BATCH_DURATION); commSession.putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, portId); commSession.putHandshakeParam(HandshakeProperty.GZIP, String.valueOf(useCompression)); if (!isEmpty(requestExpiration)) { commSession.putHandshakeParam(REQUEST_EXPIRATION_MILLIS, requestExpiration); } if (!isEmpty(batchCount)) { commSession.putHandshakeParam(BATCH_COUNT, batchCount); } if (!isEmpty(batchSize)) { commSession.putHandshakeParam(BATCH_SIZE, batchSize); } if (!isEmpty(batchDuration)) { commSession.putHandshakeParam(BATCH_DURATION, batchDuration); } if (peerDescription.isSecure()) { final NiFiUser nifiUser = NiFiUserUtils.getNiFiUser(); logger.debug("initiating peer, nifiUser={}", nifiUser); commSession.setUserDn(nifiUser.getIdentity()); } // TODO: Followed how SocketRemoteSiteListener define peerUrl and clusterUrl, but it can be more meaningful values, especially for clusterUrl. final String peerUrl = "nifi://" + clientHostName + ":" + clientPort; final String clusterUrl = "nifi://localhost:" + req.getLocalPort(); return new Peer(peerDescription, commSession, peerUrl, clusterUrl); }
From source file:org.apache.openaz.xacml.rest.XACMLRest.java
/** * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging. * * @param request - Servlet request (from a POST/GET/PUT/etc.) *///w ww .jav a 2 s . co m public static void dumpRequest(HttpServletRequest request) { if (logger.isDebugEnabled()) { // special-case for receiving heartbeat - don't need to repeatedly output all of the information // in multiple lines if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))) { logger.debug("GET type=hb : heartbeat received"); return; } logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " " + request.getRemotePort()); logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort()); Enumeration<String> en = request.getHeaderNames(); logger.debug("Headers:"); while (en.hasMoreElements()) { String element = en.nextElement(); Enumeration<String> values = request.getHeaders(element); while (values.hasMoreElements()) { String value = values.nextElement(); logger.debug(element + ":" + value); } } logger.debug("Attributes:"); en = request.getAttributeNames(); while (en.hasMoreElements()) { String element = en.nextElement(); logger.debug(element + ":" + request.getAttribute(element)); } logger.debug("ContextPath: " + request.getContextPath()); if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) { // POST and PUT are allowed to have parameters in the content, but in our usage the parameters // are always in the Query string. // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it // might contain a Policy file). // Unfortunately the request.getParameterMap method reads the content to see if there are any // parameters, // and once the content is read it cannot be read again. // Thus for PUT and POST we must avoid reading the content here so that the main code can read // it. logger.debug("Query String:" + request.getQueryString()); try { if (request.getInputStream() == null) { logger.debug("Content: No content inputStream"); } else { logger.debug("Content available: " + request.getInputStream().available()); } } catch (Exception e) { logger.debug("Content: inputStream exception: " + e.getMessage() + "; (May not be relevant)"); } } else { logger.debug("Parameters:"); Map<String, String[]> params = request.getParameterMap(); Set<String> keys = params.keySet(); for (String key : keys) { String[] values = params.get(key); logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : "")); } } logger.debug("Request URL:" + request.getRequestURL()); } }
From source file:org.apache.pulsar.proxy.server.AdminProxyHandler.java
@Override protected String rewriteTarget(HttpServletRequest request) { StringBuilder url = new StringBuilder(); boolean isFunctionsRestRequest = false; String requestUri = request.getRequestURI(); if (requestUri.startsWith("/admin/v2/functions") || requestUri.startsWith("/admin/functions")) { isFunctionsRestRequest = true;// w ww. j a va 2 s .c o m } if (isFunctionsRestRequest && !isBlank(functionWorkerWebServiceUrl)) { url.append(functionWorkerWebServiceUrl); } else if (isBlank(brokerWebServiceUrl)) { try { ServiceLookupData availableBroker = discoveryProvider.nextBroker(); if (config.isTlsEnabledWithBroker()) { url.append(availableBroker.getWebServiceUrlTls()); } else { url.append(availableBroker.getWebServiceUrl()); } if (LOG.isDebugEnabled()) { LOG.debug("[{}:{}] Selected active broker is {}", request.getRemoteAddr(), request.getRemotePort(), url.toString()); } } catch (Exception e) { LOG.warn("[{}:{}] Failed to get next active broker {}", request.getRemoteAddr(), request.getRemotePort(), e.getMessage(), e); return null; } } else { url.append(brokerWebServiceUrl); } if (url.lastIndexOf("/") == url.length() - 1) { url.deleteCharAt(url.lastIndexOf("/")); } url.append(requestUri); String query = request.getQueryString(); if (query != null) { url.append("?").append(query); } URI rewrittenUrl = URI.create(url.toString()).normalize(); if (!validateDestination(rewrittenUrl.getHost(), rewrittenUrl.getPort())) { return null; } return rewrittenUrl.toString(); }
From source file:org.apache.pulsar.websocket.ReaderHandler.java
public ReaderHandler(WebSocketService service, HttpServletRequest request, ServletUpgradeResponse response) { super(service, request, response); final int receiverQueueSize = getReceiverQueueSize(); this.maxPendingMessages = (receiverQueueSize == 0) ? 1 : receiverQueueSize; this.numMsgsDelivered = new LongAdder(); this.numBytesDelivered = new LongAdder(); if (!checkAuth(response)) { return;//from ww w. j av a2 s . co m } try { ReaderBuilder<byte[]> builder = service.getPulsarClient().newReader().topic(topic.toString()) .startMessageId(getMessageId()).receiverQueueSize(receiverQueueSize); if (queryParams.containsKey("readerName")) { builder.readerName(queryParams.get("readerName")); } this.reader = builder.create(); this.subscription = ((ReaderImpl<?>) this.reader).getConsumer().getSubscription(); if (!this.service.addReader(this)) { log.warn("[{}:{}] Failed to add reader handler for topic {}", request.getRemoteAddr(), request.getRemotePort(), topic); } } catch (Exception e) { log.warn("[{}:{}] Failed in creating reader {} on topic {}", request.getRemoteAddr(), request.getRemotePort(), subscription, topic, e); try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create reader: " + e.getMessage()); } catch (IOException e1) { log.warn("[{}:{}] Failed to send error: {}", request.getRemoteAddr(), request.getRemotePort(), e1.getMessage(), e1); } } }
From source file:org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet.java
private HttpManagementActor createHttpManagementActor(HttpServletRequest request) { return new HttpManagementActor(_rootLogger, request.getRemoteAddr(), request.getRemotePort()); }
From source file:org.asynchttpclient.test.EchoHandler.java
@Override public void handle(String pathInContext, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { LOGGER.debug("Echo received request {} on path {}", request, pathInContext); if (httpRequest.getHeader("X-HEAD") != null) { httpResponse.setContentLength(1); }// w w w . j a v a2 s. c o m if (httpRequest.getHeader("X-ISO") != null) { httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_ISO_8859_1_CHARSET); } else { httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_UTF_8_CHARSET); } if (request.getMethod().equalsIgnoreCase("OPTIONS")) { httpResponse.addHeader("Allow", "GET,HEAD,POST,OPTIONS,TRACE"); } Enumeration<String> e = httpRequest.getHeaderNames(); String headerName; while (e.hasMoreElements()) { headerName = e.nextElement(); if (headerName.startsWith("LockThread")) { final int sleepTime = httpRequest.getIntHeader(headerName); try { Thread.sleep(sleepTime == -1 ? 40 : sleepTime * 1000); } catch (InterruptedException ex) { // } } if (headerName.startsWith("X-redirect")) { httpResponse.sendRedirect(httpRequest.getHeader("X-redirect")); return; } httpResponse.addHeader("X-" + headerName, httpRequest.getHeader(headerName)); } String pathInfo = httpRequest.getPathInfo(); if (pathInfo != null) httpResponse.addHeader("X-pathInfo", pathInfo); String queryString = httpRequest.getQueryString(); if (queryString != null) httpResponse.addHeader("X-queryString", queryString); httpResponse.addHeader("X-KEEP-ALIVE", httpRequest.getRemoteAddr() + ":" + httpRequest.getRemotePort()); Cookie[] cs = httpRequest.getCookies(); if (cs != null) { for (Cookie c : cs) { httpResponse.addCookie(c); } } Enumeration<String> i = httpRequest.getParameterNames(); if (i.hasMoreElements()) { StringBuilder requestBody = new StringBuilder(); while (i.hasMoreElements()) { headerName = i.nextElement(); httpResponse.addHeader("X-" + headerName, httpRequest.getParameter(headerName)); requestBody.append(headerName); requestBody.append("_"); } if (requestBody.length() > 0) { String body = requestBody.toString(); httpResponse.getOutputStream().write(body.getBytes()); } } String requestBodyLength = httpRequest.getHeader("X-" + CONTENT_LENGTH); if (requestBodyLength != null) { byte[] requestBodyBytes = IOUtils.toByteArray(httpRequest.getInputStream()); int total = requestBodyBytes.length; httpResponse.addIntHeader("X-" + CONTENT_LENGTH, total); String md5 = TestUtils.md5(requestBodyBytes, 0, total); httpResponse.addHeader(CONTENT_MD5.toString(), md5); httpResponse.getOutputStream().write(requestBodyBytes, 0, total); } else { int size = 16384; if (httpRequest.getContentLength() > 0) { size = httpRequest.getContentLength(); } if (size > 0) { int read = 0; while (read > -1) { byte[] bytes = new byte[size]; read = httpRequest.getInputStream().read(bytes); if (read > 0) { httpResponse.getOutputStream().write(bytes, 0, read); } } } } request.setHandled(true); httpResponse.getOutputStream().flush(); // FIXME don't always close, depends on the test, cf ReactiveStreamsTest httpResponse.getOutputStream().close(); }