public void endElement(String uri, String name, String qName) {
   String elementText = this.currText.toString();
   // Listing details.
   if (name.equals("ID")) {
     bucketsOwner.setId(elementText);
   } else if (name.equals("DisplayName")) {
     bucketsOwner.setDisplayName(elementText);
   }
   // Bucket item details.
   else if (name.equals("Bucket")) {
     if (log.isDebugEnabled()) {
       log.debug("Created new bucket from listing: " + currentBucket);
     }
     currentBucket.setOwner(bucketsOwner);
     buckets.add(currentBucket);
   } else if (name.equals("Name")) {
     currentBucket.setName(elementText);
   } else if (name.equals("CreationDate")) {
     try {
       currentBucket.setCreationDate(ServiceUtils.parseIso8601Date(elementText));
     } catch (ParseException e) {
       throw new RuntimeException("Unexpected date format in list bucket output", e);
     }
   }
   this.currText = new StringBuffer();
 }
 private Distribution convert(
     final org.jets3t.service.model.cloudfront.Distribution d, Distribution.Method method)
     throws IOException, CloudFrontServiceException {
   // Retrieve distributions configuration to access current logging status settings.
   final DistributionConfig distributionConfig = this.getDistributionConfig(d);
   final String loggingTarget;
   if (null == distributionConfig.getLoggingStatus()) {
     // Default logging target to origin itself
     loggingTarget =
         ServiceUtils.findBucketNameInHostname(
             d.getConfig().getOrigin().getDomainName(), Protocol.S3_SSL.getDefaultHostname());
   } else {
     loggingTarget =
         ServiceUtils.findBucketNameInHostname(
             distributionConfig.getLoggingStatus().getBucket(),
             Protocol.S3_SSL.getDefaultHostname());
   }
   final Distribution distribution =
       new Distribution(
           d.getId(),
           distributionConfig.getEtag(),
           distributionConfig.getCallerReference(),
           d.getConfig().getOrigin().getDomainName(),
           method,
           d.getConfig().isEnabled(),
           d.isDeployed(),
           // CloudFront URL
           String.format("%s://%s%s", method.getScheme(), d.getDomainName(), method.getContext()),
           method.equals(Distribution.DOWNLOAD) || method.equals(Distribution.CUSTOM)
               ? String.format("https://%s%s", d.getDomainName(), method.getContext())
               : null, // No SSL
           null,
           Locale.localizedString(d.getStatus(), "S3"),
           distributionConfig.getCNAMEs(),
           distributionConfig.getLoggingStatus().isEnabled(),
           loggingTarget,
           distributionConfig.getDefaultRootObject());
   if (this.isInvalidationSupported(method)) {
     distribution.setInvalidationStatus(this.readInvalidationStatus(distribution));
   }
   if (this.isLoggingSupported(method)) {
     distribution.setContainers(this.getContainers());
   }
   return distribution;
 }
Exemple #3
0
  /**
   * Generates an XML document containing metadata information as Property elements. The root of the
   * document is the element Uploader.
   *
   * @return an XML document string containing Property elements.
   * @throws Exception
   */
  public String generateXml() throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    Document document = builder.newDocument();
    Element rootElem = document.createElement("Uploader");
    document.appendChild(rootElem);
    rootElem.setAttribute("version", xmlVersionNumber);
    rootElem.setAttribute("uploadDate", ServiceUtils.formatIso8601Date(new Date()));

    // Add application properties (user inputs and application parameters) to XML document.
    for (Iterator iter = applicationProperties.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      String propertyName = (String) entry.getKey();
      String propertyValue = (String) entry.getValue();
      rootElem.appendChild(
          createPropertyElement(document, propertyName, propertyValue, "ApplicationProperty"));
    }

    // Add message properties (user inputs and application parameters) to XML document.
    for (Iterator iter = messageProperties.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      String propertyName = (String) entry.getKey();
      String propertyValue = (String) entry.getValue();
      rootElem.appendChild(
          createPropertyElement(document, propertyName, propertyValue, "MessageProperty"));
    }

    // Add Object request details to XML document.
    ObjectAndSignatureRequestDetails[] details =
        (ObjectAndSignatureRequestDetails[])
            objectRequestList.toArray(
                new ObjectAndSignatureRequestDetails[objectRequestList.size()]);
    for (int i = 0; i < details.length; i++) {
      ObjectAndSignatureRequestDetails objectDetails = details[i];
      rootElem.appendChild(createSignatureRequestElement(document, objectDetails));
    }

    // Serialize XML document to String.
    StringWriter writer = new StringWriter();
    StreamResult streamResult = new StreamResult(writer);

    DOMSource domSource = new DOMSource(document);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer = tf.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.transform(domSource, streamResult);
    return writer.toString();
  }
  /**
   * Prepares objects for HTTP communications with the Gatekeeper servlet.
   *
   * @return
   */
  private HttpClient initHttpConnection() {
    // Set client parameters.
    HttpParams params = RestUtils.createDefaultHttpParams();
    HttpProtocolParams.setUserAgent(
        params, ServiceUtils.getUserAgentDescription(userAgentDescription));

    // Set connection parameters.
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, connectionTimeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    // Replace default error retry handler.
    httpClient.setHttpRequestRetryHandler(new RestUtils.JetS3tRetryHandler(maxRetryCount, null));

    // httpClient.getParams().setAuthenticationPreemptive(true);
    httpClient.setCredentialsProvider(credentialsProvider);

    return httpClient;
  }
    public void endElement(String uri, String name, String qName) {
      String elementText = this.currText.toString();

      if (name.equals("LastModified")) {
        try {
          lastModified = ServiceUtils.parseIso8601Date(elementText);
        } catch (ParseException e) {
          throw new RuntimeException("Unexpected date format in copy object output", e);
        }
      } else if (name.equals("ETag")) {
        etag = elementText;
      } else if (name.equals("Code")) {
        errorCode = elementText;
      } else if (name.equals("Message")) {
        errorMessage = elementText;
      } else if (name.equals("RequestId")) {
        errorRequestId = elementText;
      } else if (name.equals("HostId")) {
        errorHostId = elementText;
      }

      this.currText = new StringBuffer();
    }
    public void endElement(String uri, String name, String qName) {
      String elementText = this.currText.toString();
      // Listing details
      if (name.equals("Name")) {
        bucketName = elementText;
        if (log.isDebugEnabled()) {
          log.debug("Examining listing for bucket: " + bucketName);
        }
      } else if (!insideCommonPrefixes && name.equals("Prefix")) {
        requestPrefix = elementText;
      } else if (name.equals("Marker")) {
        requestMarker = elementText;
      } else if (name.equals("NextMarker")) {
        nextMarker = elementText;
      } else if (name.equals("MaxKeys")) {
        requestMaxKeys = Long.parseLong(elementText);
      } else if (name.equals("IsTruncated")) {
        String isTruncatedStr = elementText.toLowerCase(Locale.getDefault());
        if (isTruncatedStr.startsWith("false")) {
          listingTruncated = false;
        } else if (isTruncatedStr.startsWith("true")) {
          listingTruncated = true;
        } else {
          throw new RuntimeException("Invalid value for IsTruncated field: " + isTruncatedStr);
        }
      }
      // Object details.
      else if (name.equals("Contents")) {
        objects.add(currentObject);
        if (log.isDebugEnabled()) {
          log.debug("Created new S3Object from listing: " + currentObject);
        }
      } else if (name.equals("Key")) {
        currentObject.setKey(elementText);
        lastKey = elementText;
      } else if (name.equals("LastModified")) {
        try {
          currentObject.setLastModifiedDate(ServiceUtils.parseIso8601Date(elementText));
        } catch (ParseException e) {
          throw new RuntimeException("Unexpected date format in list bucket output", e);
        }
      } else if (name.equals("ETag")) {
        currentObject.setETag(elementText);
      } else if (name.equals("Size")) {
        currentObject.setContentLength(Long.parseLong(elementText));
      } else if (name.equals("StorageClass")) {
        currentObject.setStorageClass(elementText);
      }
      // Owner details.
      else if (name.equals("ID")) {
        // Work-around to support Eucalyptus responses, which do not
        // contain Owner elements.
        if (currentOwner == null) {
          currentOwner = new S3Owner();
          currentObject.setOwner(currentOwner);
        }

        currentOwner.setId(elementText);
      } else if (name.equals("DisplayName")) {
        currentOwner.setDisplayName(elementText);
      }
      // Common prefixes.
      else if (insideCommonPrefixes && name.equals("Prefix")) {
        commonPrefixes.add(elementText);
      } else if (name.equals("CommonPrefixes")) {
        insideCommonPrefixes = false;
      }

      this.currText = new StringBuffer();
    }
  @Override
  public void write(
      boolean enabled,
      String origin,
      Distribution.Method method,
      String[] cnames,
      boolean logging,
      String loggingBucket,
      String defaultRootObject) {
    try {
      this.check();

      // Configure CDN
      LoggingStatus loggingStatus = null;
      if (logging) {
        if (this.isLoggingSupported(method)) {
          final String loggingDestination =
              StringUtils.isNotBlank(loggingBucket)
                  ? ServiceUtils.generateS3HostnameForBucket(
                      loggingBucket, false, Protocol.S3_SSL.getDefaultHostname())
                  : origin;
          loggingStatus =
              new LoggingStatus(
                  loggingDestination,
                  Preferences.instance().getProperty("cloudfront.logging.prefix"));
        }
      }
      StringBuilder name =
          new StringBuilder(Locale.localizedString("Amazon CloudFront", "S3"))
              .append(" ")
              .append(method.toString());
      if (enabled) {
        this.message(
            MessageFormat.format(
                Locale.localizedString("Enable {0} Distribution", "Status"), name));
      } else {
        this.message(
            MessageFormat.format(
                Locale.localizedString("Disable {0} Distribution", "Status"), name));
      }
      Distribution d = distributionStatus.get(method).get(origin);
      if (null == d) {
        if (log.isDebugEnabled()) {
          log.debug(String.format("No existing distribution found for method %s", method));
        }
        this.createDistribution(enabled, method, origin, cnames, loggingStatus, defaultRootObject);
      } else {
        boolean modified = false;
        if (d.isEnabled() != enabled) {
          modified = true;
        }
        if (!Arrays.equals(d.getCNAMEs(), cnames)) {
          modified = true;
        }
        if (d.isLogging() != logging) {
          modified = true;
        }
        // Compare default root object for possible change
        if (!StringUtils.equals(d.getDefaultRootObject(), defaultRootObject)) {
          modified = true;
        }
        // Compare logging target for possible change
        if (!StringUtils.equals(d.getLoggingTarget(), loggingBucket)) {
          modified = true;
        }
        if (modified) {
          this.updateDistribution(
              enabled,
              method,
              origin,
              d.getId(),
              d.getEtag(),
              d.getReference(),
              cnames,
              loggingStatus,
              defaultRootObject);
        } else {
          log.info("Skip updating distribution not modified.");
        }
      }
    } catch (CloudFrontServiceException e) {
      this.error("Cannot write CDN configuration", e);
    } catch (IOException e) {
      this.error("Cannot write CDN configuration", e);
    } finally {
      distributionStatus.get(method).clear();
    }
  }