Android Open Source - android-rackspacecloud Nio Http Command Execution Handler






From Project

Back to project page android-rackspacecloud.

License

The source code is released under:

MIT License

If you think the Android project android-rackspacecloud listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
 */* ww  w  .ja  v  a  2  s. co  m*/
 * Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
 *
 * ====================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ====================================================================
 */
package org.jclouds.http.httpnio.pool;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.core.HttpHeaders;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.protocol.NHttpRequestExecutionHandler;
import org.apache.http.protocol.HttpContext;
import org.jclouds.Constants;
import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpCommandRendezvous;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpRequestFilter;
import org.jclouds.http.HttpUtils;
import org.jclouds.http.Payloads;
import org.jclouds.http.handlers.DelegatingErrorHandler;
import org.jclouds.http.handlers.DelegatingRetryHandler;
import org.jclouds.http.httpnio.util.NioHttpUtils;
import org.jclouds.http.internal.HttpWire;
import org.jclouds.logging.Logger;

import com.google.common.io.Closeables;

/**
 * // TODO: Adrian: Document this!
 * 
 * @author Adrian Cole
 */
public class NioHttpCommandExecutionHandler implements NHttpRequestExecutionHandler {
   private final ConsumingNHttpEntityFactory EntityFactory;
   private final DelegatingRetryHandler retryHandler;
   private final DelegatingErrorHandler errorHandler;
   private final HttpWire wire;

   /**
    * inputOnly: nothing is taken from this queue.
    */
   private final BlockingQueue<HttpCommandRendezvous<?>> resubmitQueue;

   @Resource
   protected Logger logger = Logger.NULL;
   @Resource
   @Named(Constants.LOGGER_HTTP_HEADERS)
   protected Logger headerLog = Logger.NULL;

   @Inject
   public NioHttpCommandExecutionHandler(ConsumingNHttpEntityFactory EntityFactory,
            BlockingQueue<HttpCommandRendezvous<?>> resubmitQueue,
            DelegatingRetryHandler retryHandler, DelegatingErrorHandler errorHandler, HttpWire wire) {
      this.EntityFactory = EntityFactory;
      this.resubmitQueue = resubmitQueue;
      this.retryHandler = retryHandler;
      this.errorHandler = errorHandler;
      this.wire = wire;
   }

   public interface ConsumingNHttpEntityFactory {
      public ConsumingNHttpEntity create(HttpEntity httpEntity);
   }

   public void initalizeContext(HttpContext context, Object attachment) {
   }

   public HttpEntityEnclosingRequest submitRequest(HttpContext context) {
      HttpCommandRendezvous<?> rendezvous = (HttpCommandRendezvous<?>) context
               .removeAttribute("command");
      if (rendezvous != null) {
         HttpRequest request = rendezvous.getCommand().getRequest();
         for (HttpRequestFilter filter : request.getFilters()) {
            filter.filter(request);
         }
         logger.debug("Sending request %s: %s", request.hashCode(), request.getRequestLine());
         if (request.getPayload() != null && wire.enabled())
            request.setPayload(Payloads.newPayload(wire
                     .output(request.getPayload().getRawContent())));
         HttpEntityEnclosingRequest nativeRequest = NioHttpUtils.convertToApacheRequest(request);
         HttpUtils.logRequest(headerLog, request, ">>");
         return nativeRequest;
      }
      return null;
   }

   public ConsumingNHttpEntity responseEntity(HttpResponse response, HttpContext context)
            throws IOException {
      return EntityFactory.create(response.getEntity());
   }

   public void handleResponse(HttpResponse apacheResponse, HttpContext context) throws IOException {
      NioHttpCommandConnectionHandle handle = (NioHttpCommandConnectionHandle) context
               .removeAttribute("command-handle");
      if (handle != null) {
         try {
            HttpCommandRendezvous<?> rendezvous = handle.getCommandRendezvous();
            HttpCommand command = rendezvous.getCommand();
            org.jclouds.http.HttpResponse response = NioHttpUtils
                     .convertToJCloudsResponse(apacheResponse);
            logger
                     .debug("Receiving response %s: %s", response.hashCode(), response
                              .getStatusLine());
            HttpUtils.logResponse(headerLog, response, "<<");
            if (response.getContent() != null && wire.enabled())
               response.setContent(wire.input(response.getContent()));
            int statusCode = response.getStatusCode();
            if (statusCode >= 300) {
               if (retryHandler.shouldRetryRequest(command, response)) {
                  resubmitQueue.add(rendezvous);
               } else {
                  errorHandler.handleError(command, response);
                  Closeables.closeQuietly(response.getContent());
                  assert command.getException() != null : "errorHandler should have set an exception!";
                  rendezvous.setException(command.getException());
               }
            } else {
               // Close early, if there is no content.
               String header = response.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH);
               if (response.getStatusCode() == 204 || (header != null && header.equals("0"))) {
                  Closeables.closeQuietly(response.getContent());
               }
               // TODO, the connection should be released when the input stream is closed
               rendezvous.setResponse(response);
            }
         } catch (InterruptedException e) {
            logger.error(e, "interrupted processing response task");
         } finally {
            // This here is probably invalid, as the connection is really tied to the server
            // response.
            releaseConnectionToPool(handle);
         }
      } else {
         throw new IllegalStateException(String.format(
                  "No command-handle associated with command %1$s", context));
      }
   }

   protected void releaseConnectionToPool(NioHttpCommandConnectionHandle handle) {
      try {
         handle.release();
      } catch (InterruptedException e) {
         logger.error(e, "Interrupted releasing handle %1$s", handle);
      }
   }

   public void finalizeContext(HttpContext context) {
      NioHttpCommandConnectionHandle handle = (NioHttpCommandConnectionHandle) context
               .removeAttribute("command-handle");
      if (handle != null) {
         try {
            handle.cancel();
         } catch (Exception e) {
            logger.error(e, "Error cancelling handle %1$s", handle);
         }
      }
   }
}




Java Source Code List

com.rackspace.cloud.files.api.client.ContainerManager.java
com.rackspace.cloud.files.api.client.ContainerObjectManager.java
com.rackspace.cloud.files.api.client.ContainerObjects.java
com.rackspace.cloud.files.api.client.Container.java
com.rackspace.cloud.files.api.client.CustomHttpClient.java
com.rackspace.cloud.files.api.client.parsers.ContainerObjectXMLparser.java
com.rackspace.cloud.files.api.client.parsers.ContainerXMLParser.java
com.rackspace.cloud.servers.api.client.Account.java
com.rackspace.cloud.servers.api.client.Backup.java
com.rackspace.cloud.servers.api.client.CloudServersException.java
com.rackspace.cloud.servers.api.client.EntityManager.java
com.rackspace.cloud.servers.api.client.Entity.java
com.rackspace.cloud.servers.api.client.FlavorManager.java
com.rackspace.cloud.servers.api.client.Flavor.java
com.rackspace.cloud.servers.api.client.ImageManager.java
com.rackspace.cloud.servers.api.client.Image.java
com.rackspace.cloud.servers.api.client.ServerManager.java
com.rackspace.cloud.servers.api.client.Server.java
com.rackspace.cloud.servers.api.client.http.Authentication.java
com.rackspace.cloud.servers.api.client.http.HttpBundle.java
com.rackspace.cloud.servers.api.client.parsers.CloudServersFaultXMLParser.java
com.rackspace.cloud.servers.api.client.parsers.FlavorsXMLParser.java
com.rackspace.cloud.servers.api.client.parsers.ImagesXMLParser.java
com.rackspace.cloud.servers.api.client.parsers.ServersXMLParser.java
com.rackspacecloud.android.AddAccountActivity.java
com.rackspacecloud.android.AddContainerActivity.java
com.rackspacecloud.android.AddFileActivity.java
com.rackspacecloud.android.AddServerActivity.java
com.rackspacecloud.android.AndroidCloudApplication.java
com.rackspacecloud.android.BackupServerActivity.java
com.rackspacecloud.android.Config.java
com.rackspacecloud.android.ConfirmResizeActivity.java
com.rackspacecloud.android.ContactActivity.java
com.rackspacecloud.android.ContainerObjectDetails.java
com.rackspacecloud.android.ContainerObjectsActivity.java
com.rackspacecloud.android.CreatePasswordActivity.java
com.rackspacecloud.android.EnableCDNActivity.java
com.rackspacecloud.android.ErrorDetailsActivity.java
com.rackspacecloud.android.GaActivity.java
com.rackspacecloud.android.GaListActivity.java
com.rackspacecloud.android.ListAccountsActivity.java
com.rackspacecloud.android.ListContainerActivity.java
com.rackspacecloud.android.ListServersActivity.java
com.rackspacecloud.android.PasswordManager.java
com.rackspacecloud.android.PasswordServerActivity.java
com.rackspacecloud.android.PingServerActivity.java
com.rackspacecloud.android.Preferences.java
com.rackspacecloud.android.ServerErrorActivity.java
com.rackspacecloud.android.TabViewActivity.java
com.rackspacecloud.android.ViewServerActivity.java
net.elasticgrid.rackspace.cloudservers.Addresses.java
net.elasticgrid.rackspace.cloudservers.BackupSchedule.java
net.elasticgrid.rackspace.cloudservers.CloudServersException.java
net.elasticgrid.rackspace.cloudservers.CloudServers.java
net.elasticgrid.rackspace.cloudservers.File.java
net.elasticgrid.rackspace.cloudservers.Flavor.java
net.elasticgrid.rackspace.cloudservers.HTTPVerb.java
net.elasticgrid.rackspace.cloudservers.Image.java
net.elasticgrid.rackspace.cloudservers.Limits.java
net.elasticgrid.rackspace.cloudservers.Personality.java
net.elasticgrid.rackspace.cloudservers.RebootType.java
net.elasticgrid.rackspace.cloudservers.Server.java
net.elasticgrid.rackspace.cloudservers.SharedIPGroup.java
net.elasticgrid.rackspace.cloudservers.XMLCloudServers.java
net.elasticgrid.rackspace.cloudservers.package-info.java
net.elasticgrid.rackspace.common.RackspaceConnection.java
net.elasticgrid.rackspace.common.RackspaceException.java
net.elasticgrid.rackspace.common.package-info.java
org.jclouds.date.joda.JodaDateService.java
org.jclouds.date.joda.config.JodaDateServiceModule.java
org.jclouds.encryption.bouncycastle.BouncyCastleEncryptionService.java
org.jclouds.encryption.bouncycastle.config.BouncyCastleEncryptionServiceModule.java
org.jclouds.enterprise.config.EnterpriseConfigurationModule.java
org.jclouds.gae.GaeHttpCommandExecutorService.java
org.jclouds.gae.config.GoogleAppEngineConfigurationModule.java
org.jclouds.http.apachehc.ApacheHCHttpCommandExecutorService.java
org.jclouds.http.apachehc.ApacheHCUtils.java
org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule.java
org.jclouds.http.httpnio.config.NioTransformingHttpCommandExecutorServiceModule.java
org.jclouds.http.httpnio.pool.NioHttpCommandConnectionHandle.java
org.jclouds.http.httpnio.pool.NioHttpCommandConnectionPool.java
org.jclouds.http.httpnio.pool.NioHttpCommandExecutionHandler.java
org.jclouds.http.httpnio.pool.NioTransformingHttpCommandExecutorService.java
org.jclouds.http.httpnio.util.NioHttpUtils.java
org.jclouds.http.pool.ConnectionPoolTransformingHttpCommandExecutorService.java
org.jclouds.http.pool.HttpCommandConnectionHandle.java
org.jclouds.http.pool.HttpCommandConnectionPool.java
org.jclouds.http.pool.config.ConnectionPoolCommandExecutorServiceModule.java
org.jclouds.logging.log4j.Log4JLogger.java
org.jclouds.logging.log4j.config.Log4JLoggingModule.java
org.jclouds.ssh.jsch.JschSshClient.java
org.jclouds.ssh.jsch.config.JschSshClientModule.java