com.amazonaws.services.cloudfront.AmazonCloudFront Java Examples

The following examples show how to use com.amazonaws.services.cloudfront.AmazonCloudFront. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the cloud front tags.
 *
 * @param temporaryCredentials the temporary credentials
 * @param cloudFrontList the cloud front list
 */
private static void setCloudFrontTags(BasicSessionCredentials temporaryCredentials,List<CloudFrontVH> cloudFrontList){
	String[] regions = {"us-west-2","us-east-1"};
	int index = 0;
	AmazonCloudFront amazonCloudFront = AmazonCloudFrontClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(regions[index]).build();
	for(CloudFrontVH cfVH: cloudFrontList){
		try{
			cfVH.setTags(amazonCloudFront.listTagsForResource(new com.amazonaws.services.cloudfront.model.ListTagsForResourceRequest().withResource(cfVH.getDistSummary().getARN())).getTags().getItems());
		}catch(Exception e){
			index = index==0?1:0;
			amazonCloudFront = AmazonCloudFrontClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(regions[index]).build();
		}
	}
}
 
Example #2
Source File: CFInvalidateStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected Void run() throws Exception {
	TaskListener listener = this.getContext().get(TaskListener.class);

	AmazonCloudFront client = AWSClientFactory.create(AmazonCloudFrontClientBuilder.standard(), this.getContext());

	String distribution = this.step.getDistribution();
	String[] paths = this.step.getPaths();
	boolean waitForCompletion = this.step.getWaitForCompletion();

	listener.getLogger().format("Invalidating paths %s in distribution %s%n", Arrays.toString(paths), distribution);

	Paths invalidationPaths = new Paths().withItems(paths).withQuantity(paths.length);
	InvalidationBatch batch = new InvalidationBatch(invalidationPaths, Long.toString(System.currentTimeMillis()));

	String invalidationId = client.createInvalidation(new CreateInvalidationRequest(distribution, batch)).getInvalidation().getId();
	listener.getLogger().format("Invalidation %s enqueued%n", invalidationId);

	if (waitForCompletion) {
		listener.getLogger().format("Waiting for invalidation %s to be completed...%n", invalidationId);
		client.waiters().invalidationCompleted().run(new WaiterParameters<GetInvalidationRequest>(new GetInvalidationRequest(distribution, invalidationId)));
		listener.getLogger().format("Invalidation %s completed%n", invalidationId);
	}

	return null;
}
 
Example #3
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
protected UpdateDistributionResult updateCustomDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    final URI origin = this.getOrigin(container, distribution.getMethod());
    if(log.isDebugEnabled()) {
        log.debug(String.format("Update %s distribution with origin %s", distribution.getMethod().toString(), origin));
    }
    final AmazonCloudFront client = client(container);
    final GetDistributionConfigResult response = client.getDistributionConfig(new GetDistributionConfigRequest(distribution.getId()));
    final DistributionConfig config = response.getDistributionConfig()
        .withEnabled(distribution.isEnabled())
        .withDefaultRootObject(distribution.getIndexDocument() != null ? distribution.getIndexDocument() : StringUtils.EMPTY)
        .withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
    // Make bucket name fully qualified
    final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
        false, new S3Protocol().getDefaultHostname());
    if(log.isDebugEnabled()) {
        log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
    }
    config.setLogging(new LoggingConfig()
        .withEnabled(distribution.isLogging())
        .withIncludeCookies(true)
        .withBucket(loggingTarget)
        .withPrefix(preferences.getProperty("cloudfront.logging.prefix"))
    );
    return client.updateDistribution(new UpdateDistributionRequest(config, distribution.getId(), response.getETag()));
}
 
Example #4
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the default root object.
 *
 * @param temporaryCredentials the temporary credentials
 * @param cloudFrontList the cloud front list
 */
private static void setConfigDetails(BasicSessionCredentials temporaryCredentials, List<CloudFrontVH> cloudFrontList){

	String[] regions = {"us-east-2","us-west-1"};
	int index = 0;
	AmazonCloudFront amazonCloudFront = AmazonCloudFrontClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(regions[index]).build();
	for(CloudFrontVH cfVH: cloudFrontList){
		try{
			DistributionConfig distConfig = amazonCloudFront.getDistributionConfig(new GetDistributionConfigRequest().withId(cfVH.getDistSummary().getId())).getDistributionConfig();
			cfVH.setDefaultRootObject(distConfig.getDefaultRootObject());
			cfVH.setBucketName(distConfig.getLogging().getBucket());
			cfVH.setAccessLogEnabled(distConfig.getLogging().getEnabled());
		}catch(Exception e){
			index = index==0?1:0;
			amazonCloudFront = AmazonCloudFrontClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(regions[index]).build();
		}
	}
}
 
Example #5
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch cloud front info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchCloudFrontInfoTest() throws Exception {
    
    mockStatic(AmazonCloudFrontClientBuilder.class);
    AmazonCloudFront amazonCloudFront = PowerMockito.mock(AmazonCloudFront.class);
    AmazonCloudFrontClientBuilder amazonCloudFrontClientBuilder = PowerMockito.mock(AmazonCloudFrontClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonCloudFrontClientBuilder.standard()).thenReturn(amazonCloudFrontClientBuilder);
    when(amazonCloudFrontClientBuilder.withCredentials(anyObject())).thenReturn(amazonCloudFrontClientBuilder);
    when(amazonCloudFrontClientBuilder.withRegion(anyString())).thenReturn(amazonCloudFrontClientBuilder);
    when(amazonCloudFrontClientBuilder.build()).thenReturn(amazonCloudFront);
    
    ListDistributionsResult listDistributionsResult = new ListDistributionsResult();
    List<DistributionSummary> distributionSummaries = new ArrayList<>();
    DistributionSummary distributionSummary = new DistributionSummary();
    distributionSummary.setARN("aRN");
    distributionSummaries.add(distributionSummary);
    DistributionList distributionList = new DistributionList();
    distributionList.setItems(distributionSummaries);
    listDistributionsResult.setDistributionList(distributionList);
    when(amazonCloudFront.listDistributions(anyObject())).thenReturn(listDistributionsResult);
    
    com.amazonaws.services.cloudfront.model.ListTagsForResourceResult listTagsForResourceResult = new com.amazonaws.services.cloudfront.model.ListTagsForResourceResult();
    Tags tags = new Tags();
    tags.setItems(new ArrayList<>());
    listTagsForResourceResult.setTags(tags );
    when(amazonCloudFront.listTagsForResource(anyObject())).thenReturn(listTagsForResourceResult );
    assertThat(inventoryUtil.fetchCloudFrontInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "account","accountName").size(), is(1));
}
 
Example #6
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * You can make any number of invalidation requests, but you can have only three invalidation requests
 * in progress at one time. Each request can contain up to 1,000 objects to invalidate. If you
 * exceed these limits, you get an error message.
 * <p>
 * It usually takes 10 to 15 minutes to complete your invalidation request, depending on
 * the size of your request.
 */
@Override
public void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt) throws BackgroundException {
    try {
        final Distribution d = this.read(container, method, prompt);
        final List<String> keys = new ArrayList<String>();
        for(Path file : files) {
            if(containerService.isContainer(file)) {
                // To invalidate all of the objects in a distribution
                keys.add(String.format("%s*", String.valueOf(Path.DELIMITER)));
            }
            else {
                if(file.isDirectory()) {
                    // The *, which replaces 0 or more characters, must be the last character in the invalidation path
                    keys.add(String.format("/%s*", containerService.getKey(file)));
                }
                else {
                    keys.add(String.format("/%s", containerService.getKey(file)));
                }
            }
        }
        if(keys.isEmpty()) {
            log.warn("No keys selected for invalidation");
        }
        else {
            final AmazonCloudFront client = client(container);
            client.createInvalidation(new CreateInvalidationRequest(d.getId(),
                new InvalidationBatch(new Paths().withItems(keys).withQuantity(keys.size()), new AlphanumericRandomStringService().random())
            ));
        }
    }
    catch(AmazonClientException e) {
        throw new AmazonServiceExceptionMappingService().map("Cannot write CDN configuration", e);
    }
}
 
Example #7
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param distribution Configuration
 * @return Status message from service
 */
private String readInvalidationStatus(final AmazonCloudFront client,
                                      final Distribution distribution) throws BackgroundException {
    try {
        int pending = 0;
        int completed = 0;
        String marker = null;
        do {
            final ListInvalidationsResult response = client.listInvalidations(new ListInvalidationsRequest(distribution.getId())
                .withMaxItems(String.valueOf(1000))
                .withMarker(marker));
            for(InvalidationSummary s : response.getInvalidationList().getItems()) {
                // When the invalidation batch is finished, the status is Completed.
                if("Completed".equals(s.getStatus())) {
                    // No schema for status enumeration. Fail.
                    completed++;
                }
                else {
                    // InProgress
                    pending++;
                }
            }
            marker = response.getInvalidationList().getNextMarker();
        }
        while(marker != null);
        if(pending > 0) {
            return MessageFormat.format(LocaleFactory.localizedString("{0} invalidations in progress", "S3"), pending);
        }
        if(completed > 0) {
            return MessageFormat.format(LocaleFactory.localizedString("{0} invalidations completed", "S3"), completed);
        }
        return LocaleFactory.localizedString("None");
    }
    catch(AmazonClientException e) {
        throw new AmazonServiceExceptionMappingService().map("Cannot read CDN configuration", e);
    }
}
 
Example #8
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Amazon CloudFront Extension to create a new distribution configuration
 *
 * @return Distribution configuration
 */
protected StreamingDistribution createStreamingDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    if(log.isDebugEnabled()) {
        log.debug(String.format("Create new %s distribution", distribution.getMethod().toString()));
    }
    final AmazonCloudFront client = client(container);
    final URI origin = this.getOrigin(container, distribution.getMethod());
    final String originId = String.format("%s-%s", preferences.getProperty("application.name"), new AlphanumericRandomStringService().random());
    final StreamingDistributionConfig config = new StreamingDistributionConfig(new AlphanumericRandomStringService().random(),
        new S3Origin(origin.getHost(), StringUtils.EMPTY), distribution.isEnabled())
        .withComment(originId)
        .withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0))
        .withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
    // Make bucket name fully qualified
    final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
        false, new S3Protocol().getDefaultHostname());
    if(log.isDebugEnabled()) {
        log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
    }
    config.setLogging(new StreamingLoggingConfig()
        .withEnabled(distribution.isLogging())
        .withBucket(loggingTarget)
        .withPrefix(preferences.getProperty("cloudfront.logging.prefix"))
    );
    return client.createStreamingDistribution(new CreateStreamingDistributionRequest(config)).getStreamingDistribution();
}
 
Example #9
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Amazon CloudFront Extension used to enable or disable a distribution configuration and its CNAMESs
 */
protected UpdateDistributionResult updateDownloadDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    final URI origin = this.getOrigin(container, distribution.getMethod());
    if(log.isDebugEnabled()) {
        log.debug(String.format("Update %s distribution with origin %s", distribution.getMethod().toString(), origin));
    }
    final AmazonCloudFront client = client(container);
    final GetDistributionConfigResult response = client.getDistributionConfig(new GetDistributionConfigRequest(distribution.getId()));
    final DistributionConfig config = response.getDistributionConfig()
        .withEnabled(distribution.isEnabled())
        .withDefaultRootObject(distribution.getIndexDocument())
        .withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
    if(distribution.isLogging()) {
        // Make bucket name fully qualified
        final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
            false, new S3Protocol().getDefaultHostname());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
        }
        config.setLogging(new LoggingConfig()
            .withEnabled(distribution.isLogging())
            .withIncludeCookies(true)
            .withBucket(loggingTarget)
            .withPrefix(preferences.getProperty("cloudfront.logging.prefix"))
        );
    }
    return client.updateDistribution(new UpdateDistributionRequest(config, distribution.getId(), response.getETag()));
}
 
Example #10
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
protected UpdateStreamingDistributionResult updateStreamingDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    final URI origin = this.getOrigin(container, distribution.getMethod());
    if(log.isDebugEnabled()) {
        log.debug(String.format("Update %s distribution with origin %s", distribution.getMethod().toString(), origin));
    }
    final AmazonCloudFront client = client(container);
    final GetStreamingDistributionConfigResult response = client.getStreamingDistributionConfig(new GetStreamingDistributionConfigRequest(distribution.getId()));
    final StreamingDistributionConfig config = response.getStreamingDistributionConfig()
        .withEnabled(distribution.isEnabled())
        .withS3Origin(new S3Origin(origin.getHost(), StringUtils.EMPTY))
        .withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
    if(distribution.isLogging()) {
        // Make bucket name fully qualified
        final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
            false, new S3Protocol().getDefaultHostname());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
        }
        config.setLogging(new StreamingLoggingConfig()
            .withEnabled(distribution.isLogging())
            .withBucket(loggingTarget)
            .withPrefix(preferences.getProperty("cloudfront.logging.prefix"))
        );
    }
    return client.updateStreamingDistribution(new UpdateStreamingDistributionRequest(config, distribution.getId(), response.getETag()));
}
 
Example #11
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
protected void deleteDownloadDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    final URI origin = this.getOrigin(container, distribution.getMethod());
    if(log.isDebugEnabled()) {
        log.debug(String.format("Update %s distribution with origin %s", distribution.getMethod().toString(), origin));
    }
    final AmazonCloudFront client = client(container);
    client.deleteDistribution(new DeleteDistributionRequest(distribution.getId(), distribution.getEtag()));
}
 
Example #12
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
protected void deleteStreamingDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    final URI origin = this.getOrigin(container, distribution.getMethod());
    if(log.isDebugEnabled()) {
        log.debug(String.format("Update %s distribution with origin %s", distribution.getMethod().toString(), origin));
    }
    final AmazonCloudFront client = client(container);
    client.deleteStreamingDistribution(new DeleteStreamingDistributionRequest(distribution.getId(), distribution.getEtag()));
}
 
Example #13
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
private Distribution readDownloadDistribution(final AmazonCloudFront client,
                                              final DistributionSummary summary,
                                              final Path container,
                                              final Distribution.Method method) throws BackgroundException {
    // Retrieve distributions configuration to access current logging status settings.
    try {
        final GetDistributionConfigResult response = client.getDistributionConfig(new GetDistributionConfigRequest(summary.getId()));
        final DistributionConfig configuration = response.getDistributionConfig();
        final Distribution distribution = new Distribution(this.getOrigin(container, method), method, summary.isEnabled());
        distribution.setId(summary.getId());
        distribution.setDeployed("Deployed".equals(summary.getStatus()));
        distribution.setUrl(URI.create(String.format("%s://%s%s", method.getScheme(), summary.getDomainName(), method.getContext())));
        distribution.setSslUrl(method.equals(Distribution.DOWNLOAD) || method.equals(Distribution.CUSTOM) ? URI.create(String.format("https://%s%s", summary.getDomainName(), method.getContext())) : null);
        distribution.setReference(configuration.getCallerReference());
        distribution.setEtag(response.getETag());
        distribution.setStatus(LocaleFactory.localizedString(summary.getStatus(), "S3"));
        distribution.setCNAMEs(configuration.getAliases().getItems().toArray(new String[configuration.getAliases().getItems().size()]));
        distribution.setLogging(configuration.getLogging().isEnabled());
        distribution.setLoggingContainer(StringUtils.isNotBlank(configuration.getLogging().getBucket()) ?
            ServiceUtils.findBucketNameInHostname(configuration.getLogging().getBucket(), new S3Protocol().getDefaultHostname()) : null);
        if(StringUtils.isNotBlank(configuration.getDefaultRootObject())) {
            distribution.setIndexDocument(configuration.getDefaultRootObject());
        }
        if(this.getFeature(Purge.class, method) != null) {
            distribution.setInvalidationStatus(this.readInvalidationStatus(client, distribution));
        }
        if(this.getFeature(DistributionLogging.class, method) != null) {
            distribution.setContainers(new S3BucketListService(session, new S3LocationFeature.S3Region(session.getHost().getRegion())).list(
                new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory)),
                new DisabledListProgressListener()).toList());
        }
        return distribution;
    }
    catch(AmazonClientException e) {
        throw new AmazonServiceExceptionMappingService().map("Cannot read CDN configuration", e);
    }
}
 
Example #14
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
private AmazonCloudFront client(final Path container) throws BackgroundException {
    final AmazonCloudFrontClientBuilder builder = AmazonCloudFrontClientBuilder.standard()
        .withCredentials(AWSCredentialsConfigurator.toAWSCredentialsProvider(bookmark.getCredentials()))
        .withClientConfiguration(configuration);
    final Location.Name region = this.getRegion(container);
    if(Location.unknown.equals(region)) {
        builder.withRegion(Regions.DEFAULT_REGION);
    }
    else {
        builder.withRegion(region.getIdentifier());
    }
    return builder.build();
}
 
Example #15
Source File: TkInvalidate.java    From jare with MIT License 5 votes vote down vote up
@Override
public Response act(final Request req) throws IOException {
    final String url = new RqHref.Base(req).href()
        .param("url").iterator().next();
    final String path = String.format(
        "/?u=%s",
        URLEncoder.encode(
            url,
            "UTF-8"
        )
    );
    final AmazonCloudFront aws = AmazonCloudFrontClientBuilder.standard()
        .withCredentials(
            new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(this.key, this.secret)
            )
        )
        .build();
    final CreateInvalidationResult result = aws.createInvalidation(
        new CreateInvalidationRequest(
            "E2QC66VZY6F0QA",
            new InvalidationBatch(
                new Paths().withItems(path).withQuantity(1),
                UUID.randomUUID().toString()
            )
        )
    );
    return new RsForward(
        new RsFlash(
            String.format(
                "URL \"%s\" was invalidated (ID=\"%s\", Status=\"%s\")",
                url,
                result.getInvalidation().getId(),
                result.getInvalidation().getStatus()
            )
        ),
        "/domains"
    );
}
 
Example #16
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch cloud front info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<CloudFrontVH>> fetchCloudFrontInfo(BasicSessionCredentials temporaryCredentials,String accountId,String accountName) {

	Map<String,List<CloudFrontVH>> cloudFront = new LinkedHashMap<>();
	List<DistributionSummary> distributionSummary = new ArrayList<>();
	AmazonCloudFront amazonCloudFront;
	String bucketName = null;
	boolean accessLogEnabled = false;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource \" ,\"type\": \"CloudFront\"" ;
	try{
		amazonCloudFront = AmazonCloudFrontClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion("us-west-2").build();

		String marker = null;
		List<CloudFrontVH> cloudFrontList = new ArrayList<>();
		DistributionList distributionList ;
		do{
			distributionList = amazonCloudFront.listDistributions(new ListDistributionsRequest().withMarker(marker)).getDistributionList();
			distributionSummary = distributionList.getItems();
			marker = distributionList.getNextMarker();
			for(DistributionSummary ds : distributionSummary) {
				CloudFrontVH cf = new CloudFrontVH();
				cf.setDistSummary(ds);
				cloudFrontList.add(cf);
			}
		}while(marker!=null);

		setCloudFrontTags(temporaryCredentials,cloudFrontList);
		setConfigDetails(temporaryCredentials,cloudFrontList);

		log.debug(InventoryConstants.ACCOUNT + accountId +" Type : CloudFront "+ " >> "+cloudFrontList.size());
		cloudFront.put(accountId+delimiter+accountName,cloudFrontList);
	}catch(Exception e){
		log.error(expPrefix+ InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
		ErrorManageUtil.uploadError(accountId,"","cloudfront",e.getMessage());
	}
	return cloudFront;
}
 
Example #17
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
protected com.amazonaws.services.cloudfront.model.Distribution createDownloadDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    if(log.isDebugEnabled()) {
        log.debug(String.format("Create new %s distribution", distribution.getMethod().toString()));
    }
    final AmazonCloudFront client = client(container);
    final URI origin = this.getOrigin(container, distribution.getMethod());
    final String originId = String.format("%s-%s", preferences.getProperty("application.name"), new AlphanumericRandomStringService().random());
    final DistributionConfig config = new DistributionConfig(new AlphanumericRandomStringService().random(), distribution.isEnabled())
        .withComment(originId)
        .withOrigins(new Origins()
            .withQuantity(1)
            .withItems(new Origin()
                .withId(originId)
                .withCustomHeaders(new CustomHeaders().withQuantity(0))
                .withOriginPath(StringUtils.EMPTY)
                .withDomainName(origin.getHost())
                .withS3OriginConfig(new S3OriginConfig().withOriginAccessIdentity(StringUtils.EMPTY))
            )
        )
        .withPriceClass(PriceClass.PriceClass_All)
        .withDefaultCacheBehavior(new DefaultCacheBehavior()
            .withTargetOriginId(originId)
            .withForwardedValues(new ForwardedValues().withQueryString(true).withCookies(new CookiePreference().withForward(ItemSelection.All)))
            .withViewerProtocolPolicy(ViewerProtocolPolicy.AllowAll)
            .withMinTTL(0L)
            .withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0)))
        .withDefaultRootObject(distribution.getIndexDocument())
        .withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
    // Make bucket name fully qualified
    final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
        false, new S3Protocol().getDefaultHostname());
    if(log.isDebugEnabled()) {
        log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
    }
    config.setLogging(new LoggingConfig()
        .withEnabled(distribution.isLogging())
        .withIncludeCookies(true)
        .withBucket(loggingTarget)
        .withPrefix(preferences.getProperty("cloudfront.logging.prefix")
        ));
    return client.createDistribution(new CreateDistributionRequest(config)).getDistribution();
}
 
Example #18
Source File: CloudFrontDistributionConfiguration.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
protected com.amazonaws.services.cloudfront.model.Distribution createCustomDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    final AmazonCloudFront client = client(container);
    int httpPort = 80;
    int httpsPort = 443;
    final URI origin = this.getOrigin(container, distribution.getMethod());
    if(origin.getPort() != -1) {
        if(origin.getScheme().equals(Scheme.http.name())) {
            httpPort = origin.getPort();
        }
        if(origin.getScheme().equals(Scheme.https.name())) {
            httpsPort = origin.getPort();
        }
    }
    final String originId = String.format("%s-%s", preferences.getProperty("application.name"), new AlphanumericRandomStringService().random());
    final DistributionConfig config = new DistributionConfig(new AlphanumericRandomStringService().random(), distribution.isEnabled())
        .withComment(originId)
        .withOrigins(new Origins()
            .withQuantity(1)
            .withItems(new Origin()
                .withId(originId)
                .withDomainName(origin.getHost())
                .withCustomOriginConfig(new CustomOriginConfig()
                    .withHTTPPort(httpPort)
                    .withHTTPSPort(httpsPort)
                    .withOriginSslProtocols(new OriginSslProtocols().withQuantity(2).withItems("TLSv1.1", "TLSv1.2"))
                    .withOriginProtocolPolicy(this.getPolicy(distribution.getMethod()))
                )
            )
        )
        .withPriceClass(PriceClass.PriceClass_All)
        .withDefaultCacheBehavior(new DefaultCacheBehavior()
            .withTargetOriginId(originId)
            .withForwardedValues(new ForwardedValues().withQueryString(true).withCookies(new CookiePreference().withForward(ItemSelection.All)))
            .withViewerProtocolPolicy(ViewerProtocolPolicy.AllowAll)
            .withMinTTL(0L)
            .withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0)))
        .withDefaultRootObject(distribution.getIndexDocument())
        .withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
    if(distribution.isLogging()) {
        // Make bucket name fully qualified
        final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
            false, new S3Protocol().getDefaultHostname());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
        }
        config.setLogging(new LoggingConfig()
            .withEnabled(distribution.isLogging())
            .withIncludeCookies(true)
            .withBucket(loggingTarget)
            .withPrefix(preferences.getProperty("cloudfront.logging.prefix"))
        );
    }
    return client.createDistribution(new CreateDistributionRequest(config)).getDistribution();
}