Example usage for com.amazonaws.regions Region getRegion

List of usage examples for com.amazonaws.regions Region getRegion

Introduction

In this page you can find the example usage for com.amazonaws.regions Region getRegion.

Prototype

public static Region getRegion(Regions region) 

Source Link

Document

Returns the region with the id given, or null if it cannot be found in the current regions.xml file.

Usage

From source file:examples.csci567.demo.userpreferencesom.AmazonClientManager.java

License:Open Source License

private void initClients() {
    Map<String, String> logins = new HashMap<String, String>();
    logins.put("accounts.google.com", token);

    // initiate a credentials provider
    CognitoCachingCredentialsProvider credentials = new CognitoCachingCredentialsProvider(context,
            Constants.IDENTITY_POOL_ID, Regions.US_EAST_1);

    credentials.setLogins(logins);//  w  w w . j  ava 2  s  .c  om

    ddb = new AmazonDynamoDBClient(credentials);
    ddb.setRegion(Region.getRegion(Regions.US_WEST_2));
}

From source file:exemplos.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from   w w w .j  a  va2 s . c o  m*/
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     *
     * Important: Be sure to fill in your AWS access credentials in the
     *            AwsCredentials.properties file before you try to run this
     *            sample.
     * http://aws.amazon.com/security-credentials
     */
    AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    String key = "MyObjectKey";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique,
         * so once a bucket name has been taken by any user, you can't create
         * another bucket with that same name.
         *
         * You can optionally specify a location for your bucket if you want to
         * keep your data closer to your applications or users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to
         * S3, or upload directly an InputStream if you know the length of
         * the data in the stream. You can also specify your own metadata
         * when uploading to S3, which allows you set a variety of options
         * like content-type and content-encoding, plus additional metadata
         * specific to your applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of
         * the object's metadata and a stream from which to read the contents.
         * It's important to read the contents of the stream as quickly as
         * possibly since the data is streamed directly from Amazon S3 and your
         * network connection will remain open until you read all the data or
         * close the input stream.
         *
         * GetObjectRequest also supports several other options, including
         * conditional downloading of objects based on modification times,
         * ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for
         * listing the objects in your bucket.  Keep in mind that buckets with
         * many objects might truncate their results when listing their objects,
         * so be sure to check if the returned object listing is truncated, and
         * use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
         * additional results.
         */
        System.out.println("Listing objects");
        ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket,
         * there is no way to undelete an object, so use caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be
         * deleted, so remember to delete any objects from your buckets before
         * you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:fsi_admin.JAwsS3Conn.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ERROR = null, codErr = null;

    try {//from   w  w w  . j a v  a2 s . c o  m
        Properties parametros = new Properties();
        Vector archivos = new Vector();
        DiskFileUpload fu = new DiskFileUpload();
        List items = fu.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                parametros.put(item.getFieldName(), item.getString());
            else
                archivos.addElement(item);
        }

        if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null
                || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null
                || parametros.getProperty("ACTION") == null) {
            System.out.println("No recibi parametros de conexin antes del archivo");
            ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD,ACTION) antes del archivo";
            codErr = "3";
            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
        }

        //Hasta aqui se han enviado todos los parametros ninguno nulo
        if (ERROR == null) {
            StringBuffer msj = new StringBuffer(), S3BUKT = new StringBuffer(), S3USR = new StringBuffer(),
                    S3PASS = new StringBuffer();
            MutableBoolean COBRAR = new MutableBoolean(false);
            MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0);
            // Primero obtiene info del S3
            if (!obtenInfoAWSS3(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"),
                    parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), S3BUKT, S3USR, S3PASS,
                    msj, COSTO, SALDO, COBRAR)) {
                System.out.println("El usuario y contrasea de servicio estan mal");
                ERROR = msj.toString();
                codErr = "2";
                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                        parametros.getProperty("PASSWORD"), request, ERROR, 2);

            } else {
                AWSCredentials credentials = new BasicAWSCredentials(S3USR.toString(), S3PASS.toString());
                AmazonS3 s3 = new AmazonS3Client(credentials);
                Region usWest2 = Region.getRegion(Regions.US_WEST_2);
                s3.setRegion(usWest2);
                //System.out.println("AwsConn:" + parametros.getProperty("NOMBRE") + ":parametros.getProperty(NOMBRE)");
                String nombre = parametros.getProperty("SERVER") + parametros.getProperty("DATABASE")
                        + parametros.getProperty("ID_MODULO") + parametros.getProperty("OBJIDS")
                        + parametros.getProperty("IDSEP") + parametros.getProperty("NOMBRE");
                //System.out.println("AwsConn_Nombre:" + nombre + ":nombre");

                if (parametros.getProperty("ACTION").equals("SUBIR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));
                    Double TAMBITES = new Double(Double.parseDouble(parametros.getProperty("TAMBITES")));

                    if (COBRAR.booleanValue() && SALDO
                            .doubleValue() < (COSTO.doubleValue() * (((TOTBITES + TAMBITES) / 1024) / 1024))) {
                        System.out
                                .println("El servicio S3 de subida tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de subida tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!subirArchivo(msj, s3, S3BUKT.toString(), nombre, archivos)) {
                            System.out.println("No se permiti subir el archivo al s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else {
                            ingresarRegistroExitoso(parametros.getProperty("SERVER"),
                                    parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"),
                                    parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"),
                                    parametros.getProperty("NOMBRE"), parametros.getProperty("TAMBITES"));
                        }
                    }

                } else if (parametros.getProperty("ACTION").equals("ELIMINAR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));

                    if (COBRAR.booleanValue()
                            && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) {
                        System.out
                                .println("El servicio S3 de borrado tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de borrado tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!eliminarArchivo(msj, s3, S3BUKT.toString(), nombre)) {
                            System.out.println("No se permiti eliminar el archivo del s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else {
                            eliminarRegistroExitoso(parametros.getProperty("SERVER"),
                                    parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"),
                                    parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"),
                                    parametros.getProperty("NOMBRE"));
                        }
                    }
                } else if (parametros.getProperty("ACTION").equals("DESCARGAR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));
                    //System.out.println("COBRAR: " + COBRAR.booleanValue() + " SALDO: " + SALDO.doubleValue() + " COSTO: " + COSTO.doubleValue() + " TOTBITES: " + TOTBITES + " TOTMB: " + ((TOTBITES / 1024) / 1024) + " RES: " + (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024)));
                    if (COBRAR.booleanValue()
                            && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) {
                        System.out.println(
                                "El servicio S3 de descarga tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de descarga tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!descargarArchivo(response, msj, s3, S3BUKT.toString(), nombre,
                                parametros.getProperty("NOMBRE"))) {
                            System.out.println("No se permiti descargar el archivo del s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else
                            return;
                    }
                }

                if (ERROR == null) {
                    //Devuelve la respuesta al cliente
                    Element S3 = new Element("S3");
                    S3.setAttribute("Archivo", nombre);
                    S3.setAttribute("MsjError", "");
                    Document Reporte = new Document(S3);

                    Format format = Format.getPrettyFormat();
                    format.setEncoding("utf-8");
                    format.setTextMode(TextMode.NORMALIZE);
                    XMLOutputter xmlOutputter = new XMLOutputter(format);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    xmlOutputter.output(Reporte, out);

                    byte[] data = out.toByteArray();
                    ByteArrayInputStream istream = new ByteArrayInputStream(data);

                    String destino = "Archivo.xml";
                    JBajarArchivo fd = new JBajarArchivo();
                    fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml",
                            data.length, destino);

                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ERROR = "ERROR DE EXCEPCION EN SERVIDOR AWS S3: " + e.getMessage();
    }

    //Genera el archivo XML de error para ser devuelto al Servidor
    if (ERROR != null) {
        Element SIGN_ERROR = new Element("SIGN_ERROR");
        SIGN_ERROR.setAttribute("CodError", codErr);
        SIGN_ERROR.setAttribute("MsjError", ERROR);
        Document Reporte = new Document(SIGN_ERROR);

        Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");
        format.setTextMode(TextMode.NORMALIZE);
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutputter.output(Reporte, out);

        byte[] data = out.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(data);

        String destino = "SIGN_ERROR.xml";
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length,
                destino);

    }

}

From source file:gobblin.aws.GobblinAWSClusterLauncher.java

License:Apache License

@VisibleForTesting
AWSSdkClient createAWSSdkClient() {//from  ww  w . j a  v a 2  s .co m
    return new AWSSdkClient(this.awsClusterSecurityManager, Region.getRegion(Regions.fromName(this.awsRegion)));
}

From source file:gov.pnnl.cloud.producer.kinesis.ProducerBuilder.java

License:Open Source License

public ProducerBuilder withRegion(String regionName) {
    Region region = Region.getRegion(Regions.fromName(regionName));
    this.region = region;
    return this;
}

From source file:gov.usgs.cida.iplover.util.ImageStorage.java

public static AmazonS3 prepS3Client() {

    AWSCredentials credentials = null;/* www  . j a v  a 2s.co m*/
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (~/.aws/credentials), and is in valid format.", e);
    }

    AmazonS3 s3 = new AmazonS3Client(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    return s3;
}

From source file:hu.cloud.edu.SimpleQueueServiceSample.java

License:Open Source License

public static void main(String[] args) throws Exception {

    /*//from w  ww. j a  v  a  2  s. co m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (C:\\Users\\Isaac\\.aws\\credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("default").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (C:\\Users\\Isaac\\.aws\\credentials), and is in valid format.", e);
    }

    AmazonSQS sqs = new AmazonSQSClient(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon SQS");
    System.out.println("===========================================\n");

    try {
        // Create a queue
        System.out.println("Creating a new SQS queue called MyQueue.\n");
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
        String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

        // List queues
        System.out.println("Listing all queues in your account.\n");
        for (String queueUrl : sqs.listQueues().getQueueUrls()) {
            System.out.println("  QueueUrl: " + queueUrl);
        }
        System.out.println();

        // Send a message
        System.out.println("Sending a message to MyQueue.\n");
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));

        // Receive messages
        System.out.println("Receiving messages from MyQueue.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete a message
        System.out.println("Deleting a message.\n");
        String messageRecieptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

        // Delete a queue
        System.out.println("Deleting the test queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon SQS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with SQS, such as not "
                + "being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:il.co.togetthere.db.AmazonClientManager.java

License:Open Source License

private void initClients() {
    CognitoCachingCredentialsProvider credentials = new CognitoCachingCredentialsProvider(context,
            Constants.ACCOUNT_ID, Constants.IDENTITY_POOL_ID, Constants.UNAUTH_ROLE_ARN, null,
            Regions.US_EAST_1);//from ww w.java2 s . co  m

    ddb = new AmazonDynamoDBClient(credentials);
    ddb.setRegion(Region.getRegion(Regions.US_WEST_2));
}

From source file:ingest.utility.IngestUtilities.java

License:Apache License

/**
 * Gets an instance of an S3 client to use.
 * /*w w w . ja  v a2  s. c o m*/
 * @param useEncryption
 *            True if encryption should be used (only for Piazza Bucket). For all external Buckets, encryption is
 *            not used.
 * 
 * @return The S3 client
 */
public AmazonS3 getAwsClient(boolean useEncryption) {
    AmazonS3 s3Client;
    if ((AMAZONS3_ACCESS_KEY.isEmpty()) && (AMAZONS3_PRIVATE_KEY.isEmpty())) {
        s3Client = new AmazonS3Client();
    } else {
        BasicAWSCredentials credentials = new BasicAWSCredentials(AMAZONS3_ACCESS_KEY, AMAZONS3_PRIVATE_KEY);
        // Set up encryption using the KMS CMK Key
        if (useEncryption) {
            KMSEncryptionMaterialsProvider materialProvider = new KMSEncryptionMaterialsProvider(S3_KMS_CMK_ID);
            s3Client = new AmazonS3EncryptionClient(credentials, materialProvider,
                    new CryptoConfiguration().withKmsRegion(Regions.US_EAST_1))
                            .withRegion(Region.getRegion(Regions.US_EAST_1));
        } else {
            s3Client = new AmazonS3Client(credentials);
        }
    }
    return s3Client;
}

From source file:io.fineo.client.auth.AWSAbstractCognitoIdentityProvider.java

License:Open Source License

/**
 * Sets up an AWSAbstractCognitoIdentityProvider, which will serve as the
 * baseline for both Cognito and developer trusted identity providers.
 * Custom providers should not extend this class, but should extend
 * AWSAbstractCognitoDeveloperIdentityProvider
 *
 * @param accountId the accountId of the developer
 * @param identityPoolId the identityPoolId to be used
 * @param clientConfiguration the client configuration to be used by the
 *            client// w w w  .  j  a  va 2  s.c  o m
 * @param region the region cognito will use
 */
public AWSAbstractCognitoIdentityProvider(String accountId, String identityPoolId,
        ClientConfiguration clientConfiguration, Regions region) {
    this(accountId, identityPoolId,
            new AmazonCognitoIdentityClient(new AnonymousAWSCredentials(), clientConfiguration));
    this.cib.setRegion(Region.getRegion(region));
}