下面列出了com.amazonaws.services.s3.model.CanonicalGrantee#com.amazonaws.auth.profile.ProfileCredentialsProvider 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public AWSLogs createAWSLogs() {
AWSLogsClientBuilder builder = AWSLogsClientBuilder.standard();
if(region!=null) {
builder.withRegion(region);
}
if(clientConfig!=null) {
builder.withClientConfiguration(clientConfig);
}
if(profileName!=null) {
builder.withCredentials(new ProfileCredentialsProvider(profileName));
}
else if(credentials!=null) {
builder.withCredentials(new AWSStaticCredentialsProvider(credentials));
}
return builder.build();
}
private static AwsIamConnector createConnector() {
AWSCredentialsProvider baseCredentials = new ProfileCredentialsProvider("default");
AWSSecurityTokenServiceAsync stsClient = new AmazonStsAsyncProvider(CONFIGURATION, baseCredentials).get();
AWSCredentialsProvider credentialsProvider = new DataPlaneAgentCredentialsProvider(CONFIGURATION, stsClient, baseCredentials).get();
Region currentRegion = Regions.getCurrentRegion();
if (currentRegion == null) {
currentRegion = Region.getRegion(Regions.US_EAST_1);
}
return new AwsIamConnector(
CONFIGURATION,
AmazonIdentityManagementAsyncClientBuilder.standard()
.withRegion(currentRegion.getName())
.withCredentials(credentialsProvider)
.build(),
AWSSecurityTokenServiceAsyncClientBuilder.standard()
.withRegion(currentRegion.getName())
.withCredentials(credentialsProvider)
.build(),
new DefaultRegistry()
);
}
private static AwsInstanceCloudConnector createConnector() {
AWSCredentialsProvider baseCredentials = new ProfileCredentialsProvider("default");
AWSSecurityTokenServiceAsync stsClient = new AmazonStsAsyncProvider(CONFIGURATION, baseCredentials).get();
AWSCredentialsProvider credentialsProvider = new DataPlaneControllerCredentialsProvider(CONFIGURATION, stsClient, baseCredentials).get();
Region currentRegion = Regions.getCurrentRegion();
if (currentRegion == null) {
currentRegion = Region.getRegion(Regions.US_EAST_1);
}
return new AwsInstanceCloudConnector(
CONFIGURATION,
AmazonEC2AsyncClientBuilder.standard()
.withRegion(currentRegion.getName())
.withCredentials(credentialsProvider)
.build(),
AmazonAutoScalingAsyncClientBuilder.standard()
.withRegion(currentRegion.getName())
.withCredentials(credentialsProvider)
.build()
);
}
public static AmazonS3 buildS3(LocalServerConfig configuration) {
String region = configuration.getProperty(pRegion);
String endpoint = configuration.getProperty(pEndpoint);
String credentialsFile = configuration.getProperty(pCredentialFile);
String credentialsProfile = configuration.getProperty(pCredentialProfile);
AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard();
if ( endpoint == null )
builder.withRegion(region);
else {
// Needed for S3mock
builder.withPathStyleAccessEnabled(true);
builder.withEndpointConfiguration(new EndpointConfiguration(endpoint, region));
builder.withCredentials(new AWSStaticCredentialsProvider(new AnonymousAWSCredentials()));
}
if ( credentialsFile != null )
builder.withCredentials(new ProfileCredentialsProvider(credentialsFile, credentialsProfile));
return builder.build();
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please specify a function name");
System.exit(1);
}
// snippet-start:[lambda.java1.delete.main]
String functionName = args[0];
try {
AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(Regions.US_WEST_2).build();
DeleteFunctionRequest delFunc = new DeleteFunctionRequest();
delFunc.withFunctionName(functionName);
//Delete the functiom
awsLambda.deleteFunction(delFunc);
System.out.println("The function is deleted");
} catch (ServiceException e) {
System.out.println(e);
}
// snippet-end:[lambda.java1.delete.main]
}
public static void main(String[] args) {
// snippet-start:[lambda.java1.list.main]
ListFunctionsResult functionResult = null;
try {
AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(Regions.US_WEST_2).build();
functionResult = awsLambda.listFunctions();
List<FunctionConfiguration> list = functionResult.getFunctions();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
FunctionConfiguration config = (FunctionConfiguration)iter.next();
System.out.println("The function name is "+config.getFunctionName());
}
} catch (ServiceException e) {
System.out.println(e);
}
// snippet-end:[lambda.java1.list.main]
}
public static void main(String args[]) throws Exception
{
AWSCredentials credentials = null;
try
{
credentials = new ProfileCredentialsProvider().getCredentials();
}catch(Exception e)
{
throw new AmazonClientException("Cannot Load credentials");
}
AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-east-1")
.build();
CreateServiceRequest crequest = new CreateServiceRequest();
crequest.setName("example-service-01");
crequest.setDescription("This is an example service request");
crequest.setNamespaceId("ns-ldmexc5fqajjnhco");//Replace with the namespaceID
System.out.println(client.createService(crequest));
}
public static void main(String args[]) throws Exception
{
AWSCredentials credentials = null;
try
{
credentials = new ProfileCredentialsProvider().getCredentials();
}catch(Exception e)
{
throw new AmazonClientException("Cannot Load credentials");
}
AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-east-1")
.build();
ListInstancesRequest lreq = new ListInstancesRequest();
lreq.setServiceId("srv-l7gkxmjapm5givba"); //Replace with service id
System.out.println(client.listInstances(lreq));
}
/**
* The only information needed to create a client are security credentials -
* your AWS Access Key ID and Secret Access Key. All other
* configuration, such as the service endpoints have defaults provided.
*
* Additional client parameters, such as proxy configuration, can be specified
* in an optional ClientConfiguration object when constructing a client.
*
* @see com.amazonaws.auth.BasicAWSCredentials
* @see com.amazonaws.auth.PropertiesCredentials
* @see com.amazonaws.ClientConfiguration
*/
private static void init() throws Exception {
/*
* ProfileCredentialsProvider loads AWS security credentials from a
* .aws/config file in your home directory.
*
* These same credentials are used when working with other AWS SDKs and the AWS CLI.
*
* You can find more information on the AWS profiles config file here:
* http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
*/
File configFile = new File(System.getProperty("user.home"), ".aws/credentials");
AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider(
new ProfilesConfigFile(configFile), "default");
if (credentialsProvider.getCredentials() == null) {
throw new RuntimeException("No AWS security credentials found:\n"
+ "Make sure you've configured your credentials in: " + configFile.getAbsolutePath() + "\n"
+ "For more information on configuring your credentials, see "
+ "http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html");
}
ec2 = new AmazonEC2Client(credentialsProvider);
s3 = new AmazonS3Client(credentialsProvider);
}
private List<AWSCredentialsProvider> resolveCredentialsProviders(
AwsCredentialsProperties properties) {
List<AWSCredentialsProvider> providers = new ArrayList<>();
if (StringUtils.hasText(properties.getAccessKey())
&& StringUtils.hasText(properties.getSecretKey())) {
providers.add(new AWSStaticCredentialsProvider(new BasicAWSCredentials(
properties.getAccessKey(), properties.getSecretKey())));
}
if (properties.isInstanceProfile()) {
providers.add(new EC2ContainerCredentialsProviderWrapper());
}
if (properties.getProfileName() != null) {
providers.add(properties.getProfilePath() != null
? new ProfileCredentialsProvider(properties.getProfilePath(),
properties.getProfileName())
: new ProfileCredentialsProvider(properties.getProfileName()));
}
return providers;
}
@Test
void credentialsProvider_profileNameConfigured_configuresProfileCredentialsProvider() {
this.contextRunner.withPropertyValues(
"cloud.aws.credentials.use-default-aws-credentials-chain:false",
"cloud.aws.credentials.profile-name:test").run((context) -> {
AWSCredentialsProvider awsCredentialsProvider = context.getBean(
AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
AWSCredentialsProvider.class);
assertThat(awsCredentialsProvider).isNotNull();
@SuppressWarnings("unchecked")
List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
.getField(awsCredentialsProvider, "credentialsProviders");
assertThat(credentialsProviders).hasSize(1)
.hasOnlyElementsOfType(ProfileCredentialsProvider.class);
assertThat(ReflectionTestUtils.getField(credentialsProviders.get(0),
"profileName")).isEqualTo("test");
});
}
@Test
void credentialsProvider_configWithAllProviders_allCredentialsProvidersConfigured()
throws Exception {
// Arrange
this.context = new AnnotationConfigApplicationContext(
ApplicationConfigurationWithAllProviders.class);
// Act
AWSCredentialsProvider awsCredentialsProvider = this.context
.getBean(AWSCredentialsProvider.class);
// Assert
assertThat(awsCredentialsProvider).isNotNull();
@SuppressWarnings("unchecked")
List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
.getField(awsCredentialsProvider, "credentialsProviders");
assertThat(credentialsProviders.size()).isEqualTo(3);
assertThat(AWSStaticCredentialsProvider.class
.isInstance(credentialsProviders.get(0))).isTrue();
assertThat(EC2ContainerCredentialsProviderWrapper.class
.isInstance(credentialsProviders.get(1))).isTrue();
assertThat(
ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(2)))
.isTrue();
}
/**
* Constructor.
* @param clientConfiguration clientConfiguration
* @param environment environment
*/
public AWSLambdaConfiguration(AWSClientConfiguration clientConfiguration, Environment environment) {
this.clientConfiguration = clientConfiguration;
this.builder.setCredentials(new AWSCredentialsProviderChain(
new EnvironmentAWSCredentialsProvider(environment),
new EnvironmentVariableCredentialsProvider(),
new SystemPropertiesCredentialsProvider(),
new ProfileCredentialsProvider(),
new EC2ContainerCredentialsProviderWrapper()
));
}
@Test
public void testNamedProfileCredentials() throws Throwable {
final TestRunner runner = TestRunners.newTestRunner(MockAWSProcessor.class);
runner.setProperty(CredentialPropertyDescriptors.USE_DEFAULT_CREDENTIALS, "false");
runner.setProperty(CredentialPropertyDescriptors.PROFILE_NAME, "BogusProfile");
runner.assertValid();
Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
final CredentialsProviderFactory factory = new CredentialsProviderFactory();
final AWSCredentialsProvider credentialsProvider = factory.getCredentialsProvider(properties);
Assert.assertNotNull(credentialsProvider);
assertEquals("credentials provider should be equal", ProfileCredentialsProvider.class,
credentialsProvider.getClass());
}
@Before
public void setUp() {
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
AmazonElasticLoadBalancingAsync albClient = AmazonElasticLoadBalancingAsyncClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(REGION)
.build();
awsLoadBalancerConnector = getAwsLoadBalancerConnector(albClient);
}
@Before
public void testSetup() {
final RekognitionInput rekognitionInput = RekognitionInput.builder()
.kinesisVideoStreamArn("<kvs-stream-arn>")
.kinesisDataStreamArn("<kds-stream-arn>")
.streamingProcessorName("<stream-processor-name>")
// Refer how to add face collection :
// https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html
.faceCollectionId("<face-collection-id>")
.iamRoleArn("<iam-role>")
.matchThreshold(0.08f)
.build();
streamProcessor = RekognitionStreamProcessor.create(Regions.US_WEST_2, new ProfileCredentialsProvider(), rekognitionInput);
}
@Ignore
@Test
public void testExample() throws InterruptedException, IOException {
KinesisVideoRendererExample example = KinesisVideoRendererExample.builder().region(Regions.US_WEST_2)
.streamName("render-example-stream")
.credentialsProvider(new ProfileCredentialsProvider())
.inputVideoStream(TestResourceUtil.getTestInputStream("vogels_480.mkv"))
.renderFragmentMetadata(false)
.build();
example.execute();
}
@Ignore
@Test
public void testDifferentResolution() throws InterruptedException, IOException {
KinesisVideoRendererExample example = KinesisVideoRendererExample.builder().region(Regions.US_WEST_2)
.streamName("render-example-stream")
.credentialsProvider(new ProfileCredentialsProvider())
.inputVideoStream(TestResourceUtil.getTestInputStream("vogels_330.mkv"))
.renderFragmentMetadata(false)
.build();
example.execute();
}
@Ignore
@Test
public void testConsumerExample() throws InterruptedException, IOException {
KinesisVideoRendererExample example = KinesisVideoRendererExample.builder().region(Regions.US_WEST_2)
.streamName("render-example-stream")
.credentialsProvider(new ProfileCredentialsProvider())
// Display the tags in the frame viewer window
.renderFragmentMetadata(true)
// Use existing stream in KVS (with Producer sending)
.noSampleInputRequired(true)
.build();
example.execute();
}
@Ignore
@Test
public void testExample() throws InterruptedException, IOException, MkvElementVisitException {
final Path outputFilePath = Paths.get("output_from_gstreamer-"+System.currentTimeMillis()+".mkv");
String gStreamerPipelineArgument =
"matroskademux ! matroskamux! filesink location=" + outputFilePath.toAbsolutePath().toString();
//Might need to update DEFAULT_PATH_TO_GSTREAMER variable in KinesisVideoGStreamerPiperExample class
KinesisVideoGStreamerPiperExample example = KinesisVideoGStreamerPiperExample.builder().region(Regions.US_WEST_2)
.streamName("myTestStream2")
.credentialsProvider(new ProfileCredentialsProvider())
.inputVideoStream(TestResourceUtil.getTestInputStream("clusters.mkv"))
.gStreamerPipelineArgument(gStreamerPipelineArgument)
.build();
example.execute();
//Verify that the generated output file has the expected number of segments, clusters and simple blocks.
CountVisitor countVisitor =
CountVisitor.create(MkvTypeInfos.SEGMENT, MkvTypeInfos.CLUSTER, MkvTypeInfos.SIMPLEBLOCK);
StreamingMkvReader.createDefault(new InputStreamParserByteSource(Files.newInputStream(outputFilePath)))
.apply(countVisitor);
Assert.assertEquals(1,countVisitor.getCount(MkvTypeInfos.SEGMENT));
Assert.assertEquals(8,countVisitor.getCount(MkvTypeInfos.CLUSTER));
Assert.assertEquals(444,countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK));
}
@Ignore
@Test
public void testExample() throws InterruptedException, IOException {
// NOTE: Rekogntion Input needs ARN for both Kinesis Video Streams and Kinesis Data Streams.
// For more info please refer https://docs.aws.amazon.com/rekognition/latest/dg/streaming-video.html
RekognitionInput rekognitionInput = RekognitionInput.builder()
.kinesisVideoStreamArn("<kvs-stream-arn>")
.kinesisDataStreamArn("<kds-stream-arn>")
.streamingProcessorName("<stream-processor-name>")
// Refer how to add face collection :
// https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html
.faceCollectionId("<face-collection-id>")
.iamRoleArn("<iam-role>")
.matchThreshold(0.08f)
.build();
KinesisVideoRekognitionIntegrationExample example = KinesisVideoRekognitionIntegrationExample.builder()
.region(Regions.US_WEST_2)
.kvsStreamName("<kvs-stream-name>")
.kdsStreamName("<kds-stream-name>")
.rekognitionInput(rekognitionInput)
.credentialsProvider(new ProfileCredentialsProvider())
// NOTE: If the input stream is not passed then the example assumes that the video fragments are
// ingested using other mechanisms like GStreamer sample app or AmazonKinesisVideoDemoApp
.inputStream(TestResourceUtil.getTestInputStream("bezos_vogels.mkv"))
.build();
// The test file resolution is 1280p.
example.setWidth(1280);
example.setHeight(720);
// This test might render frames with high latency until the rekognition results are returned. Change below
// timeout to smaller value if the frames need to be rendered with low latency when rekognition results
// are not present.
example.setRekognitionMaxTimeoutInMillis(100);
example.execute(30L);
}
@Ignore
@Test
public void testExample() throws InterruptedException, IOException {
KinesisVideoExample example = KinesisVideoExample.builder().region(Regions.US_WEST_2)
.streamName("myTestStream")
.credentialsProvider(new ProfileCredentialsProvider())
.inputVideoStream(TestResourceUtil.getTestInputStream("vogels_480.mkv"))
.build();
example.execute();
Assert.assertEquals(9, example.getFragmentsPersisted());
Assert.assertEquals(9, example.getFragmentsRead());
}
@Ignore
@Test
public void testConsumerExample() throws InterruptedException, IOException {
KinesisVideoExample example = KinesisVideoExample.builder().region(Regions.US_WEST_2)
.streamName("myTestStream")
.credentialsProvider(new ProfileCredentialsProvider())
// Use existing stream in KVS (with Producer sending)
.noSampleInputRequired(true)
.build();
example.execute();
}
AuthenticationInfoAWSCredentialsProviderChain(AuthenticationInfo authenticationInfo) {
super(
new InstanceProfileCredentialsProvider(),
new ProfileCredentialsProvider(),
new EnvironmentVariableCredentialsProvider(),
new SystemPropertiesCredentialsProvider(),
new InstanceProfileCredentialsProvider());
}
private static AWSCredentialsProvider handleProfile(EnvVars vars) {
String profile = vars.get(AWS_PROFILE, vars.get(AWS_DEFAULT_PROFILE));
if (profile != null) {
return new ProfileCredentialsProvider(profile);
}
return null;
}
@Value.Lazy
AmazonS3 s3Client() {
return AmazonS3ClientBuilder.standard()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpointUrl(), null))
.withCredentials(new ProfileCredentialsProvider(profile()))
.build();
}
public static void main(String[] args) {
AWSCredentials credentials_profile = null;
try {
credentials_profile = new ProfileCredentialsProvider("default").getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load credentials from .aws/credentials file. " +
"Make sure that the credentials file exists and the profile name is specified within it.",
e);
}
AmazonElasticMapReduce emr = AmazonElasticMapReduceClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials_profile))
.withRegion(Regions.US_WEST_1)
.build();
// Run a bash script using a predefined step in the StepFactory helper class
StepFactory stepFactory = new StepFactory();
StepConfig runBashScript = new StepConfig()
.withName("Run a bash script")
.withHadoopJarStep(stepFactory.newScriptRunnerStep("s3://jeffgoll/emr-scripts/create_users.sh"))
.withActionOnFailure("CONTINUE");
// Run a custom jar file as a step
HadoopJarStepConfig hadoopConfig1 = new HadoopJarStepConfig()
.withJar("s3://path/to/my/jarfolder") // replace with the location of the jar to run as a step
.withMainClass("com.my.Main1") // optional main class, this can be omitted if jar above has a manifest
.withArgs("--verbose"); // optional list of arguments to pass to the jar
StepConfig myCustomJarStep = new StepConfig("RunHadoopJar", hadoopConfig1);
AddJobFlowStepsResult result = emr.addJobFlowSteps(new AddJobFlowStepsRequest()
.withJobFlowId("j-xxxxxxxxxxxx") // replace with cluster id to run the steps
.withSteps(runBashScript,myCustomJarStep));
System.out.println(result.getStepIds());
}
public static void main(String args[]) throws Exception
{
AWSCredentials credentials = null;
try
{
credentials = new ProfileCredentialsProvider().getCredentials();
}catch(Exception e)
{
throw new AmazonClientException("Cannot Load credentials");
}
AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-east-1")
.build();
DiscoverInstancesRequest direquest = new DiscoverInstancesRequest();
direquest.setNamespaceName("my-apps");
direquest.setServiceName("frontend");
//Use a filter to retrieve the service based on environment and version
Map<String,String> filtermap = new HashMap<String,String>();
filtermap.put("Stage", "Dev"); //Stage - key of the custom attribute, Dev - value of the custom attribute
filtermap.put("Version", "01");//Version - key of the custom attribute, 01 - value of the custom attribute
direquest.setQueryParameters(filtermap);
System.out.println(client.discoverInstances(direquest));
}
@Override
public AWSCredentialsProvider deserializeWithType(
JsonParser jsonParser, DeserializationContext context, TypeDeserializer typeDeserializer)
throws IOException {
Map<String, String> asMap =
jsonParser.readValueAs(new TypeReference<Map<String, String>>() {});
String typeNameKey = typeDeserializer.getPropertyName();
String typeName = asMap.get(typeNameKey);
if (typeName == null) {
throw new IOException(
String.format("AWS credentials provider type name key '%s' not found", typeNameKey));
}
if (typeName.equals(AWSStaticCredentialsProvider.class.getSimpleName())) {
return new AWSStaticCredentialsProvider(
new BasicAWSCredentials(asMap.get(AWS_ACCESS_KEY_ID), asMap.get(AWS_SECRET_KEY)));
} else if (typeName.equals(PropertiesFileCredentialsProvider.class.getSimpleName())) {
return new PropertiesFileCredentialsProvider(asMap.get(CREDENTIALS_FILE_PATH));
} else if (typeName.equals(
ClasspathPropertiesFileCredentialsProvider.class.getSimpleName())) {
return new ClasspathPropertiesFileCredentialsProvider(asMap.get(CREDENTIALS_FILE_PATH));
} else if (typeName.equals(DefaultAWSCredentialsProviderChain.class.getSimpleName())) {
return new DefaultAWSCredentialsProviderChain();
} else if (typeName.equals(EnvironmentVariableCredentialsProvider.class.getSimpleName())) {
return new EnvironmentVariableCredentialsProvider();
} else if (typeName.equals(SystemPropertiesCredentialsProvider.class.getSimpleName())) {
return new SystemPropertiesCredentialsProvider();
} else if (typeName.equals(ProfileCredentialsProvider.class.getSimpleName())) {
return new ProfileCredentialsProvider();
} else if (typeName.equals(EC2ContainerCredentialsProviderWrapper.class.getSimpleName())) {
return new EC2ContainerCredentialsProviderWrapper();
} else {
throw new IOException(
String.format("AWS credential provider type '%s' is not supported", typeName));
}
}
@TaskAction
protected void deploy() {
String versionLabel = getVersionLabel();
AWSCredentialsProviderChain credentialsProvider = new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(), new ProfileCredentialsProvider(beanstalk.getProfile()), new EC2ContainerCredentialsProviderWrapper());
BeanstalkDeployer deployer = new BeanstalkDeployer(beanstalk.getS3Endpoint(), beanstalk.getBeanstalkEndpoint(), credentialsProvider);
File warFile = getProject().files(war).getSingleFile();
deployer.deploy(warFile, deployment.getApplication(), deployment.getEnvironment(), deployment.getTemplate(), versionLabel);
}