Example usage for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials

List of usage examples for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials

Introduction

In this page you can find the example usage for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials.

Prototype

public BasicAWSCredentials(String accessKey, String secretKey) 

Source Link

Document

Constructs a new BasicAWSCredentials object, with the specified AWS access key and AWS secret key.

Usage

From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.java

License:Open Source License

public static AmazonCloudWatchAsyncClient getStatsAsyncClient(AuthCredentialsServiceState credentials,
        String region, ExecutorService executorService, boolean isMockRequest) {
    AmazonCloudWatchAsyncClient client = new AmazonCloudWatchAsyncClient(
            new BasicAWSCredentials(credentials.privateKeyId, credentials.privateKey), executorService);

    client.setRegion(Region.getRegion(Regions.fromName(region)));
    // make a call to validate credentials
    if (!isMockRequest) {
        client.describeAlarms();//w  w  w. j  a  va 2 s . co m
    }
    return client;
}

From source file:com.waltercedric.tvprogram.plugins.reader.PollyTTSReader.java

License:Open Source License

public PollyTTSReader() {
    BasicAWSCredentials awsCreds = new BasicAWSCredentials(config.getIam_access(), config.getIam_secret());

    polly = AmazonPollyAsyncClient.asyncBuilder().withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            .withRegion(config.getAws_region()).build();

    myplayer = config.getPlayer();/*from  ww w .  j  a  v  a2s. c o m*/
}

From source file:com.willetinc.hadoop.mapreduce.dynamodb.DynamoDBConfiguration.java

License:Apache License

public AmazonDynamoDBClient getAmazonDynamoDBClient() {
    String accessKey = conf.get(ACCESS_KEY_PROPERTY);
    String secretKey = conf.get(SECRET_KEY_PROPERTY);
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

    AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials);
    String endpoint = conf.get(DYNAMODB_ENDPOINT);
    if (null != endpoint) {
        client.setEndpoint(endpoint);/*from  ww w .j  ava 2  s. com*/
    }
    return client;
}

From source file:com.wowza.wms.plugin.s3upload.ModuleS3Upload.java

License:Open Source License

public void onAppStart(IApplicationInstance appInstance) {
    logger = WMSLoggerFactory.getLoggerObj(appInstance);
    this.appInstance = appInstance;

    try {//  w  w  w .j a v a 2 s  . c  o m
        WMSProperties props = appInstance.getProperties();
        accessKey = props.getPropertyStr("s3UploadAccessKey", accessKey);
        secretKey = props.getPropertyStr("s3UploadSecretKey", secretKey);
        bucketName = props.getPropertyStr("s3UploadBucketName", bucketName);
        endpoint = props.getPropertyStr("s3UploadEndpoint", endpoint);
        resumeUploads = props.getPropertyBoolean("s3UploadResumeUploads", resumeUploads);
        deleteOriginalFiles = props.getPropertyBoolean("s3UploadDeletOriginalFiles", deleteOriginalFiles);
        // fix typo in property name
        deleteOriginalFiles = props.getPropertyBoolean("s3UploadDeleteOriginalFiles", deleteOriginalFiles);

        // This value should be the URI representation of the "Group Grantee" found here http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html under "Amazon S3 Predefined Groups"
        aclGroupGranteeUri = props.getPropertyStr("s3UploadACLGroupGranteeUri", aclGroupGranteeUri);
        // This should be a string that represents the level of permissions we want to grant to the "Group Grantee" access to the file to be uploaded
        aclPermissionRule = props.getPropertyStr("s3UploadACLPermissionRule", aclPermissionRule);

        // With the passed property, check if it maps to a specified GroupGrantee
        GroupGrantee grantee = GroupGrantee.parseGroupGrantee(aclGroupGranteeUri);
        // In order for the parsing to work correctly, we will go ahead and force uppercase on the string passed
        Permission permission = Permission.parsePermission(aclPermissionRule.toUpperCase());

        // If we have properties for specifying permisions on the file upload, create the AccessControlList object and set the Grantee and Permissions
        if (grantee != null && permission != null) {
            acl = new AccessControlList();
            acl.grantPermission(grantee, permission);
        }

        if (StringUtils.isEmpty(accessKey) || StringUtils.isEmpty(secretKey)) {
            logger.warn(
                    MODULE_NAME + ".onAppStart: [" + appInstance.getContextStr() + "] missing S3 credentials",
                    WMSLoggerIDs.CAT_application, WMSLoggerIDs.EVT_comment);
            return;
        }

        AmazonS3 s3Client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));

        if (!StringUtils.isEmpty(endpoint))
            s3Client.setEndpoint(endpoint);

        if (!StringUtils.isEmpty(bucketName)) {
            boolean hasBucket = false;
            List<Bucket> buckets = s3Client.listBuckets();
            for (Bucket bucket : buckets) {
                if (bucket.getName().equals(bucketName)) {
                    hasBucket = true;
                    break;
                }
            }
            if (!hasBucket) {
                logger.warn(MODULE_NAME + ".onAppStart: [" + appInstance.getContextStr()
                        + "] missing S3 bucket: " + bucketName, WMSLoggerIDs.CAT_application,
                        WMSLoggerIDs.EVT_comment);
                return;
            }
        }

        logger.info(MODULE_NAME + ".onAppStart [" + appInstance.getContextStr() + "] S3 Bucket Name: "
                + bucketName + ", Resume Uploads: " + resumeUploads + ", Delete Original Files: "
                + deleteOriginalFiles, WMSLoggerIDs.CAT_application, WMSLoggerIDs.EVT_comment);
        transferManager = new TransferManager(s3Client);
        resumeUploads();

        appInstance.addMediaWriterListener(new WriteListener());
    } catch (AmazonS3Exception ase) {
        logger.error(MODULE_NAME + ".onAppStart [" + appInstance.getContextStr() + "] AmazonS3Exception: "
                + ase.getMessage());
    } catch (Exception e) {
        logger.error(
                MODULE_NAME + ".onAppStart [" + appInstance.getContextStr() + "] exception: " + e.getMessage(),
                e);
    } catch (Throwable t) {
        logger.error(MODULE_NAME + ".onAppStart [" + appInstance.getContextStr() + "] throwable exception: "
                + t.getMessage(), t);
    }
}

From source file:com.xebialabs.overcast.host.Ec2CloudHost.java

License:Apache License

public Ec2CloudHost(String hostLabel, String amiId) {
    this.hostLabel = hostLabel;
    this.amiId = amiId;
    this.awsEndpointURL = getOvercastProperty(AWS_ENDPOINT_PROPERTY, AWS_ENDPOINT_DEFAULT);
    this.awsAccessKey = getRequiredOvercastProperty(AWS_ACCESS_KEY_PROPERTY);
    this.awsSecretKey = getRequiredOvercastProperty(AWS_SECRET_KEY_PROPERTY);
    this.amiAvailabilityZone = getOvercastProperty(hostLabel + AMI_AVAILABILITY_ZONE_PROPERTY_SUFFIX, null);
    this.amiInstanceType = getRequiredOvercastProperty(hostLabel + AMI_INSTANCE_TYPE_PROPERTY_SUFFIX);
    this.amiSecurityGroup = getRequiredOvercastProperty(hostLabel + AMI_SECURITY_GROUP_PROPERTY_SUFFIX);
    this.amiKeyName = getRequiredOvercastProperty(hostLabel + AMI_KEY_NAME_PROPERTY_SUFFIX);
    this.amiBootSeconds = Integer
            .valueOf(getRequiredOvercastProperty(hostLabel + AMI_BOOT_SECONDS_PROPERTY_SUFFIX));

    ec2 = new AmazonEC2Client(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
    ec2.setEndpoint(awsEndpointURL);//w w w .  ja va 2s . com
}

From source file:com.yahoo.ycsb.db.S3Client.java

License:Open Source License

/**
* Initialize any state for the storage.//  ww w . java  2  s .  c o  m
* Called once per S3 instance; If the client is not null it is re-used.
*/
@Override
public void init() throws DBException {
    final int count = INIT_COUNT.incrementAndGet();
    synchronized (S3Client.class) {
        Properties propsCL = getProperties();
        int recordcount = Integer.parseInt(propsCL.getProperty("recordcount"));
        int operationcount = Integer.parseInt(propsCL.getProperty("operationcount"));
        int numberOfOperations = 0;
        if (recordcount > 0) {
            if (recordcount > operationcount) {
                numberOfOperations = recordcount;
            } else {
                numberOfOperations = operationcount;
            }
        } else {
            numberOfOperations = operationcount;
        }
        if (count <= numberOfOperations) {
            String accessKeyId = null;
            String secretKey = null;
            String endPoint = null;
            String region = null;
            String maxErrorRetry = null;
            String maxConnections = null;
            String protocol = null;
            BasicAWSCredentials s3Credentials;
            ClientConfiguration clientConfig;
            if (s3Client != null) {
                System.out.println("Reusing the same client");
                return;
            }
            try {
                InputStream propFile = S3Client.class.getClassLoader().getResourceAsStream("s3.properties");
                Properties props = new Properties(System.getProperties());
                props.load(propFile);
                accessKeyId = props.getProperty("s3.accessKeyId");
                if (accessKeyId == null) {
                    accessKeyId = propsCL.getProperty("s3.accessKeyId");
                }
                System.out.println(accessKeyId);
                secretKey = props.getProperty("s3.secretKey");
                if (secretKey == null) {
                    secretKey = propsCL.getProperty("s3.secretKey");
                }
                System.out.println(secretKey);
                endPoint = props.getProperty("s3.endPoint");
                if (endPoint == null) {
                    endPoint = propsCL.getProperty("s3.endPoint", "s3.amazonaws.com");
                }
                System.out.println(endPoint);
                region = props.getProperty("s3.region");
                if (region == null) {
                    region = propsCL.getProperty("s3.region", "us-east-1");
                }
                System.out.println(region);
                maxErrorRetry = props.getProperty("s3.maxErrorRetry");
                if (maxErrorRetry == null) {
                    maxErrorRetry = propsCL.getProperty("s3.maxErrorRetry", "15");
                }
                maxConnections = props.getProperty("s3.maxConnections");
                if (maxConnections == null) {
                    maxConnections = propsCL.getProperty("s3.maxConnections");
                }
                protocol = props.getProperty("s3.protocol");
                if (protocol == null) {
                    protocol = propsCL.getProperty("s3.protocol", "HTTPS");
                }
                sse = props.getProperty("s3.sse");
                if (sse == null) {
                    sse = propsCL.getProperty("s3.sse", "false");
                }
                String ssec = props.getProperty("s3.ssec");
                if (ssec == null) {
                    ssec = propsCL.getProperty("s3.ssec", null);
                } else {
                    ssecKey = new SSECustomerKey(ssec);
                }
            } catch (Exception e) {
                System.err.println("The file properties doesn't exist " + e.toString());
                e.printStackTrace();
            }
            try {
                System.out.println("Inizializing the S3 connection");
                s3Credentials = new BasicAWSCredentials(accessKeyId, secretKey);
                clientConfig = new ClientConfiguration();
                clientConfig.setMaxErrorRetry(Integer.parseInt(maxErrorRetry));
                if (protocol.equals("HTTP")) {
                    clientConfig.setProtocol(Protocol.HTTP);
                } else {
                    clientConfig.setProtocol(Protocol.HTTPS);
                }
                if (maxConnections != null) {
                    clientConfig.setMaxConnections(Integer.parseInt(maxConnections));
                }
                s3Client = new AmazonS3Client(s3Credentials, clientConfig);
                s3Client.setRegion(Region.getRegion(Regions.fromName(region)));
                s3Client.setEndpoint(endPoint);
                System.out.println("Connection successfully initialized");
            } catch (Exception e) {
                System.err.println("Could not connect to S3 storage: " + e.toString());
                e.printStackTrace();
                throw new DBException(e);
            }
        } else {
            System.err.println("The number of threads must be less or equal than the operations");
            throw new DBException(new Error("The number of threads must be less or equal than the operations"));
        }
    }
}

From source file:com.yahoo.ycsb.utils.connection.S3Connection.java

License:Open Source License

public S3Connection(String bucket, String region, String endPoint) throws ClientException {
    super(bucket, region, endPoint);
    logger.debug("S3Client.establishConnection(" + region + "," + endPoint + ") bucket: " + bucket);
    org.apache.log4j.Logger.getLogger("com.amazonaws").setLevel(Level.OFF);

    /*if (S3Connection.init == true) {
    init();/*w w  w. j av a  2 s .co  m*/
    S3Connection.init = false;
    }*/

    this.bucket = bucket;
    this.region = region;

    try {
        BasicAWSCredentials s3Credentials = new BasicAWSCredentials(accessKeyId, secretKey);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setMaxErrorRetry(Integer.parseInt(maxErrorRetry));
        if (protocol.equals("HTTP")) {
            clientConfig.setProtocol(Protocol.HTTP);
        } else {
            clientConfig.setProtocol(Protocol.HTTPS);
        }
        if (maxConnections != null) {
            clientConfig.setMaxConnections(Integer.parseInt(maxConnections));
        }

        logger.debug("Inizializing the S3 connection...");
        awsClient = new AmazonS3Client(s3Credentials, clientConfig);
        awsClient.setRegion(Region.getRegion(Regions.fromName(region)));
        awsClient.setEndpoint(endPoint);
        logger.debug("Connection successfully initialized");
    } catch (Exception e) {
        logger.error("Could not connect to S3 storage: " + e.toString());
        e.printStackTrace();
        throw new ClientException(e);
    }
}

From source file:com.yosanai.java.aws.console.DefaultAWSConnectionProvider.java

License:Open Source License

@Override
public void updateEC2Config(boolean reuseExisting, Configuration config) throws Exception {
    if (StringUtils.isNotBlank(config.getString(AWS_KEY))) {
        if (null == amazonEC2 || !reuseExisting) {
            synchronized (lock) {
                if (null != amazonEC2) {
                    amazonEC2.shutdown();
                    amazonEC2 = null;//from  w  w w .  j  a  va 2 s . c  om
                }
                amazonEC2 = new AmazonEC2Client(new BasicAWSCredentials(config.getString(AWS_KEY, ""),
                        config.getString(AWS_SECRET, "")));
                amazonEC2.describeInstances();
            }
        }
    }
}

From source file:com.zero_x_baadf00d.play.module.aws.s3.AmazonS3ModuleImpl.java

License:Open Source License

/**
 * Create a simple instance of {@code S3Module}.
 *
 * @param lifecycle     The application life cycle
 * @param configuration The application configuration
 * @since 16.03.13//from w  w  w .ja v  a  2 s . c  o m
 */
@Inject
public AmazonS3ModuleImpl(final ApplicationLifecycle lifecycle, final Configuration configuration) {
    final String accessKey = configuration.getString(AmazonS3ModuleImpl.AWS_ACCESS_KEY);
    final String secretKey = configuration.getString(AmazonS3ModuleImpl.AWS_SECRET_KEY);
    this.s3Bucket = configuration.getString(AmazonS3ModuleImpl.AWS_S3_BUCKET);
    if ((accessKey != null) && (secretKey != null) && (this.s3Bucket != null)) {
        final AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        this.amazonS3 = new AmazonS3Client(awsCredentials);
        this.amazonS3.setEndpoint(configuration.getString(AmazonS3ModuleImpl.AWS_ENDPOINT));
        if (configuration.getBoolean(AmazonS3ModuleImpl.AWS_WITHPATHSTYLE, false)) {
            this.amazonS3.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
        }
        try {
            this.amazonS3.createBucket(this.s3Bucket);
        } catch (AmazonS3Exception e) {
            if (e.getErrorCode().compareTo("BucketAlreadyOwnedByYou") != 0
                    && e.getErrorCode().compareTo("AccessDenied") != 0) {
                throw e;
            }
        } finally {
            Logger.info("Using S3 Bucket: " + this.s3Bucket);
        }
    } else {
        throw new RuntimeException("S3Module is not properly configured");
    }
    lifecycle.addStopHook(() -> CompletableFuture.completedFuture(null));
}

From source file:com.zero_x_baadf00d.play.module.aws.s3.AmazonS3ModuleInitializer.java

License:Open Source License

/**
 * Create a simple instance of {@code S3Module}.
 *
 * @param lifecycle     The application life cycle
 * @param configuration The application configuration
 * @since 16.03.13/*from  w w  w .  ja  v a2s  . c o m*/
 */
@Inject
public AmazonS3ModuleInitializer(final ApplicationLifecycle lifecycle, final Config configuration) {
    final String accessKey;
    final String secretKey;

    if (configuration.hasPath("aws.s3.authKey")) {
        accessKey = configuration.getString("aws.s3.authKey");
    } else {
        accessKey = configuration.getString("aws.authKey");
    }
    if (configuration.hasPath("aws.s3.authSecret")) {
        secretKey = configuration.getString("aws.s3.authSecret");
    } else {
        secretKey = configuration.getString("aws.authSecret");
    }
    final String endPoint = configuration.getString("aws.s3.endPoint");
    final String signingRegion = configuration.getString("aws.s3.signingRegion");

    final boolean withPathStyle = configuration.hasPath("aws.s3.withPathStyle")
            && configuration.getBoolean("aws.s3.withPathStyle");
    final boolean withChunkedEncodingDisabled = configuration.hasPath("aws.s3.disableChunkedEncoding")
            && configuration.getBoolean("aws.s3.disableChunkedEncoding");

    PlayS3.bucketName = configuration.getString("aws.s3.bucketName");
    PlayS3.publicUrl = configuration.hasPath("aws.s3.publicUrl") ? configuration.getString("aws.s3.publicUrl")
            : "/";
    if (!PlayS3.publicUrl.endsWith("/")) {
        PlayS3.publicUrl += "/";
    }

    if (accessKey == null || secretKey == null || PlayS3.bucketName == null) {
        throw new RuntimeException("S3Module is not properly configured");
    }

    PlayS3.amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(new AWSCredentialsProvider() {
        @Override
        public AWSCredentials getCredentials() {
            return new BasicAWSCredentials(accessKey, secretKey);
        }

        @Override
        public void refresh() {
            // Not used with basic AWS credentials
        }
    }).withPathStyleAccessEnabled(withPathStyle).withChunkedEncodingDisabled(withChunkedEncodingDisabled)
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endPoint, signingRegion))
            .build();
    try {
        PlayS3.amazonS3.createBucket(PlayS3.bucketName);
    } catch (final AmazonS3Exception ex) {
        if (ex.getErrorCode().compareTo("BucketAlreadyOwnedByYou") != 0
                && ex.getErrorCode().compareTo("AccessDenied") != 0) {
            throw ex;
        }
    } finally {
        Logger.info("Using PlayS3 Bucket: " + PlayS3.bucketName);
    }

    lifecycle.addStopHook(() -> CompletableFuture.completedFuture(null));
}