List of usage examples for com.amazonaws AmazonServiceException getMessage
@Override
public String getMessage()
From source file:edu.utn.frba.grupo5303.serverenviolibre.services.NotificacionesPushService.java
@Override public void enviarNotificacion(NotificacionPush notificacion) { try {//from w ww .ja v a 2s. c o m logger.log(Level.INFO, "Enviando notificacion al snsId: {0}", notificacion.getGcmIdDestino()); logger.log(Level.INFO, "Enviando notificacion de tipo: {0}", notificacion.getCodigo()); PublishRequest publishRequest = new PublishRequest(); Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes( attributesMap.get(plataforma)); if (notificationAttributes != null && !notificationAttributes.isEmpty()) { publishRequest.setMessageAttributes(notificationAttributes); } publishRequest.setMessageStructure("json"); // If the message attributes are not set in the requisite method, // notification is sent with default attributes Map<String, String> messageMap = new HashMap<>(); messageMap.put(plataforma.name(), notificacion.getMensajeDeNotificacion()); String message = SampleMessageGenerator.jsonify(messageMap); // Create Platform Application. This corresponds to an app on a // platform. CreatePlatformApplicationResult platformApplicationResult = createPlatformApplication(); // The Platform Application Arn can be used to uniquely identify the // Platform Application. String platformApplicationArn = platformApplicationResult.getPlatformApplicationArn(); // Create an Endpoint. This corresponds to an app on a device. CreatePlatformEndpointResult platformEndpointResult = createPlatformEndpoint("CustomData", notificacion.getGcmIdDestino(), platformApplicationArn); // For direct publish to mobile end points, topicArn is not relevant. publishRequest.setTargetArn(platformEndpointResult.getEndpointArn()); publishRequest.setMessage(message); snsClient.publish(publishRequest); } catch (AmazonServiceException ase) { logger.log(Level.SEVERE, "Caught an AmazonServiceException, which means your request made it " + "to Amazon SNS, but was rejected with an error response for some reason."); logger.log(Level.SEVERE, "Error Message: {0}", ase.getMessage()); logger.log(Level.SEVERE, "HTTP Status Code: {0}", ase.getStatusCode()); logger.log(Level.SEVERE, "AWS Error Code: {0}", ase.getErrorCode()); logger.log(Level.SEVERE, "Error Type: {0}", ase.getErrorType()); logger.log(Level.SEVERE, "Request ID: {0}", ase.getRequestId()); } catch (AmazonClientException ace) { logger.log(Level.SEVERE, "Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with SNS, such as not " + "being able to access the network."); logger.log(Level.SEVERE, "Error Message: {0}", ace.getMessage()); } }
From source file:eu.optimis.interopt.provider.aws.AmazonClient.java
License:Apache License
@Override public void deployService(String service_id, List<ServiceComponent> serviceComponents, XmlBeanServiceManifestDocument manifest) throws ServiceInstantiationException { AmazonEC2 ec2 = getAmazonEC2Client(); log.info("Deploying service..."); if (isDeployed(service_id)) { throw new ServiceInstantiationException( "This service is already deployed! " + "Terminate it before deploying it again.", new java.lang.Throwable()); }/*from w w w. j a v a 2 s . c om*/ // Get the number of VMs to deploy int totalVms = 0; for (ServiceComponent sc : serviceComponents) { totalVms = totalVms + sc.getInstances(); } // If sum < maxvms invoke createVM method as many times as needed if (totalVms > AmazonClient.maxvms) { throw new ServiceInstantiationException("Number of VMs to deploy exceeds the maximum", new java.lang.Throwable()); } for (ServiceComponent sc : serviceComponents) { int numInstances = sc.getInstances(); log.info("Number of vm instances to deploy: " + numInstances); String imageId = sc.getImage(); InstanceType type = selectInstanceType(sc); Placement placement = new Placement(); placement.setAvailabilityZone(availabilityZone.getZoneName()); RunInstancesRequest req = new RunInstancesRequest(imageId, numInstances, numInstances); ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add(SECURITY_GROUP); req.setSecurityGroupIds(securityGroups); req.setInstanceType(type); req.setPlacement(placement); //req.setMonitoring(true); try { RunInstancesResult res = ec2.runInstances(req); List<Instance> instances = res.getReservation().getInstances(); log.info("Creating Tags..."); for (Instance inst : instances) { Tag tag = new Tag("serviceid", service_id); List<Tag> tags = new ArrayList<Tag>(); tags.add(tag); List<String> resources = new ArrayList<String>(); resources.add(inst.getInstanceId()); CreateTagsRequest req2 = new CreateTagsRequest(resources, tags); ec2.createTags(req2); } } catch (AmazonServiceException e) { log.error("Service deployment has failed: "); log.error(printServiceException(e)); throw new ServiceInstantiationException("Service deployment has failed: " + e.getMessage(), new java.lang.Throwable()); } log.info("Service Deployed successfully!"); } }
From source file:eu.optimis.interopt.provider.aws.AmazonClient.java
License:Apache License
@Override public List<VMProperties> queryServiceProperties(String serviceId) throws UnknownServiceException { List<VMProperties> list = null; AmazonEC2 ec2 = getAmazonEC2Client(); log.info("Querying service VMs..."); List<String> sids = new ArrayList<String>(); sids.add(serviceId);/* w ww . ja v a 2 s. c om*/ Filter filt = new Filter("tag:serviceid", sids); List<Filter> filters = new ArrayList<Filter>(); filters.add(filt); DescribeInstancesRequest req = new DescribeInstancesRequest(); req.setFilters(filters); try { DescribeInstancesResult res = ec2.describeInstances(req); List<Instance> instances = new ArrayList<Instance>(); for (Reservation r : res.getReservations()) { instances.addAll(r.getInstances()); } log.info("#VMs found: " + instances.size()); list = new ArrayList<VMProperties>(); for (Instance inst : instances) { String status = inst.getState().getName().toString(); if (!status.equals(InstanceStateName.Terminated.toString())) { VMProperties prop = new VMProperties(); prop.setId(inst.getInstanceId()); prop.setStatus(inst.getState().getName().toString()); prop.setHostname(inst.getPublicDnsName()); prop.setIp(inst.getPublicIpAddress()); prop.put(VMProperties.AWS_INSTANCE_TYPE, inst.getInstanceType()); list.add(prop); } } } catch (AmazonServiceException e) { log.error("Service query has failed: "); log.error(printServiceException(e)); throw new UnknownServiceException("Service query has failed: " + e.getMessage()); } return list; }
From source file:eu.optimis.interopt.provider.aws.AmazonClient.java
License:Apache License
@Override public void terminate(String serviceId) throws UnknownServiceException { AmazonEC2 ec2 = getAmazonEC2Client(); log.info("Terminating service..."); List<VMProperties> vms = queryServiceProperties(serviceId); List<String> instances = new ArrayList<String>(); for (VMProperties vm : vms) { if (!(vm.getStatus().equals(InstanceStateName.Terminated.toString()) || vm.getStatus().equals(InstanceStateName.ShuttingDown.toString()))) { instances.add(vm.getId());/*from w w w .j a v a 2 s .c o m*/ log.debug("Instance to stop: " + vm.getId()); } } if (instances.size() == 0) { log.info("There are no instances to be terminated!"); return; } TerminateInstancesRequest req = new TerminateInstancesRequest(instances); try { ec2.terminateInstances(req); } catch (AmazonServiceException e) { log.error("Service termination has failed: "); log.error(printServiceException(e)); throw new UnknownServiceException("Service termination has failed: " + e.getMessage()); } }
From source file:eu.optimis.interopt.provider.aws.AmazonClient.java
License:Apache License
private String printServiceException(AmazonServiceException se) { return se.getMessage() + "(HTTP Code: " + se.getStatusCode() + " - AWS Code: " + se.getErrorCode() + " - Error Type: " + se.getErrorType() + " )"; }
From source file:example.uploads3.UploadS3.java
License:Apache License
public static void main(String[] args) throws Exception { String uploadFileName = args[0]; String bucketName = "haos3"; String keyName = "test/byspark.txt"; // Create a Java Spark Context. SparkConf conf = new SparkConf().setAppName("UploadS3"); JavaSparkContext sc = new JavaSparkContext(conf); AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider()); try {/* ww w. j a v a 2 s .c o m*/ System.out.println("Uploading a new object to S3 from a file\n"); File file = new File(uploadFileName); PutObjectRequest putRequest = new PutObjectRequest(bucketName, keyName, file); // Request server-side encryption. ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setServerSideEncryption("AES256"); putRequest.setMetadata(objectMetadata); s3client.putObject(putRequest); } 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 " + "an internal error 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:exemplos.S3Sample.java
License:Open Source License
public static void main(String[] args) throws IOException { /*/*ww w . j a va 2 s .co 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") private boolean subirArchivo(StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre, Vector archivos) { //System.out.println("AwsConn SubirArchivo:" + nombre + ":nombre"); if (!archivos.isEmpty()) { FileItem actual = null;//from w ww . ja v a 2s . com try { for (int i = 0; i < archivos.size(); i++) { InputStream inputStream = null; try { actual = (FileItem) archivos.elementAt(i); ///////////////////////////////////////////////////////// //Obtain the Content length of the Input stream for S3 header InputStream is = actual.getInputStream(); byte[] contentBytes = IOUtils.toByteArray(is); Long contentLength = Long.valueOf(contentBytes.length); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(contentLength); //Reobtain the tmp uploaded file as input stream inputStream = actual.getInputStream(); //Put the object in S3 //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); s3.putObject(new PutObjectRequest(S3BUKT, nombre, inputStream, metadata)); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } //////////////////////////////////////////////////////////// } return true; } catch (AmazonServiceException ase) { ase.printStackTrace(); msj.append("Error de AmazonServiceException al subir archivo a S3.<br>"); msj.append("Mensaje: " + ase.getMessage() + "<br>"); msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>"); msj.append("Cdigo de Error AWS: " + ase.getErrorCode() + "<br>"); msj.append("Tipo de Error: " + ase.getErrorType() + "<br>"); msj.append("Request ID: " + ase.getRequestId()); return false; } catch (AmazonClientException ace) { ace.printStackTrace(); msj.append("Error de AmazonClientException al subir archivo a S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } catch (IOException e) { e.printStackTrace(); msj.append("Error de Entrada/Salida al subir archivo a S3: " + e.getMessage()); return false; } } else { msj.append("Error al subir archivo a la nube: No se envi ningun archivo"); return false; } }
From source file:fsi_admin.JAwsS3Conn.java
License:Open Source License
private boolean eliminarArchivo(StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre) { //System.out.println("AwsConn EliminarArchivo:" + nombre + ":nombre"); try {/*from ww w . j a v a 2 s . co m*/ //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); s3.deleteObject(S3BUKT, nombre); return true; } catch (AmazonServiceException ase) { ase.printStackTrace(); msj.append("Error de AmazonServiceException al eliminar archivo de S3.<br>"); msj.append("Mensaje: " + ase.getMessage() + "<br>"); msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>"); msj.append("Cdigo de Error AWS: " + ase.getErrorCode() + "<br>"); msj.append("Tipo de Error: " + ase.getErrorType() + "<br>"); msj.append("Request ID: " + ase.getRequestId()); return false; } catch (AmazonClientException ace) { ace.printStackTrace(); msj.append("Error de AmazonClientException al eliminar archivo de S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } }
From source file:fsi_admin.JAwsS3Conn.java
License:Open Source License
private boolean descargarArchivo(HttpServletResponse response, StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre, String destino) { //System.out.println("AwsConn DescargarArchivo:" + nombre + ":nombre"); try {//from ww w. j a v a2s. co m System.out.println("DESCARGA BUCKET: " + S3BUKT + " OBJETO: " + nombre); S3Object object = s3.getObject(new GetObjectRequest(S3BUKT, nombre)); //out.println("Content-Type: " + object.getObjectMetadata().getContentType()); //System.out.println("Content-Type: " + object.getObjectMetadata().getContentType()); byte[] byteArray = IOUtils.toByteArray(object.getObjectContent()); ByteArrayInputStream bais = new ByteArrayInputStream(byteArray); JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), bais, object.getObjectMetadata().getContentType(), byteArray.length, destino); System.out.println("Content-Length: " + object.getObjectMetadata().getContentLength() + " BA: " + byteArray.length); return true; } catch (AmazonServiceException ase) { ase.printStackTrace(); msj.append("Error de AmazonServiceException al descargar archivo de S3.<br>"); msj.append("Mensaje: " + ase.getMessage() + "<br>"); msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>"); msj.append("Cdigo de Error AWS: " + ase.getErrorCode() + "<br>"); msj.append("Tipo de Error: " + ase.getErrorType() + "<br>"); msj.append("Request ID: " + ase.getRequestId()); return false; } catch (AmazonClientException ace) { ace.printStackTrace(); msj.append("Error de AmazonClientException al descargar archivo de S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } catch (IOException ace) { ace.printStackTrace(); msj.append("Error de IOException al descargar archivo de S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } }