Example usage for com.amazonaws.auth AWSCredentials getAWSAccessKeyId

List of usage examples for com.amazonaws.auth AWSCredentials getAWSAccessKeyId

Introduction

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

Prototype

public String getAWSAccessKeyId();

Source Link

Document

Returns the AWS access key ID for this credentials object.

Usage

From source file:littleware.apps.fishRunner.FishApp.java

License:LGPL

/**
 * Pulls in configuration from command line or falls back to environment variables
 * of the same name. //  w  w  w  .j  ava  2s . c om
 * Command line flags: S3_KEY, S3_SECRET, DATABASE_URL, WAR_URI, CONTEXT_ROOT.
 * DATABASE_URL must be of form postgres://user:password@host:port/database -
 * we currently only support postgres database.
 * WAR_URI must be of form s3://... - we currently only support s3: URL's.
 * The app downloads the .war from WAR_URI using AWS credentials S3_KEY and S3_SECRET,
 * launches glassfish on port 8080, establishes a database resource
 * at jndi://jdbc/littleDB connected to DATABASE_URL,
 * and deploys the downloaded WAR to CONTEXT_ROOT if set - 
 * otherwise assumes the .war includes a 
 * glassfish_web.xml that specifies the context root.
 * 
 * @param args command line args
 */
public static void main(String[] args) {
    final Map<String, String> configMap = new HashMap<>();

    configMap.put(Flag.PORT.toString(), "8080");
    for (Flag key : Flag.values()) { // scan environment
        configMap.put(key.toString(), System.getenv(key.toString()));
    }

    { // command line overrides
        String key = null;
        for (String value : args) {
            if (null == key) {
                key = value;
            } else {
                configMap.put(key, value);
                key = null;
            }
        }
    }

    log.log(Level.INFO, "Setting up runtime environment: ");
    for (String key : configMap.keySet()) {
        log.log(Level.INFO, key + "='" + configMap.get(key) + "'");
    }

    try {

        // sanity check
        for (Flag key : EnumSet.of(Flag.CONTEXT_ROOT, Flag.DATABASE_URL, Flag.WAR_URI)) {
            // LOGIN_URI may be null
            if (null == configMap.get(key.toString())) {
                throw new ConfigException(
                        "Parameter must be specified in environment or on command line: " + key);
            }
        }

        final Set<Flag> s3Flags = EnumSet.of(Flag.S3_CREDSFILE, Flag.S3_KEY, Flag.S3_SECRET);
        String s3Key = configMap.get(Flag.S3_KEY.toString());
        String s3Secret = configMap.get(Flag.S3_SECRET.toString());
        String s3CredsFile = configMap.get(Flag.S3_CREDSFILE.toString());

        if ((null == s3Key) || (null == s3Secret)) {
            if (null == s3CredsFile) {
                throw new ConfigException("Must specify (S3_KEY,S3_SECRET) or S3_CREDSFILE");
            }
            final AWSCredentials creds = new PropertiesCredentials(new java.io.File(s3CredsFile));
            s3Key = creds.getAWSAccessKeyId();
            s3Secret = creds.getAWSSecretKey();
        } else if (null != s3CredsFile) {
            throw new ConfigException(
                    "Ambiguous S3 credentials - both (S3_KEY,S3_SECRET) and S3_CREDSFILE defined");
        }

        // finally - launch the app
        final Config config = new Config(configMap.get(Flag.WAR_URI.toString()),
                configMap.get(Flag.CONTEXT_ROOT.toString()), configMap.get(Flag.LOGIN_URI.toString()));

        final int port = Integer.parseInt(configMap.get(Flag.PORT.toString()));
        final Injector ij = Guice.createInjector(new AppModule(config), new FishModule(s3Key, s3Secret,
                new java.net.URI(configMap.get(Flag.DATABASE_URL.toString())), port));

        final FishApp app = ij.getInstance(FishApp.class);
        final GlassFish gf = app.call();

        System.out.print("Enter 'quit' to shutdown server:\n> ");
        System.out.flush();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            final String input = reader.readLine();
            System.out.print("\n> ");
            System.out.flush();
            if (null == input) {
                log.log(Level.INFO, "stdin closed - assuming daemon environment - leaving interactive thread");
                break;
            }
            if (input.equals("quit")) {
                log.log(Level.INFO, "Shutting down ...");
                gf.stop();
                Thread.sleep(5000);
                System.exit(0);
            }
        }
    } catch (Exception ex) {
        log.log(Level.SEVERE, "Failed to launch webapp", ex);
        log.log(Level.INFO, instructions);
        System.exit(1);
    }
}

From source file:lumbermill.internal.aws.AWSV4SignerImpl.java

License:Open Source License

public Map<String, String> getSignedHeaders(String uri, String method, Map<String, String> queryParams,
        Map<String, String> headers, Optional<byte[]> payload) {
    final LocalDateTime now = clock.get();
    final AWSCredentials credentials = credentialsProvider.getCredentials();
    final Map<String, String> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    result.putAll(headers);//w ww .j a v  a 2s  . co  m
    if (!result.containsKey(DATE)) {
        result.put(X_AMZ_DATE, now.format(BASIC_TIME_FORMAT));
    }
    if (AWSSessionCredentials.class.isAssignableFrom(credentials.getClass())) {
        result.put(SESSION_TOKEN, ((AWSSessionCredentials) credentials).getSessionToken());
    }

    final StringBuilder headersString = new StringBuilder();
    final ImmutableList.Builder<String> signedHeaders = ImmutableList.builder();

    for (Map.Entry<String, String> entry : result.entrySet()) {
        headersString.append(headerAsString(entry)).append(RETURN);
        signedHeaders.add(entry.getKey().toLowerCase());
    }

    final String signedHeaderKeys = JOINER.join(signedHeaders.build());
    final String canonicalRequest = method + RETURN + uri + RETURN + queryParamsString(queryParams) + RETURN
            + headersString.toString() + RETURN + signedHeaderKeys + RETURN
            + toBase16(hash(payload.orElse(EMPTY.getBytes(Charsets.UTF_8))));
    final String stringToSign = createStringToSign(canonicalRequest, now);
    final String signature = sign(stringToSign, now, credentials);
    final String autorizationHeader = AWS4_HMAC_SHA256_CREDENTIAL + credentials.getAWSAccessKeyId() + SLASH
            + getCredentialScope(now) + SIGNED_HEADERS + signedHeaderKeys + SIGNATURE + signature;

    result.put(AUTHORIZATION, autorizationHeader);
    return ImmutableMap.copyOf(result);
}

From source file:org.apache.bookkeeper.mledger.offload.jcloud.impl.BlobStoreManagedLedgerOffloader.java

License:Apache License

public static Credentials getCredentials(String driver, TieredStorageConfigurationData conf)
        throws IOException {
    // credentials:
    //   for s3, get by DefaultAWSCredentialsProviderChain.
    //   for gcs, use downloaded file 'google_creds.json', which contains service account key by
    //     following instructions in page https://support.google.com/googleapi/answer/6158849

    if (isGcsDriver(driver)) {
        String gcsKeyPath = conf.getGcsManagedLedgerOffloadServiceAccountKeyFile();
        if (Strings.isNullOrEmpty(gcsKeyPath)) {
            throw new IOException("The service account key path is empty for GCS driver");
        }//w  ww  .  ja  va 2 s  . com
        try {
            String gcsKeyContent = Files.toString(new File(gcsKeyPath), Charset.defaultCharset());
            return new GoogleCredentialsFromJson(gcsKeyContent).get();
        } catch (IOException ioe) {
            log.error("Cannot read GCS service account credentials file: {}", gcsKeyPath);
            throw new IOException(ioe);
        }
    } else if (isS3Driver(driver)) {
        AWSCredentials credentials = null;
        try {
            DefaultAWSCredentialsProviderChain creds = DefaultAWSCredentialsProviderChain.getInstance();
            credentials = creds.getCredentials();
        } catch (Exception e) {
            // allowed, some mock s3 service not need credential
            log.warn("Exception when get credentials for s3 ", e);
        }

        String id = "accesskey";
        String key = "secretkey";
        if (credentials != null) {
            id = credentials.getAWSAccessKeyId();
            key = credentials.getAWSSecretKey();
        }
        return new Credentials(id, key);
    } else {
        throw new IOException("Not support this kind of driver: " + driver);
    }
}

From source file:org.apache.hadoop.fs.s3a.AWSCredentialProviderList.java

License:Apache License

/**
 * Iterate through the list of providers, to find one with credentials.
 * If {@link #reuseLastProvider} is true, then it is re-used.
 * @return a set of credentials (possibly anonymous), for authenticating.
 *///from  w w  w  .  ja v  a  2s . c  o  m
@Override
public AWSCredentials getCredentials() {
    checkNotEmpty();
    if (reuseLastProvider && lastProvider != null) {
        return lastProvider.getCredentials();
    }

    AmazonClientException lastException = null;
    for (AWSCredentialsProvider provider : providers) {
        try {
            AWSCredentials credentials = provider.getCredentials();
            if ((credentials.getAWSAccessKeyId() != null && credentials.getAWSSecretKey() != null)
                    || (credentials instanceof AnonymousAWSCredentials)) {
                lastProvider = provider;
                LOG.debug("Using credentials from {}", provider);
                return credentials;
            }
        } catch (AmazonClientException e) {
            lastException = e;
            LOG.debug("No credentials provided by {}: {}", provider, e.toString(), e);
        }
    }

    // no providers had any credentials. Rethrow the last exception
    // or create a new one.
    String message = "No AWS Credentials provided by " + listProviderNames();
    if (lastException != null) {
        message += ": " + lastException;
    }
    throw new AmazonClientException(message, lastException);

}

From source file:org.duracloud.audit.reader.impl.AuditLogReaderImpl.java

License:Apache License

protected StorageProvider getStorageProvider() {
    AWSCredentials creds = new DefaultAWSCredentialsProviderChain().getCredentials();
    AmazonS3 s3client = AmazonS3ClientBuilder.standard().build();
    return new S3StorageProvider(s3client, creds.getAWSAccessKeyId(), null);
}

From source file:org.openinfinity.cloud.service.administrator.EC2Wrapper.java

License:Apache License

public void init(AWSCredentials credentials, int cloudType) {
    this.cloudType = cloudType;
    try {/*  w  w  w  .jav a  2 s  .c  o  m*/
        if (ec2 == null) {
            if (cloudType == CLOUD_TYPE_AMAZON) {
                LOG.info("Credentials: " + credentials.getAWSAccessKeyId() + ", "
                        + credentials.getAWSSecretKey());
                ec2 = new AmazonEC2Client(credentials);
                ec2.setEndpoint(endpoint);
            } else if (cloudType == CLOUD_TYPE_EUCALYPTUS) {
                LOG.info("Credentials: " + credentials.getAWSAccessKeyId() + ", "
                        + credentials.getAWSSecretKey());
                ec2 = new AmazonEC2Client(credentials);
                ec2.setEndpoint(endpoint);
            }
        }
        if (lb == null) {
            /* if (cloudType == CLOUD_TYPE_AMAZON) {
               lb = new AmazonElasticLoadBalancingClient(credentials);
               lb.setEndpoint("elasticloadbalancing.eu-west-1.amazonaws.com");
            } */
        }
    } catch (Exception e) {
        String message = e.getMessage();
        LOG.error("Error initialising EC2 connection: " + message);
        ExceptionUtil.throwSystemException(message, e);
    }
}

From source file:org.pentaho.amazon.s3.S3FileOutputDialog.java

License:Apache License

protected FileSystemOptions getFileSystemOptions() throws FileSystemException {
    FileSystemOptions opts = new FileSystemOptions();
    AWSCredentials credentials = S3CredentialsProvider.getAWSCredentials();
    if (credentials != null) {
        StaticUserAuthenticator userAuthenticator = new StaticUserAuthenticator(null,
                credentials.getAWSAccessKeyId(), credentials.getAWSSecretKey());
        DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, userAuthenticator);
    }/*ww  w . j  av  a 2s  . com*/
    return opts;
}

From source file:org.pentaho.amazon.s3.S3NVfsFileChooserDialog.java

License:Apache License

private FileSystemOptions getFileSystemOptions() throws FileSystemException {
    FileSystemOptions opts = new FileSystemOptions();
    try {//  w  ww.j av  a2 s.c o  m
        AWSCredentials credentials = S3CredentialsProvider.getAWSCredentials();
        if (credentials != null) {
            StaticUserAuthenticator userAuthenticator = new StaticUserAuthenticator(null,
                    credentials.getAWSAccessKeyId(), credentials.getAWSSecretKey());
            DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, userAuthenticator);
        }
    } catch (SdkClientException e) {
        throw new FileSystemException(e);
    }
    return opts;
}

From source file:org.pentaho.hadoop.shim.common.format.S3NCredentialUtils.java

License:Apache License

public static void applyS3CredentialsToHadoopConfigurationIfNecessary(String filename, Configuration conf) {
    Path outputFile = new Path(scrubFilePathIfNecessary(filename));
    URI uri = outputFile.toUri();
    String scheme = uri != null ? uri.getScheme() : null;
    if (scheme != null && scheme.equals(S3NSCHEME)) {
        AWSCredentials credentials = DefaultAWSCredentialsProviderChain.getInstance().getCredentials();
        conf.set("fs.s3n.awsAccessKeyId", credentials.getAWSAccessKeyId());
        conf.set("fs.s3n.awsSecretAccessKey", credentials.getAWSSecretKey());
        conf.set("fs.s3.buffer.dir", System.getProperty("java.io.tmpdir"));
    }//from   w  ww. j a  va  2s  .  c o m
}

From source file:org.springframework.cloud.config.server.support.AwsCodeCommitCredentialProvider.java

License:Apache License

/**
 * Get the username and password to use for the given uri.
 * @see org.eclipse.jgit.transport.CredentialsProvider#get(org.eclipse.jgit.transport.URIish, org.eclipse.jgit.transport.CredentialItem[])
 *///w ww  .  j  a v a 2 s. com
@Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
    String codeCommitPassword;
    String awsAccessKey;
    String awsSecretKey;
    try {
        AWSCredentials awsCredentials = retrieveAwsCredentials();
        StringBuilder awsKey = new StringBuilder();
        awsKey.append(awsCredentials.getAWSAccessKeyId());
        awsSecretKey = awsCredentials.getAWSSecretKey();
        if (awsCredentials instanceof AWSSessionCredentials) {
            AWSSessionCredentials sessionCreds = (AWSSessionCredentials) awsCredentials;
            if (sessionCreds.getSessionToken() != null) {
                awsKey.append('%').append(sessionCreds.getSessionToken());
            }
        }
        awsAccessKey = awsKey.toString();
    } catch (Throwable t) {
        logger.warn("Unable to retrieve AWS Credentials", t);
        return false;
    }
    try {
        codeCommitPassword = calculateCodeCommitPassword(uri, awsSecretKey);
    } catch (Throwable t) {
        logger.warn("Error calculating the AWS CodeCommit password", t);
        return false;
    }

    for (CredentialItem i : items) {
        if (i instanceof CredentialItem.Username) {
            ((CredentialItem.Username) i).setValue(awsAccessKey);
            logger.trace("Returning username " + awsAccessKey);
            continue;
        }
        if (i instanceof CredentialItem.Password) {
            ((CredentialItem.Password) i).setValue(codeCommitPassword.toCharArray());
            logger.trace("Returning password " + codeCommitPassword);
            continue;
        }
        if (i instanceof CredentialItem.StringType && i.getPromptText().equals("Password: ")) { //$NON-NLS-1$
            ((CredentialItem.StringType) i).setValue(codeCommitPassword);
            logger.trace("Returning password string " + codeCommitPassword);
            continue;
        }
        throw new UnsupportedCredentialItem(uri, i.getClass().getName() + ":" + i.getPromptText()); //$NON-NLS-1$
    }

    return true;
}