@Override
  public void handleError(final HttpCommand command, final HttpResponse response) {
    // it is important to always read fully and close streams
    String message = parseMessage(response);
    Exception exception =
        message == null
            ? new HttpResponseException(command, response)
            : new HttpResponseException(command, response, message);
    try {
      message =
          message == null
              ? String.format(
                  "%s -> %s",
                  command.getCurrentRequest().getRequestLine(), response.getStatusLine())
              : message;
      switch (response.getStatusCode()) {
        case 400:
          if (message.contains("unauthorized_client")) {
            exception = new AuthorizationException(message, exception);
          } else {
            exception = new IllegalArgumentException(message, exception);
          }
          break;
        case 401:
        case 403:
          exception = new AuthorizationException(message, exception);
          break;

        case 404:
          if (!command.getCurrentRequest().getMethod().equals("DELETE")) {
            exception = new ResourceNotFoundException(message, exception);
          }
          break;
        case 409:
          exception = new IllegalStateException(message, exception);
          break;
        case 429:
          exception = new AzureComputeRateLimitExceededException(response, exception);
          break;
        default:
      }
    } finally {
      Closeables2.closeQuietly(response.getPayload());
      command.setException(exception);
    }
  }
 private static HashCode buildHashedPayload(HttpRequest request) {
   HashingInputStream his = null;
   try {
     his =
         new HashingInputStream(
             Hashing.sha256(),
             request.getPayload() == null
                 ? ByteSource.empty().openStream()
                 : request.getPayload().openStream());
     ByteStreams.copy(his, ByteStreams.nullOutputStream());
     return his.hash();
   } catch (IOException e) {
     throw new HttpException("Error signing request", e);
   } finally {
     closeQuietly(his);
   }
 }
  @Override
  public void handleError(final HttpCommand command, final HttpResponse response) {
    Exception exception = null;
    String defaultMessage =
        String.format(
            "%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine());

    try {
      switch (response.getStatusCode()) {
        case 401:
        case 403:
          // Authorization exceptions do not return an errors DTO, so we
          // encapsulate a generic exception
          exception =
              new AuthorizationException(
                  defaultMessage, new HttpResponseException(command, response, defaultMessage));
          break;
        case 404:
          // TODO: get the exception to encapsulate from the returned error
          // object
          exception = new ResourceNotFoundException(defaultMessage);
          break;
        case 301:
          // Moved resources in Abiquo should be handled with the
          // ReturnMovedResource exception parser to return the moved
          // entity.
          exception = new HttpResponseException(command, response, defaultMessage);
          break;
        default:
          // TODO: get the exception to encapsulate from the returned error
          // object
          exception = new HttpResponseException(response.getMessage(), command, response);
          break;
      }
    } finally {
      closeQuietly(response.getPayload());
      command.setException(exception);
    }
  }
Example #4
0
 /** {@inheritDoc} */
 @Override
 public void close() {
   closeQuietly(closer);
 }
  @Override
  public String putBlob(final String containerName, final Blob blob) throws IOException {
    String blobKey = blob.getMetadata().getName();
    Payload payload = blob.getPayload();
    filesystemContainerNameValidator.validate(containerName);
    filesystemBlobKeyValidator.validate(blobKey);
    if (getDirectoryBlobSuffix(blobKey) != null) {
      return putDirectoryBlob(containerName, blob);
    }
    File outputFile = getFileForBlobKey(containerName, blobKey);
    // TODO: should we use a known suffix to filter these out during list?
    String tmpBlobName = blobKey + "-" + UUID.randomUUID();
    File tmpFile = getFileForBlobKey(containerName, tmpBlobName);
    Path tmpPath = tmpFile.toPath();
    HashingInputStream his = null;
    try {
      Files.createParentDirs(tmpFile);
      his = new HashingInputStream(Hashing.md5(), payload.openStream());
      long actualSize = Files.asByteSink(tmpFile).writeFrom(his);
      Long expectedSize = blob.getMetadata().getContentMetadata().getContentLength();
      if (expectedSize != null && actualSize != expectedSize) {
        throw new IOException(
            "Content-Length mismatch, actual: " + actualSize + " expected: " + expectedSize);
      }
      HashCode actualHashCode = his.hash();
      HashCode expectedHashCode = payload.getContentMetadata().getContentMD5AsHashCode();
      if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) {
        throw new IOException(
            "MD5 hash code mismatch, actual: " + actualHashCode + " expected: " + expectedHashCode);
      }
      payload.getContentMetadata().setContentMD5(actualHashCode);

      if (outputFile.exists()) {
        delete(outputFile);
      }

      UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(tmpPath);
      if (view != null) {
        try {
          view.write(XATTR_CONTENT_MD5, ByteBuffer.wrap(actualHashCode.asBytes()));
          writeCommonMetadataAttr(view, blob);
        } catch (IOException e) {
          logger.debug("xattrs not supported on %s", tmpPath);
        }
      }

      setBlobAccess(containerName, tmpBlobName, BlobAccess.PRIVATE);

      if (!tmpFile.renameTo(outputFile)) {
        throw new RuntimeException("Could not rename file " + tmpFile + " to " + outputFile);
      }

      return base16().lowerCase().encode(actualHashCode.asBytes());
    } catch (IOException ex) {
      if (tmpFile != null) {
        try {
          delete(tmpFile);
        } catch (IOException e) {
          logger.debug("Could not delete %s: %s", tmpFile, e);
        }
      }
      throw ex;
    } finally {
      closeQuietly(his);
      if (payload != null) {
        payload.release();
      }
    }
  }
Example #6
0
  @Test
  public void testUrlHandler() throws Exception {
    if (isBlobStoreLiveConfigured()) {
      createManagedBlobStoreService("aws-s3");
      BlobStore blobStoreService = getOsgiService(BlobStore.class);
      Thread.sleep(DEFAULT_TIMEOUT);

      FeaturesService featuresService = getOsgiService(FeaturesService.class);
      featuresService.installFeature("jclouds-url-handler");

      // Let's add a bundle to S3
      String groupId = "org.jclouds.api";
      String artifactId = "byon";
      String version = System.getProperty("jclouds.version");

      System.err.println(executeCommand("jclouds:blobstore-list"));
      System.err.println(executeCommand("jclouds:blobstore-container-create itest-container"));

      URL artifactUrl = new URL("mvn:" + groupId + "/" + artifactId + "/" + version);
      URL blobUrl =
          new URL(
              "blob:aws-s3/itest-container/maven2/org/jclouds/api/byon/"
                  + version
                  + "/"
                  + artifactId
                  + "-"
                  + version
                  + ".jar");
      InputStream is = artifactUrl.openConnection().getInputStream();
      OutputStream os = blobUrl.openConnection().getOutputStream();
      try {
        ByteStreams.copy(is, os);
        os.flush();
      } finally {
        Closeables2.closeQuietly(is);
        Closeables2.closeQuietly(os);
      }
      // Make sure that only S3 is available as a repo.
      System.err.println(
          executeCommands(
              "config:edit org.ops4j.pax.url.mvn",
              "config:propset org.ops4j.pax.url.mvn.localRepository "
                  + System.getProperty("karaf.base")
                  + File.separatorChar
                  + "none",
              "config:propset org.ops4j.pax.url.mvn.repositories blob:aws-s3/itest-container/maven2@snapshots ",
              "config:update"));
      Thread.sleep(DEFAULT_TIMEOUT);

      final Set<String> installedSymbolicNames = new LinkedHashSet<String>();

      // Add a Bundle Listener
      bundleContext.addBundleListener(
          new BundleListener() {
            @Override
            public void bundleChanged(BundleEvent event) {
              if (event.getType() == BundleEvent.INSTALLED) {
                installedSymbolicNames.add(event.getBundle().getSymbolicName());
              }
            }
          });

      // Install the bundle the from S3.
      System.err.println(executeCommand("osgi:install mvn:org.jclouds.api/byon/" + version));

      // Verify that no other bundle can be installed.
      System.err.println(executeCommand("osgi:install mvn:org.jclouds.api/nova/" + version));
      assertTrue(installedSymbolicNames.contains("byon"));
      assertFalse(installedSymbolicNames.contains("nova"));
    }
  }