List of usage examples for org.apache.http.protocol HttpContext getAttribute
Object getAttribute(String str);
From source file:org.apache.synapse.transport.nhttp.ServerHandler.java
/** * Shutdown the connection ignoring any IO errors during the process * @param conn the connection to be shutdown * @param isError whether shutdown is due to an error * @param errorMsg error message if shutdown happens on error *///from w w w . j a v a 2s . c om private void shutdownConnection(final NHttpServerConnection conn, boolean isError, String errorMsg) { SharedOutputBuffer outputBuffer = (SharedOutputBuffer) conn.getContext() .getAttribute(RESPONSE_SOURCE_BUFFER); if (outputBuffer != null) { outputBuffer.close(); } SharedInputBuffer inputBuffer = (SharedInputBuffer) conn.getContext().getAttribute(REQUEST_SINK_BUFFER); if (inputBuffer != null) { inputBuffer.close(); } if (log.isWarnEnabled() && (isError || log.isDebugEnabled()) && conn instanceof HttpInetConnection) { HttpInetConnection inetConnection = (HttpInetConnection) conn; InetAddress remoteAddress = inetConnection.getRemoteAddress(); int remotePort = inetConnection.getRemotePort(); String msg; if (remotePort != -1 && remoteAddress != null) { // If connection is still alive msg = "Connection from remote address : " + remoteAddress + ":" + remotePort + " to local address : " + inetConnection.getLocalAddress() + ":" + inetConnection.getLocalPort() + " is closed!" + (errorMsg != null ? " - On error : " + errorMsg : ""); } else { // if connection is already closed. obtain params from http context HttpContext httpContext = conn.getContext(); msg = "Connection from remote address : " + httpContext.getAttribute(NhttpConstants.CLIENT_REMOTE_ADDR) + ":" + httpContext.getAttribute(NhttpConstants.CLIENT_REMOTE_PORT) + " to local address : " + inetConnection.getLocalAddress() + ":" + inetConnection.getLocalPort() + " is closed!" + (errorMsg != null ? " - On error : " + errorMsg : ""); } if (isError) { log.warn(msg); } else { log.debug(msg); } } synchronized (this) { if (!activeConnections.isEmpty() && activeConnections.remove(conn) && log.isDebugEnabled()) { log.debug("Removing the connection : " + conn + " from pool of size : " + activeConnections.size()); } } try { conn.shutdown(); } catch (IOException ignore) { } }
From source file:org.apache.synapse.transport.passthru.SourceHandler.java
public void outputReady(NHttpServerConnection conn, ContentEncoder encoder) { try {/* w w w. j ava 2s.c o m*/ ProtocolState protocolState = SourceContext.getState(conn); //special case to handle WSDLs if (protocolState == ProtocolState.WSDL_RESPONSE_DONE) { // we need to shut down if the shutdown flag is set HttpContext context = conn.getContext(); ContentOutputBuffer outBuf = (ContentOutputBuffer) context .getAttribute("synapse.response-source-buffer"); int bytesWritten = outBuf.produceContent(encoder); if (metrics != null && bytesWritten > 0) { metrics.incrementBytesSent(bytesWritten); } conn.requestInput(); if (outBuf instanceof SimpleOutputBuffer && !((SimpleOutputBuffer) outBuf).hasData()) { sourceConfiguration.getSourceConnections().releaseConnection(conn); } endTransaction(conn); return; } if (protocolState != ProtocolState.RESPONSE_HEAD && protocolState != ProtocolState.RESPONSE_BODY) { log.warn("Illegal incoming connection state: " + protocolState + " . Possibly two send backs " + "are happening for the same request"); handleInvalidState(conn, "Trying to write response body"); endTransaction(conn); return; } SourceContext.updateState(conn, ProtocolState.RESPONSE_BODY); SourceResponse response = SourceContext.getResponse(conn); int bytesSent = response.write(conn, encoder); if (encoder.isCompleted()) { HttpContext context = conn.getContext(); long departure = System.currentTimeMillis(); context.setAttribute(PassThroughConstants.RES_TO_CLIENT_WRITE_END_TIME, departure); context.setAttribute(PassThroughConstants.RES_DEPARTURE_TIME, departure); updateLatencyView(context); } endTransaction(conn); metrics.incrementBytesSent(bytesSent); } catch (IOException e) { logIOException(conn, e); informWriterError(conn); SourceContext.updateState(conn, ProtocolState.CLOSING); sourceConfiguration.getSourceConnections().shutDownConnection(conn, true); } }
From source file:org.apache.synapse.transport.passthru.TargetHandler.java
public void requestReady(NHttpClientConnection conn) { HttpContext context = conn.getContext(); ProtocolState connState = null;/*w w w. j ava2 s. c om*/ try { connState = TargetContext.getState(conn); if (connState == ProtocolState.REQUEST_DONE || connState == ProtocolState.RESPONSE_BODY) { return; } if (connState != ProtocolState.REQUEST_READY) { handleInvalidState(conn, "Request not started"); return; } ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context .getAttribute(PassThroughConstants.TUNNEL_HANDLER); if (tunnelHandler != null && !tunnelHandler.isCompleted()) { if (!tunnelHandler.isRequested()) { HttpRequest request = tunnelHandler.generateRequest(context); if (targetConfiguration.getProxyAuthenticator() != null) { targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, context); } if (log.isDebugEnabled()) { log.debug(conn + ": Sending CONNECT request to " + tunnelHandler.getProxy()); } conn.submitRequest(request); tunnelHandler.setRequested(); } return; } TargetRequest request = TargetContext.getRequest(conn); if (request != null) { request.start(conn); targetConfiguration.getMetrics().incrementMessagesSent(); } context.setAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME, System.currentTimeMillis()); context.setAttribute(PassThroughConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis()); } catch (IOException e) { logIOException(conn, e); TargetContext.updateState(conn, ProtocolState.CLOSED); targetConfiguration.getConnections().shutdownConnection(conn, true); MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx(); if (requestMsgCtx != null) { targetErrorHandler.handleError(requestMsgCtx, ErrorCodes.SND_IO_ERROR, "Error in Sender", null, connState); } } catch (HttpException e) { log.error(e.getMessage(), e); TargetContext.updateState(conn, ProtocolState.CLOSED); targetConfiguration.getConnections().shutdownConnection(conn, true); MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx(); if (requestMsgCtx != null) { targetErrorHandler.handleError(requestMsgCtx, ErrorCodes.SND_HTTP_ERROR, "Error in Sender", null, connState); } } }
From source file:org.apache.synapse.transport.passthru.TargetHandler.java
public void responseReceived(NHttpClientConnection conn) { HttpContext context = conn.getContext(); HttpResponse response = conn.getHttpResponse(); ProtocolState connState;//from w w w . j a v a 2s . c o m try { String method = null; ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context .getAttribute(PassThroughConstants.TUNNEL_HANDLER); if (tunnelHandler != null && !tunnelHandler.isCompleted()) { method = "CONNECT"; context.removeAttribute(PassThroughConstants.TUNNEL_HANDLER); tunnelHandler.handleResponse(response, conn); if (tunnelHandler.isSuccessful()) { log.debug(conn + ": Tunnel established"); conn.resetInput(); conn.requestOutput(); return; } else { TargetContext.updateState(conn, ProtocolState.REQUEST_DONE); } } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < HttpStatus.SC_OK) { if (log.isDebugEnabled()) { log.debug(conn + ": Received a 100 Continue response"); } // Ignore 1xx response return; } boolean isError = false; context.setAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME, System.currentTimeMillis()); connState = TargetContext.getState(conn); MessageContext requestMsgContext = TargetContext.get(conn).getRequestMsgCtx(); NHttpServerConnection sourceConn = (NHttpServerConnection) requestMsgContext .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION); if (connState != ProtocolState.REQUEST_DONE) { isError = true; StatusLine errorStatus = response.getStatusLine(); /* We might receive a 404 or a similar type, even before we write the request body. */ if (errorStatus != null) { if (errorStatus.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) { TargetContext.updateState(conn, ProtocolState.REQUEST_DONE); conn.resetOutput(); if (sourceConn != null) { SourceContext.updateState(sourceConn, ProtocolState.REQUEST_DONE); SourceContext.get(sourceConn).setShutDown(true); } if (log.isDebugEnabled()) { log.debug(conn + ": Received response with status code : " + response.getStatusLine().getStatusCode() + " in invalid state : " + connState.name()); } } } else { handleInvalidState(conn, "Receiving response"); return; } } context.setAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME, System.currentTimeMillis()); TargetRequest targetRequest = TargetContext.getRequest(conn); if (targetRequest != null) { method = targetRequest.getMethod(); } if (method == null) { method = "POST"; } boolean canResponseHaveBody = isResponseHaveBodyExpected(method, response); if (!canResponseHaveBody) { if (log.isDebugEnabled()) { log.debug(conn + ": Received no-content response " + response.getStatusLine().getStatusCode()); } conn.resetInput(); } TargetResponse targetResponse = new TargetResponse(targetConfiguration, response, conn, canResponseHaveBody, isError); TargetContext.setResponse(conn, targetResponse); targetResponse.start(conn); if (statusCode == HttpStatus.SC_ACCEPTED && handle202(requestMsgContext)) { return; } targetConfiguration.getWorkerPool() .execute(new ClientWorker(targetConfiguration, requestMsgContext, targetResponse)); targetConfiguration.getMetrics().incrementMessagesReceived(); sourceConn = (NHttpServerConnection) requestMsgContext .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION); if (sourceConn != null) { sourceConn.getContext().setAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME, conn.getContext().getAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME)); conn.getContext().removeAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME); sourceConn.getContext().setAttribute(PassThroughConstants.REQ_DEPARTURE_TIME, conn.getContext().getAttribute(PassThroughConstants.REQ_DEPARTURE_TIME)); conn.getContext().removeAttribute(PassThroughConstants.REQ_DEPARTURE_TIME); sourceConn.getContext().setAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME, conn.getContext().getAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME)); conn.getContext().removeAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME); sourceConn.getContext().setAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_END_TIME, conn.getContext().getAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_END_TIME)); conn.getContext().removeAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_END_TIME); sourceConn.getContext().setAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME, conn.getContext().getAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME)); conn.getContext().removeAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME); } } catch (Exception ex) { log.error("Exception occurred while processing response", ex); informReaderError(conn); TargetContext.updateState(conn, ProtocolState.CLOSED); targetConfiguration.getConnections().shutdownConnection(conn, true); } }
From source file:org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateScheme.java
/** * Produces Negotiate authorization Header based on token created by processChallenge. * * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials * from JAAS will be used instead. * @param request The request being authenticated * * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure * * @return an Negotiate authorization Header *///from w ww .ja v a 2 s.c o m @Override public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (state == State.TOKEN_GENERATED) { // hack for auto redirects return new BasicHeader("X-dummy", "Token already generated"); } if (state != State.CHALLENGE_RECEIVED) { throw new IllegalStateException("Negotiation authentication process has not been initiated"); } try { String key = HttpCoreContext.HTTP_TARGET_HOST; HttpHost host = (HttpHost) context.getAttribute(key); if (host == null) { throw new AuthenticationException("Authentication host is not set " + "in the execution context"); } String authServer; if (!this.stripPort && host.getPort() > 0) { authServer = host.toHostString(); } else { authServer = host.getHostName(); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("init " + authServer); } final Oid negotiationOid = new Oid(SPNEGO_OID); final GSSManager manager = GSSManager.getInstance(); final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); if (token == null) { token = new byte[0]; } token = gssContext.initSecContext(token, 0, token.length); if (token == null) { state = State.FAILED; throw new AuthenticationException("GSS security context initialization failed"); } state = State.TOKEN_GENERATED; String tokenstr = new String(base64codec.encode(token)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending response '" + tokenstr + "' back to the auth server"); } CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Negotiate "); buffer.append(tokenstr); return new BufferedHeader(buffer); } catch (GSSException gsse) { state = State.FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.NO_CRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) throw new AuthenticationException(gsse.getMessage(), gsse); // other error throw new AuthenticationException(gsse.getMessage()); } }
From source file:org.siddhiesb.transport.passthru.SourceHandler.java
public void outputReady(NHttpServerConnection conn, ContentEncoder encoder) { try {//from w w w .j a v a2 s .c o m org.siddhiesb.transport.passthru.ProtocolState protocolState = org.siddhiesb.transport.passthru.SourceContext .getState(conn); //special case to handle WSDLs if (protocolState == org.siddhiesb.transport.passthru.ProtocolState.WSDL_RESPONSE_DONE) { // we need to shut down if the shutdown flag is set HttpContext context = conn.getContext(); ContentOutputBuffer outBuf = (ContentOutputBuffer) context .getAttribute("synapse.response-source-buffer"); int bytesWritten = outBuf.produceContent(encoder); conn.requestInput(); if (outBuf instanceof SimpleOutputBuffer && !((SimpleOutputBuffer) outBuf).hasData()) { sourceConfiguration.getSourceConnections().releaseConnection(conn); } return; } if (protocolState != org.siddhiesb.transport.passthru.ProtocolState.RESPONSE_HEAD && protocolState != org.siddhiesb.transport.passthru.ProtocolState.RESPONSE_BODY) { log.warn("Illegal incoming connection state: " + protocolState + " . Possibly two send backs " + "are happening for the same request"); handleInvalidState(conn, "Trying to write response body"); return; } org.siddhiesb.transport.passthru.SourceContext.updateState(conn, org.siddhiesb.transport.passthru.ProtocolState.RESPONSE_BODY); SourceResponse response = org.siddhiesb.transport.passthru.SourceContext.getResponse(conn); int bytesSent = response.write(conn, encoder); if (encoder.isCompleted()) { HttpContext context = conn.getContext(); if (context.getAttribute(PassThroughConstants.REQ_ARRIVAL_TIME) != null && context.getAttribute(PassThroughConstants.REQ_DEPARTURE_TIME) != null && context.getAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME) != null) { } context.removeAttribute(PassThroughConstants.REQ_ARRIVAL_TIME); context.removeAttribute(PassThroughConstants.REQ_DEPARTURE_TIME); context.removeAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME); } } catch (IOException e) { logIOException(conn, e); informWriterError(conn); org.siddhiesb.transport.passthru.SourceContext.updateState(conn, org.siddhiesb.transport.passthru.ProtocolState.CLOSING); sourceConfiguration.getSourceConnections().shutDownConnection(conn); } }
From source file:org.siddhiesb.transport.passthru.TargetHandler.java
public void requestReady(NHttpClientConnection conn) { //System.out.println("============ TargetHandler : requestReady ==============="); HttpContext context = conn.getContext(); org.siddhiesb.transport.passthru.ProtocolState connState = null; try {//from ww w . ja v a 2 s . c om connState = org.siddhiesb.transport.passthru.TargetContext.getState(conn); if (connState == org.siddhiesb.transport.passthru.ProtocolState.REQUEST_DONE || connState == org.siddhiesb.transport.passthru.ProtocolState.RESPONSE_BODY) { return; } if (connState != org.siddhiesb.transport.passthru.ProtocolState.REQUEST_READY) { handleInvalidState(conn, "Request not started"); return; } ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context .getAttribute(PassThroughConstants.TUNNEL_HANDLER); if (tunnelHandler != null && !tunnelHandler.isCompleted()) { if (!tunnelHandler.isRequested()) { HttpRequest request = tunnelHandler.generateRequest(context); if (targetConfiguration.getProxyAuthenticator() != null) { targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, context); } if (log.isDebugEnabled()) { log.debug(conn + ": Sending CONNECT request to " + tunnelHandler.getProxy()); } conn.submitRequest(request); tunnelHandler.setRequested(); } return; } TargetRequest request = org.siddhiesb.transport.passthru.TargetContext.getRequest(conn); if (request != null) { request.start(conn); } context.setAttribute(PassThroughConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis()); } catch (IOException e) { logIOException(conn, e); org.siddhiesb.transport.passthru.TargetContext.updateState(conn, org.siddhiesb.transport.passthru.ProtocolState.CLOSED); targetConfiguration.getConnections().shutdownConnection(conn); } catch (HttpException e) { log.error(e.getMessage(), e); org.siddhiesb.transport.passthru.TargetContext.updateState(conn, org.siddhiesb.transport.passthru.ProtocolState.CLOSED); targetConfiguration.getConnections().shutdownConnection(conn); } }
From source file:org.siddhiesb.transport.passthru.TargetHandler.java
public void responseReceived(NHttpClientConnection conn) { //System.out.println("============ TargetHandler : responseReceived ==============="); HttpContext context = conn.getContext(); HttpResponse response = conn.getHttpResponse(); org.siddhiesb.transport.passthru.ProtocolState connState; try {//from w ww. j a v a 2 s. c o m String method = null; ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context .getAttribute(PassThroughConstants.TUNNEL_HANDLER); if (tunnelHandler != null && !tunnelHandler.isCompleted()) { method = "CONNECT"; context.removeAttribute(PassThroughConstants.TUNNEL_HANDLER); tunnelHandler.handleResponse(response, conn); if (tunnelHandler.isSuccessful()) { log.debug(conn + ": Tunnel established"); conn.resetInput(); conn.requestOutput(); return; } else { org.siddhiesb.transport.passthru.TargetContext.updateState(conn, org.siddhiesb.transport.passthru.ProtocolState.REQUEST_DONE); } } context.setAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME, System.currentTimeMillis()); connState = org.siddhiesb.transport.passthru.TargetContext.getState(conn); if (connState != org.siddhiesb.transport.passthru.ProtocolState.REQUEST_DONE) { handleInvalidState(conn, "Receiving response"); return; } TargetRequest targetRequest = org.siddhiesb.transport.passthru.TargetContext.getRequest(conn); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < HttpStatus.SC_OK) { if (log.isDebugEnabled()) { log.debug(conn + ": Received a 100 Continue response"); } // Ignore 1xx response return; } if (targetRequest != null) { method = targetRequest.getMethod(); } if (method == null) { method = "POST"; } boolean canResponseHaveBody = isResponseHaveBodyExpected(method, response); TargetResponse targetResponse = new TargetResponse(targetConfiguration, response, conn, canResponseHaveBody); org.siddhiesb.transport.passthru.TargetContext.setResponse(conn, targetResponse); targetResponse.start(conn); CommonContext requestContext = org.siddhiesb.transport.passthru.TargetContext.get(conn) .getCommonContext(); targetConfiguration.getWorkerPool() .execute(new ClientWorker(requestContext, targetResponse, mediationEngine)); } catch (Exception ex) { log.error(ex.getMessage(), ex); informReaderError(conn); org.siddhiesb.transport.passthru.TargetContext.updateState(conn, org.siddhiesb.transport.passthru.ProtocolState.CLOSED); targetConfiguration.getConnections().shutdownConnection(conn); } }