com.amazonaws.auth.BasicSessionCredentials Java Examples

The following examples show how to use com.amazonaws.auth.BasicSessionCredentials. 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: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch reserved instances test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchReservedInstancesTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeReservedInstancesResult describeReservedInstancesResult = new DescribeReservedInstancesResult();
    List<ReservedInstances> reservedInstancesList = new ArrayList<>();
    reservedInstancesList.add(new ReservedInstances());
    describeReservedInstancesResult.setReservedInstances(reservedInstancesList);
    when(ec2Client.describeReservedInstances()).thenReturn(describeReservedInstancesResult);
    assertThat(ec2InventoryUtil.fetchReservedInstances(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #2
Source File: AWSClientFactory.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
private AWSCredentialsProvider getStepCreds(EnvVars stepEnvVars) {
    String stepAccessKey = stepEnvVars.get(AWS_ACCESS_KEY_ID);
    String stepSecretKey = stepEnvVars.get(AWS_SECRET_ACCESS_KEY);
    String stepSessionToken = stepEnvVars.get(AWS_SESSION_TOKEN);

    if(stepAccessKey != null && !stepAccessKey.isEmpty() && stepSecretKey != null && !stepSecretKey.isEmpty()) {
        this.credentialsDescriptor = stepCredentials;
        if(stepSessionToken != null && !stepSessionToken.isEmpty()) {
            return new AWSStaticCredentialsProvider(new BasicSessionCredentials(stepAccessKey, stepSecretKey, stepSessionToken));
        } else {
            return new AWSStaticCredentialsProvider(new BasicAWSCredentials(stepAccessKey, stepSecretKey));
        }
    }

    return null;
}
 
Example #3
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch route tables.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<RouteTable>> fetchRouteTables(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<RouteTable>> routeTableMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + InventoryConstants.ERROR_PREFIX_EC2 ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<RouteTable> routeTableList = ec2Client.describeRouteTables().getRouteTables();
				
				if(!routeTableList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Route table "+ region.getName()+" >> " + routeTableList.size());
					routeTableMap.put(accountId+delimiter+accountName+delimiter+region.getName(), routeTableList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"routetable",e.getMessage());
	   	}
	}
	return routeTableMap;
}
 
Example #4
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch redshift info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchRedshiftInfoTest() throws Exception {
    
    mockStatic(AmazonRedshiftClientBuilder.class);
    AmazonRedshift redshiftClient = PowerMockito.mock(AmazonRedshift.class);
    AmazonRedshiftClientBuilder amazonRedshiftClientBuilder = PowerMockito.mock(AmazonRedshiftClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonRedshiftClientBuilder.standard()).thenReturn(amazonRedshiftClientBuilder);
    when(amazonRedshiftClientBuilder.withCredentials(anyObject())).thenReturn(amazonRedshiftClientBuilder);
    when(amazonRedshiftClientBuilder.withRegion(anyString())).thenReturn(amazonRedshiftClientBuilder);
    when(amazonRedshiftClientBuilder.build()).thenReturn(redshiftClient);
    
    DescribeClustersResult describeClustersResult = new DescribeClustersResult();
    List<com.amazonaws.services.redshift.model.Cluster> redshiftList = new ArrayList<>();
    redshiftList.add(new com.amazonaws.services.redshift.model.Cluster());
    describeClustersResult.setClusters(redshiftList);
    when(redshiftClient.describeClusters(anyObject())).thenReturn(describeClustersResult);
    assertThat(inventoryUtil.fetchRedshiftInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #5
Source File: KinesisSinkTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testCredentialProviderPlugin() throws Exception {
    KinesisSink sink = new KinesisSink();

    AWSCredentialsProvider credentialProvider = sink
            .createCredentialProviderWithPlugin(AwsCredentialProviderPluginImpl.class.getName(), "{}")
            .getCredentialProvider();
    Assert.assertNotNull(credentialProvider);
    Assert.assertEquals(credentialProvider.getCredentials().getAWSAccessKeyId(),
            AwsCredentialProviderPluginImpl.accessKey);
    Assert.assertEquals(credentialProvider.getCredentials().getAWSSecretKey(),
            AwsCredentialProviderPluginImpl.secretKey);
    Assert.assertEquals(((BasicSessionCredentials) credentialProvider.getCredentials()).getSessionToken(),
            AwsCredentialProviderPluginImpl.sessionToken);

    sink.close();
}
 
Example #6
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch elastic IP addresses.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<Address>> fetchElasticIPAddresses(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<Address>> elasticIPMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + InventoryConstants.ERROR_PREFIX_EC2 ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<Address> elasticIPList = ec2Client.describeAddresses().getAddresses();
				
				if(!elasticIPList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Elastic IP "+ region.getName()+" >> " + elasticIPList.size());
					elasticIPMap.put(accountId+delimiter+accountName+delimiter+region.getName(), elasticIPList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"elasticip",e.getMessage());
	   	}
	}
	return elasticIPMap;
}
 
Example #7
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch internet gateway.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<InternetGateway>> fetchInternetGateway(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	
	Map<String,List<InternetGateway>> internetGatewayMap = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"internetgateway\" , \"region\":\"" ;

	for(Region region : RegionUtils.getRegions()) { 
		try{
			if(!skipRegions.contains(region.getName())){ 
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				List<InternetGateway> internetGatewayList = ec2Client.describeInternetGateways().getInternetGateways();
				
				if(!internetGatewayList.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : EC2 Internet Gateway "+ region.getName()+" >> " + internetGatewayList.size());
					internetGatewayMap.put(accountId+delimiter+accountName+delimiter+region.getName(), internetGatewayList);
				}
		   	}
		}catch(Exception e){
	   		log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"internetgateway",e.getMessage());
	   	}
	}
	return internetGatewayMap;
}
 
Example #8
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch subnets test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchSubnetsTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeSubnetsResult describeSubnetsResult = new DescribeSubnetsResult();
    List<Subnet> subnets = new ArrayList<>();
    subnets.add(new Subnet());
    describeSubnetsResult.setSubnets(subnets);
    when(ec2Client.describeSubnets()).thenReturn(describeSubnetsResult);
    assertThat(inventoryUtil.fetchSubnets(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #9
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch security groups test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchSecurityGroupsTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeSecurityGroupsResult describeSecurityGroupsResult = new DescribeSecurityGroupsResult();
    List<SecurityGroup> secGrpList = new ArrayList<>();
    secGrpList.add(new SecurityGroup());
    describeSecurityGroupsResult.setSecurityGroups(secGrpList);
    when(ec2Client.describeSecurityGroups()).thenReturn(describeSecurityGroupsResult);
    assertThat(inventoryUtil.fetchSecurityGroups(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #10
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch network interfaces test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchNetworkInterfacesTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeNetworkInterfacesResult describeNetworkInterfacesResult = new DescribeNetworkInterfacesResult();
    List<NetworkInterface> niList = new ArrayList<>();
    niList.add(new NetworkInterface());
    describeNetworkInterfacesResult.setNetworkInterfaces(niList);
    when(ec2Client.describeNetworkInterfaces()).thenReturn(describeNetworkInterfacesResult);
    assertThat(inventoryUtil.fetchNetworkIntefaces(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #11
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch VPN connections test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchVPNConnectionsTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeVpnConnectionsResult describeVpnConnectionsResult = new DescribeVpnConnectionsResult();
    List<VpnConnection> vpnConnectionsList = new ArrayList<>();
    vpnConnectionsList.add(new VpnConnection());
    describeVpnConnectionsResult.setVpnConnections(vpnConnectionsList);
    when(ec2Client.describeVpnConnections()).thenReturn(describeVpnConnectionsResult);
    assertThat(ec2InventoryUtil.fetchVPNConnections(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #12
Source File: BastionCredentialsProvider.java    From kork with Apache License 2.0 6 votes vote down vote up
private AWSCredentials getRemoteCredentials() {
  final String command =
      String.format(
          "oq-ssh -r %s %s,0 'curl -s %s/%s'",
          proxyRegion, proxyCluster, CREDENTIALS_BASE_URL, iamRole);
  final RemoteCredentials credentials =
      RemoteCredentialsSupport.getRemoteCredentials(command, user, host, port);

  try {
    expiration = format.parse(credentials.getExpiration());
  } catch (ParseException e) {
    log.error("Failed to parse credentials expiration {}", credentials.getExpiration(), e);
    throw new IllegalStateException(e);
  }

  return new BasicSessionCredentials(
      credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getToken());
}
 
Example #13
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch NAT gateway info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<NatGateway>> fetchNATGatewayInfo(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	Map<String,List<NatGateway>> natGatwayMap =  new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Nat Gateway\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeNatGatewaysResult rslt = ec2Client.describeNatGateways(new DescribeNatGatewaysRequest());
				List<NatGateway> natGatwayList =rslt.getNatGateways();
				if(! natGatwayList.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : Nat Gateway "+region.getName() + " >> "+natGatwayList.size());
					natGatwayMap.put(accountId+delimiter+accountName+delimiter+region.getName(), natGatwayList);
				}

			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"nat",e.getMessage());
		}
	}
	return natGatwayMap;
}
 
Example #14
Source File: S3Conf.java    From pentaho-hadoop-shims with Apache License 2.0 6 votes vote down vote up
public S3Conf( ConnectionDetails details ) {
  super( details );
  Map<String, String> props = details.getProperties();
  credentialsFilePath = props.get( "credentialsFilePath" );

  if ( shouldGetCredsFromFile( props.get( "accessKey" ), props.get( "credentialsFilePath" ) ) ) {
    AWSCredentials creds = getCredsFromFile( props, credentialsFilePath );
    accessKey = creds.getAWSAccessKeyId();
    secretKey = creds.getAWSSecretKey();
    if ( creds instanceof BasicSessionCredentials ) {
      sessionToken = ( (BasicSessionCredentials) creds ).getSessionToken();
    } else {
      sessionToken = null;
    }
  } else {
    accessKey = props.get( "accessKey" );
    secretKey = props.get( "secretKey" );
    sessionToken = props.get( "sessionToken" );
    // Use only when VFS is configured for generic S3 connection
    endpoint = props.get( "endpoint" );
    pathStyleAccess = props.get( "pathStyleAccess" );
  }
}
 
Example #15
Source File: AwsClientFactory.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a client for accessing Amazon EMR service.
 *
 * @param awsParamsDto the AWS related parameters DTO that includes optional AWS credentials and proxy information
 *
 * @return the Amazon EMR client
 */
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public AmazonElasticMapReduce getEmrClient(AwsParamsDto awsParamsDto)
{
    // Get client configuration.
    ClientConfiguration clientConfiguration = awsHelper.getClientConfiguration(awsParamsDto);

    // If specified, use the AWS credentials passed in.
    if (StringUtils.isNotBlank(awsParamsDto.getAwsAccessKeyId()))
    {
        return AmazonElasticMapReduceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(
            new BasicSessionCredentials(awsParamsDto.getAwsAccessKeyId(), awsParamsDto.getAwsSecretKey(), awsParamsDto.getSessionToken())))
            .withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName()).build();
    }
    // Otherwise, use the default AWS credentials provider chain.
    else
    {
        return AmazonElasticMapReduceClientBuilder.standard().withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName())
            .build();
    }
}
 
Example #16
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch RDSDB snapshots test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchRDSDBSnapshotsTest() throws Exception {
    
    mockStatic(AmazonRDSClientBuilder.class);
    AmazonRDS rdsClient = PowerMockito.mock(AmazonRDS.class);
    AmazonRDSClientBuilder amazonRDSClientBuilder = PowerMockito.mock(AmazonRDSClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonRDSClientBuilder.standard()).thenReturn(amazonRDSClientBuilder);
    when(amazonRDSClientBuilder.withCredentials(anyObject())).thenReturn(amazonRDSClientBuilder);
    when(amazonRDSClientBuilder.withRegion(anyString())).thenReturn(amazonRDSClientBuilder);
    when(amazonRDSClientBuilder.build()).thenReturn(rdsClient);
    
    DescribeDBSnapshotsResult describeDBSnapshotsResult = new DescribeDBSnapshotsResult();
    List<DBSnapshot> snapshots = new ArrayList<>();
    snapshots.add(new DBSnapshot());
    describeDBSnapshotsResult.setDBSnapshots(snapshots);
    when(rdsClient.describeDBSnapshots(anyObject())).thenReturn(describeDBSnapshotsResult);
    assertThat(inventoryUtil.fetchRDSDBSnapshots(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #17
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 #18
Source File: SNSInventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch SNS topics test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchSNSTopicsTest() throws Exception {
    
    mockStatic(AmazonSNSClientBuilder.class);
    AmazonSNSClient snsClient = PowerMockito.mock(AmazonSNSClient.class);
    AmazonSNSClientBuilder amazonSNSClientBuilder = PowerMockito.mock(AmazonSNSClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonSNSClientBuilder.standard()).thenReturn(amazonSNSClientBuilder);
    when(amazonSNSClientBuilder.withCredentials(anyObject())).thenReturn(amazonSNSClientBuilder);
    when(amazonSNSClientBuilder.withRegion(anyString())).thenReturn(amazonSNSClientBuilder);
    when(amazonSNSClientBuilder.build()).thenReturn(snsClient);
    
    ListSubscriptionsResult listSubscriptionDefinitionsResult = new ListSubscriptionsResult();
    List<Subscription> subscriptionList = new ArrayList<>();
    subscriptionList.add(new Subscription());
    listSubscriptionDefinitionsResult.setSubscriptions(subscriptionList);
    when(snsClient.listSubscriptions( new ListSubscriptionsRequest())).thenReturn(listSubscriptionDefinitionsResult);
    assertThat(snsInventoryUtil.fetchSNSTopics(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #19
Source File: Broadcaster.java    From kickflip-android-sdk with Apache License 2.0 6 votes vote down vote up
private void onGotStreamResponse(HlsStream stream) {
    mStream = stream;
    if (mConfig.shouldAttachLocation()) {
        Kickflip.addLocationToStream(mContext, mStream, mEventBus);
    }
    mStream.setTitle(mConfig.getTitle());
    mStream.setDescription(mConfig.getDescription());
    mStream.setExtraInfo(mConfig.getExtraInfo());
    mStream.setIsPrivate(mConfig.isPrivate());
    if (VERBOSE) Log.i(TAG, "Got hls start stream " + stream);
    mS3Manager = new S3BroadcastManager(this,
            new BasicSessionCredentials(mStream.getAwsKey(), mStream.getAwsSecret(), mStream.getToken()));
    mS3Manager.setRegion(mStream.getRegion());
    mS3Manager.addRequestInterceptor(mS3RequestInterceptor);
    mReadyToBroadcast = true;
    submitQueuedUploadsToS3();
    mEventBus.post(new BroadcastIsBufferingEvent());
    if (mBroadcastListener != null) {
        mBroadcastListener.onBroadcastStart();
    }
}
 
Example #20
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch launch configurations test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchLaunchConfigurationsTest() throws Exception {
    
    mockStatic(AmazonAutoScalingClientBuilder.class);
    AmazonAutoScaling asgClient = PowerMockito.mock(AmazonAutoScaling.class);
    AmazonAutoScalingClientBuilder amazonAutoScalingClientBuilder = PowerMockito.mock(AmazonAutoScalingClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonAutoScalingClientBuilder.standard()).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.withCredentials(anyObject())).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.withRegion(anyString())).thenReturn(amazonAutoScalingClientBuilder);
    when(amazonAutoScalingClientBuilder.build()).thenReturn(asgClient);
    
    DescribeAutoScalingGroupsResult autoScalingGroupsResult = new DescribeAutoScalingGroupsResult();
    List<AutoScalingGroup> asgList = new ArrayList<>();
    asgList.add(new AutoScalingGroup());
    autoScalingGroupsResult.setAutoScalingGroups(asgList);
    when(asgClient.describeAutoScalingGroups(anyObject())).thenReturn(autoScalingGroupsResult);
    assertThat(inventoryUtil.fetchAsg(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #21
Source File: DirectConnectionInventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch direct connections test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchDirectConnectionsTest() throws Exception {
    
    mockStatic(AmazonDirectConnectClientBuilder.class);
    AmazonDirectConnectClient amazonDirectConnectClient = PowerMockito.mock(AmazonDirectConnectClient.class);
    AmazonDirectConnectClientBuilder amazonDirectConnectClientBuilder = PowerMockito.mock(AmazonDirectConnectClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonDirectConnectClientBuilder.standard()).thenReturn(amazonDirectConnectClientBuilder);
    when(amazonDirectConnectClientBuilder.withCredentials(anyObject())).thenReturn(amazonDirectConnectClientBuilder);
    when(amazonDirectConnectClientBuilder.withRegion(anyString())).thenReturn(amazonDirectConnectClientBuilder);
    when(amazonDirectConnectClientBuilder.build()).thenReturn(amazonDirectConnectClient);
    
    DescribeConnectionsResult describeConnectionsResult = new DescribeConnectionsResult();
    List<Connection> connections = new ArrayList<>();
    connections.add(new Connection());
    describeConnectionsResult.setConnections(connections);
    when(amazonDirectConnectClient.describeConnections()).thenReturn(describeConnectionsResult);
    assertThat(directConnectionInventoryUtil.fetchDirectConnections(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #22
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch route tables test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchRouteTablesTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeRouteTablesResult describeRouteTablesResult = new DescribeRouteTablesResult();
    List<RouteTable> routeTableList = new ArrayList<>();
    routeTableList.add(new RouteTable());
    describeRouteTablesResult.setRouteTables(routeTableList);
    when(ec2Client.describeRouteTables()).thenReturn(describeRouteTablesResult);
    assertThat(ec2InventoryUtil.fetchRouteTables(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #23
Source File: AwsClientFactory.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a cacheable client for AWS SES service with pluggable aws client params.
 *
 * @param awsParamsDto the specified aws parameters
 *
 * @return the Amazon SES client
 */
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public AmazonSimpleEmailService getSesClient(AwsParamsDto awsParamsDto)
{
    // Get client configuration
    ClientConfiguration clientConfiguration = awsHelper.getClientConfiguration(awsParamsDto);

    // If specified, use the AWS credentials passed in.
    if (StringUtils.isNotBlank(awsParamsDto.getAwsAccessKeyId()))
    {
        return AmazonSimpleEmailServiceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(
            new BasicSessionCredentials(awsParamsDto.getAwsAccessKeyId(), awsParamsDto.getAwsSecretKey(), awsParamsDto.getSessionToken())))
            .withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName()).build();
    }
    // Otherwise, use the default AWS credentials provider chain.
    else
    {
        return AmazonSimpleEmailServiceClientBuilder.standard().withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName())
            .build();
    }
}
 
Example #24
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch elastic IP addresses test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchElasticIPAddressesTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeAddressesResult describeAddressesResult = new DescribeAddressesResult();
    List<Address> elasticIPList = new ArrayList<>();
    elasticIPList.add(new Address());
    describeAddressesResult.setAddresses(elasticIPList);
    when(ec2Client.describeAddresses()).thenReturn(describeAddressesResult);
    assertThat(ec2InventoryUtil.fetchElasticIPAddresses(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #25
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch volumet info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchVolumetInfoTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeVolumesResult describeVolumesResult = new DescribeVolumesResult();
    List<Volume> volumeList = new ArrayList<>();
    volumeList.add(new Volume());
    describeVolumesResult.setVolumes(volumeList);
    when(ec2Client.describeVolumes()).thenReturn(describeVolumesResult);
    assertThat(inventoryUtil.fetchVolumetInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #26
Source File: AWSCodePipelineJobCredentialsProvider.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void refresh() {
    final GetJobDetailsRequest getJobDetailsRequest = new GetJobDetailsRequest().withJobId(jobId);
    final GetJobDetailsResult getJobDetailsResult = codePipelineClient.getJobDetails(getJobDetailsRequest);
    final com.amazonaws.services.codepipeline.model.AWSSessionCredentials credentials
        = getJobDetailsResult.getJobDetails().getData().getArtifactCredentials();

    this.lastRefreshedInstant = Instant.now();
    this.credentials = new BasicSessionCredentials(
            credentials.getAccessKeyId(),
            credentials.getSecretAccessKey(),
            credentials.getSessionToken());
}
 
Example #27
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch egress gateway test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchEgressGatewayTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeEgressOnlyInternetGatewaysResult describeEgressOnlyInternetGatewaysResult = new DescribeEgressOnlyInternetGatewaysResult();
    List<EgressOnlyInternetGateway> egressGatewayList = new ArrayList<>();
    egressGatewayList.add(new EgressOnlyInternetGateway());
    describeEgressOnlyInternetGatewaysResult.setEgressOnlyInternetGateways(egressGatewayList);
    when(ec2Client.describeEgressOnlyInternetGateways(anyObject())).thenReturn(describeEgressOnlyInternetGatewaysResult);
    assertThat(ec2InventoryUtil.fetchEgressGateway(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #28
Source File: AWSGlueClientFactoryTest.java    From aws-glue-data-catalog-client-for-apache-hive-metastore with Apache License 2.0 6 votes vote down vote up
@Test
public void testCredentialsCreatedBySessionCredentialsProviderFactory() throws Exception {
  hiveConf.setStrings(SessionCredentialsProviderFactory.AWS_ACCESS_KEY_CONF_VAR, FAKE_ACCESS_KEY);
  hiveConf.setStrings(SessionCredentialsProviderFactory.AWS_SECRET_KEY_CONF_VAR, FAKE_SECRET_KEY);
  hiveConf.setStrings(SessionCredentialsProviderFactory.AWS_SESSION_TOKEN_CONF_VAR, FAKE_SESSION_TOKEN);

  SessionCredentialsProviderFactory factory = new SessionCredentialsProviderFactory();
  AWSCredentialsProvider provider = factory.buildAWSCredentialsProvider(hiveConf);
  AWSCredentials credentials = provider.getCredentials();

  assertThat(credentials, instanceOf(BasicSessionCredentials.class));

  BasicSessionCredentials sessionCredentials = (BasicSessionCredentials) credentials;

  assertEquals(FAKE_ACCESS_KEY, sessionCredentials.getAWSAccessKeyId());
  assertEquals(FAKE_SECRET_KEY, sessionCredentials.getAWSSecretKey());
  assertEquals(FAKE_SESSION_TOKEN, sessionCredentials.getSessionToken());
}
 
Example #29
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch reserved instances test exception.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchReservedInstancesTest_Exception() throws Exception {
    
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenThrow(new Exception());
    assertThat(ec2InventoryUtil.fetchReservedInstances(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(0));
}
 
Example #30
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch PHD info test exception.
 *
 * @throws Exception the exception
 */
@SuppressWarnings({ "static-access"})
@Test
public void fetchPHDInfoTest_Exception() throws Exception {
    
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenThrow(new Exception());
    assertThat(inventoryUtil.fetchPHDInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "account","accountName").size(), is(0));
}