List of usage examples for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials
public BasicAWSCredentials(String accessKey, String secretKey)
From source file:com.eBilling.util.S3Example.java
public static void main(String[] args) throws IOException { AWSCredentials Credentials = new BasicAWSCredentials("AKIAJKLWA7ECH7VQKWVQ", "7XxAbyy0wZ+Dt25g3Ug4XYS7JW66YBLFyQ00MIg2"); S3Example s3client = new S3Example(); s3client.uploadfile(Credentials);//w w w . j ava 2 s . co m //s3client.deletefile(Credentials); //s3client.downloadfile(Credentials); }
From source file:com.ec2box.manage.action.AWSCredAction.java
License:Apache License
/** * Validates fields for credential submit *///from ww w. j a v a2s .co m public void validateSaveAWSCred() { if (awsCred.getAccessKey() == null || awsCred.getAccessKey().trim().equals("")) { addFieldError("awsCred.accessKey", "Required"); } if (awsCred.getSecretKey() == null || awsCred.getSecretKey().trim().equals("")) { addFieldError("awsCred.secretKey", "Required"); } if (!this.hasErrors()) { try { //check if credential are valid BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); AmazonEC2 service = new AmazonEC2Client(awsCredentials, AWSClientConfig.getClientConfig()); service.describeKeyPairs(); } catch (Exception ex) { addActionError("Invalid Credentials"); } } if (this.hasActionErrors() || this.hasErrors()) { sortedSet = AWSCredDB.getAWSCredSet(sortedSet); } }
From source file:com.ec2box.manage.action.EC2KeyAction.java
License:Apache License
/** * returns keypairs as a json string//from w w w. java 2 s . c om */ @Action(value = "/manage/getKeyPairJSON") public String getKeyPairJSON() { AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredId()); //set AWS credentials for service BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); AmazonEC2 service = new AmazonEC2Client(awsCredentials, AWSClientConfig.getClientConfig()); service.setEndpoint(ec2Key.getEc2Region()); DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); DescribeKeyPairsResult describeKeyPairsResult = service.describeKeyPairs(describeKeyPairsRequest); List<KeyPairInfo> keyPairInfoList = describeKeyPairsResult.getKeyPairs(); String json = new Gson().toJson(keyPairInfoList); try { servletResponse.getOutputStream().write(json.getBytes()); } catch (Exception ex) { log.error(ex.toString(), ex); } return null; }
From source file:com.ec2box.manage.action.EC2KeyAction.java
License:Apache License
@Action(value = "/manage/submitEC2Key", results = { @Result(name = "input", location = "/manage/view_ec2_keys.jsp"), @Result(name = "success", location = "/manage/viewEC2Keys.action", type = "redirect") }) public String submitEC2Key() { String retVal = SUCCESS;//from w ww.j ava 2 s . c o m try { //get AWS credentials from DB AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredId()); //set AWS credentials for service BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); //create service AmazonEC2 service = new AmazonEC2Client(awsCredentials, AWSClientConfig.getClientConfig()); service.setEndpoint(ec2Key.getEc2Region()); //create key pair request CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest(); createKeyPairRequest.withKeyName(ec2Key.getKeyNm()); //call service CreateKeyPairResult createKeyPairResult = service.createKeyPair(createKeyPairRequest); //get key pair result KeyPair keyPair = createKeyPairResult.getKeyPair(); //set private key String privateKey = keyPair.getKeyMaterial(); ec2Key.setPrivateKey(privateKey); //add to db EC2KeyDB.saveEC2Key(ec2Key); } catch (AmazonServiceException ex) { addActionError(ex.getMessage()); retVal = INPUT; } return retVal; }
From source file:com.ec2box.manage.action.EC2KeyAction.java
License:Apache License
@Action(value = "/manage/importEC2Key", results = { @Result(name = "input", location = "/manage/view_ec2_keys.jsp"), @Result(name = "success", location = "/manage/viewEC2Keys.action", type = "redirect") }) public String importEC2Key() { String retVal = SUCCESS;//from www . ja v a 2 s .c o m try { //get AWS credentials from DB AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredId()); //set AWS credentials for service BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); //create service AmazonEC2 service = new AmazonEC2Client(awsCredentials, AWSClientConfig.getClientConfig()); service.setEndpoint(ec2Key.getEc2Region()); //describe key pair request DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); describeKeyPairsRequest.setKeyNames(Arrays.asList(ec2Key.getKeyNm())); //call service DescribeKeyPairsResult describeKeyPairsResult = service.describeKeyPairs(describeKeyPairsRequest); if (describeKeyPairsResult != null && describeKeyPairsResult.getKeyPairs().size() > 0) { //add to db EC2KeyDB.saveEC2Key(ec2Key); } else { addActionError("Imported key does not exist on AWS"); retVal = INPUT; } } catch (AmazonServiceException ex) { addActionError(ex.getMessage()); retVal = INPUT; } return retVal; }
From source file:com.ec2box.manage.action.SystemAction.java
License:Apache License
@Action(value = "/admin/viewSystems", results = { @Result(name = "success", location = "/admin/view_systems.jsp") }) public String viewSystems() { Long userId = AuthUtil.getUserId(servletRequest.getSession()); String userType = AuthUtil.getUserType(servletRequest.getSession()); List<String> ec2RegionList = EC2KeyDB.getEC2Regions(); List<String> instanceIdList = new ArrayList<String>(); //default instance state if (sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE) == null) { sortedSet.getFilterMap().put(FILTER_BY_INSTANCE_STATE, AppConfig.getProperty("defaultInstanceState")); }/*from w w w. j a v a 2 s . com*/ try { Map<String, HostSystem> hostSystemList = new HashMap<String, HostSystem>(); //if user profile has been set or user is a manager List<Profile> profileList = UserProfileDB.getProfilesByUser(userId); if (profileList.size() > 0 || Auth.MANAGER.equals(userType)) { //set tags for profile List<String> profileTags = new ArrayList<>(); for (Profile profile : profileList) { profileTags.add(profile.getTag()); } Map<String, List<String>> profileTagMap = parseTags(profileTags); //set tags from input filters Map<String, List<String>> filterTags = fetchInputFilterTags(userType, profileTagMap); //parse out security group list in format group[,group] List<String> securityGroupList = new ArrayList<>(); if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SECURITY_GROUP))) { securityGroupList = Arrays .asList(sortedSet.getFilterMap().get(FILTER_BY_SECURITY_GROUP).split(",")); } //get AWS credentials from DB for (AWSCred awsCred : AWSCredDB.getAWSCredList()) { if (awsCred != null) { //set AWS credentials for service BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(), awsCred.getSecretKey()); for (String ec2Region : ec2RegionList) { //create service AmazonEC2 service = new AmazonEC2Client(awsCredentials, AWSClientConfig.getClientConfig()); service.setEndpoint(ec2Region); //only return systems that have keys set List<String> keyValueList = new ArrayList<String>(); for (EC2Key ec2Key : EC2KeyDB.getEC2KeyByRegion(ec2Region, awsCred.getId())) { keyValueList.add(ec2Key.getKeyNm()); } DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); Filter keyNmFilter = new Filter("key-name", keyValueList); describeInstancesRequest.withFilters(keyNmFilter); //instance state filter if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE))) { List<String> instanceStateList = new ArrayList<String>(); instanceStateList.add(sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE)); Filter instanceStateFilter = new Filter("instance-state-name", instanceStateList); describeInstancesRequest.withFilters(instanceStateFilter); } if (securityGroupList.size() > 0) { Filter groupFilter = new Filter("group-name", securityGroupList); describeInstancesRequest.withFilters(groupFilter); } //set name value pair for tag filter List<String> tagList = new ArrayList<String>(); //always add all profile tags to filter list addTagsToDescribeInstanceRequest(profileTagMap, describeInstancesRequest, tagList); //add all additional filter tags provided by the user addTagsToDescribeInstanceRequest(filterTags, describeInstancesRequest, tagList); if (tagList.size() > 0) { Filter tagFilter = new Filter("tag-key", tagList); describeInstancesRequest.withFilters(tagFilter); } DescribeInstancesResult describeInstancesResult = service .describeInstances(describeInstancesRequest); for (Reservation res : describeInstancesResult.getReservations()) { for (Instance instance : res.getInstances()) { HostSystem hostSystem = new HostSystem(); hostSystem.setInstance(instance.getInstanceId()); //check for public dns if doesn't exist set to ip or pvt dns if (!"true".equals(AppConfig.getProperty("useEC2PvtDNS")) && StringUtils.isNotEmpty(instance.getPublicDnsName())) { hostSystem.setHost(instance.getPublicDnsName()); } else if (!"true".equals(AppConfig.getProperty("useEC2PvtDNS")) && StringUtils.isNotEmpty(instance.getPublicIpAddress())) { hostSystem.setHost(instance.getPublicIpAddress()); } else if (StringUtils.isNotEmpty(instance.getPrivateDnsName())) { hostSystem.setHost(instance.getPrivateDnsName()); } else { hostSystem.setHost(instance.getPrivateIpAddress()); } hostSystem.setKeyId(EC2KeyDB .getEC2KeyByNmRegion(instance.getKeyName(), ec2Region, awsCred.getId()) .getId()); hostSystem.setEc2Region(ec2Region); hostSystem.setState(instance.getState().getName()); for (Tag tag : instance.getTags()) { if ("Name".equals(tag.getKey())) { hostSystem.setDisplayNm(tag.getValue()); } } instanceIdList.add(hostSystem.getInstance()); hostSystemList.put(hostSystem.getInstance(), hostSystem); } } if (instanceIdList.size() > 0) { //set instance id list to check permissions when creating sessions servletRequest.getSession().setAttribute("instanceIdList", new ArrayList<String>(instanceIdList)); if (showStatus) { //make service call 100 instances at a time b/c of AWS limitation int i = 0; List<String> idCallList = new ArrayList<String>(); while (!instanceIdList.isEmpty()) { idCallList.add(instanceIdList.remove(0)); i++; //when i eq 100 make call if (i >= 100 || instanceIdList.isEmpty()) { //get status for host systems DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest(); describeInstanceStatusRequest.withInstanceIds(idCallList); DescribeInstanceStatusResult describeInstanceStatusResult = service .describeInstanceStatus(describeInstanceStatusRequest); for (InstanceStatus instanceStatus : describeInstanceStatusResult .getInstanceStatuses()) { HostSystem hostSystem = hostSystemList .remove(instanceStatus.getInstanceId()); hostSystem.setSystemStatus( instanceStatus.getSystemStatus().getStatus()); hostSystem.setInstanceStatus( instanceStatus.getInstanceStatus().getStatus()); //check and filter by instance or system status if ((StringUtils.isEmpty( sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATUS)) && StringUtils.isEmpty(sortedSet.getFilterMap() .get(FILTER_BY_SYSTEM_STATUS))) || (hostSystem.getInstanceStatus() .equals(sortedSet.getFilterMap() .get(FILTER_BY_INSTANCE_STATUS)) && StringUtils.isEmpty(sortedSet.getFilterMap() .get(FILTER_BY_SYSTEM_STATUS))) || (hostSystem.getInstanceStatus() .equals(sortedSet.getFilterMap() .get(FILTER_BY_SYSTEM_STATUS)) && StringUtils.isEmpty(sortedSet.getFilterMap() .get(FILTER_BY_INSTANCE_STATUS))) || (hostSystem.getInstanceStatus() .equals(sortedSet.getFilterMap() .get(FILTER_BY_SYSTEM_STATUS)) && hostSystem.getInstanceStatus() .equals(sortedSet.getFilterMap() .get(FILTER_BY_INSTANCE_STATUS)))) { hostSystemList.put(hostSystem.getInstance(), hostSystem); } } //start over i = 0; //clear list idCallList.clear(); } } //check alarms for ec2 instances AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient( awsCredentials, AWSClientConfig.getClientConfig()); cloudWatchClient.setEndpoint(ec2Region.replace("ec2", "monitoring")); DescribeAlarmsResult describeAlarmsResult = cloudWatchClient.describeAlarms(); for (MetricAlarm metricAlarm : describeAlarmsResult.getMetricAlarms()) { for (Dimension dim : metricAlarm.getDimensions()) { if (dim.getName().equals("InstanceId")) { HostSystem hostSystem = hostSystemList.remove(dim.getValue()); if (hostSystem != null) { if ("ALARM".equals(metricAlarm.getStateValue())) { hostSystem .setMonitorAlarm(hostSystem.getMonitorAlarm() + 1); } else if ("INSUFFICIENT_DATA" .equals(metricAlarm.getStateValue())) { hostSystem.setMonitorInsufficientData( hostSystem.getMonitorInsufficientData() + 1); } else { hostSystem.setMonitorOk(hostSystem.getMonitorOk() + 1); } //check and filter by alarm state if (StringUtils.isEmpty( sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))) { hostSystemList.put(hostSystem.getInstance(), hostSystem); } else if ("ALARM".equals( sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE)) && hostSystem.getMonitorAlarm() > 0) { hostSystemList.put(hostSystem.getInstance(), hostSystem); } else if ("INSUFFICIENT_DATA".equals( sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE)) && hostSystem.getMonitorInsufficientData() > 0) { hostSystemList.put(hostSystem.getInstance(), hostSystem); } else if ("OK".equals( sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE)) && hostSystem.getMonitorOk() > 0 && hostSystem.getMonitorInsufficientData() <= 0 && hostSystem.getMonitorAlarm() <= 0) { hostSystemList.put(hostSystem.getInstance(), hostSystem); } } } } } } } } } } //set ec2 systems SystemDB.setSystems(hostSystemList.values()); sortedSet = SystemDB.getSystemSet(sortedSet, new ArrayList<String>(hostSystemList.keySet())); } } catch (AmazonServiceException ex) { log.error(ex.toString(), ex); } if (script != null && script.getId() != null) { script = ScriptDB.getScript(script.getId(), userId); } return SUCCESS; }
From source file:com.emc.ecs.sync.source.S3Source.java
License:Open Source License
@Override public void configure(SyncSource source, Iterator<SyncFilter> filters, SyncTarget target) { Assert.hasText(accessKey, "accessKey is required"); Assert.hasText(secretKey, "secretKey is required"); Assert.hasText(bucketName, "bucketName is required"); Assert.isTrue(bucketName.matches("[A-Za-z0-9._-]+"), bucketName + " is not a valid bucket name"); AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); ClientConfiguration config = new ClientConfiguration(); if (protocol != null) config.setProtocol(Protocol.valueOf(protocol.toUpperCase())); if (legacySignatures) config.setSignerOverride("S3SignerType"); if (socketTimeoutMs >= 0) config.setSocketTimeout(socketTimeoutMs); s3 = new AmazonS3Client(creds, config); if (endpoint != null) s3.setEndpoint(endpoint);/* w ww . j a v a 2 s.c o m*/ // TODO: generalize uri translation AwsS3Util.S3Uri s3Uri = new AwsS3Util.S3Uri(); s3Uri.protocol = protocol; s3Uri.endpoint = endpoint; s3Uri.accessKey = accessKey; s3Uri.secretKey = secretKey; s3Uri.rootKey = rootKey; if (sourceUri == null) sourceUri = s3Uri.toUri(); if (disableVHosts) { log.info( "The use of virtual hosted buckets on the s3 source has been DISABLED. Path style buckets will be used."); S3ClientOptions opts = new S3ClientOptions(); opts.setPathStyleAccess(true); s3.setS3ClientOptions(opts); } if (!s3.doesBucketExist(bucketName)) { throw new ConfigurationException("The bucket " + bucketName + " does not exist."); } if (rootKey == null) rootKey = ""; // make sure rootKey isn't null // for version support. TODO: genericize version support if (target instanceof S3Target) { s3Target = (S3Target) target; if (s3Target.isIncludeVersions()) { BucketVersioningConfiguration versioningConfig = s3.getBucketVersioningConfiguration(bucketName); List<String> versionedStates = Arrays.asList(BucketVersioningConfiguration.ENABLED, BucketVersioningConfiguration.SUSPENDED); versioningEnabled = versionedStates.contains(versioningConfig.getStatus()); } } }
From source file:com.emc.ecs.sync.target.S3Target.java
License:Open Source License
@Override public void configure(SyncSource source, Iterator<SyncFilter> filters, SyncTarget target) { Assert.hasText(accessKey, "accessKey is required"); Assert.hasText(secretKey, "secretKey is required"); Assert.hasText(bucketName, "bucketName is required"); Assert.isTrue(bucketName.matches("[A-Za-z0-9._-]+"), bucketName + " is not a valid bucket name"); AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); ClientConfiguration config = new ClientConfiguration(); if (protocol != null) config.setProtocol(Protocol.valueOf(protocol.toUpperCase())); if (legacySignatures) config.setSignerOverride("S3SignerType"); if (socketTimeoutMs >= 0) config.setSocketTimeout(socketTimeoutMs); s3 = new AmazonS3Client(creds, config); if (endpoint != null) s3.setEndpoint(endpoint);/* w w w.j a v a 2 s .c o m*/ // TODO: generalize uri translation AwsS3Util.S3Uri s3Uri = new AwsS3Util.S3Uri(); s3Uri.protocol = protocol; s3Uri.endpoint = endpoint; s3Uri.accessKey = accessKey; s3Uri.secretKey = secretKey; s3Uri.rootKey = rootKey; if (targetUri == null) targetUri = s3Uri.toUri(); if (disableVHosts) { log.info( "The use of virtual hosted buckets on the s3 source has been DISABLED. Path style buckets will be used."); S3ClientOptions opts = new S3ClientOptions(); opts.setPathStyleAccess(true); s3.setS3ClientOptions(opts); } // for version support. TODO: genericize version support if (source instanceof S3Source) { s3Source = (S3Source) source; if (!s3Source.isVersioningEnabled()) includeVersions = false; // don't include versions if source versioning is off } else if (includeVersions) { throw new ConfigurationException( "Object versions are currently only supported with the S3 source & target plugins."); } if (!s3.doesBucketExist(bucketName)) { if (createBucket) { s3.createBucket(bucketName); if (includeVersions) s3.setBucketVersioningConfiguration(new SetBucketVersioningConfigurationRequest(bucketName, new BucketVersioningConfiguration(BucketVersioningConfiguration.ENABLED))); } else { throw new ConfigurationException("The bucket " + bucketName + " does not exist."); } } if (rootKey == null) rootKey = ""; // make sure rootKey isn't null if (includeVersions) { String status = s3.getBucketVersioningConfiguration(bucketName).getStatus(); if (BucketVersioningConfiguration.OFF.equals(status)) throw new ConfigurationException("The specified bucket does not have versioning enabled."); } if (mpuThresholdMB > AwsS3Util.MAX_PUT_SIZE_MB) { log.warn("{}MB is above the maximum PUT size of {}MB. the maximum will be used instead", mpuThresholdMB, AwsS3Util.MAX_PUT_SIZE_MB); mpuThresholdMB = AwsS3Util.MAX_PUT_SIZE_MB; } if (mpuPartSizeMB < AwsS3Util.MIN_PART_SIZE_MB) { log.warn("{}MB is below the minimum MPU part size of {}MB. the minimum will be used instead", mpuPartSizeMB, AwsS3Util.MIN_PART_SIZE_MB); mpuPartSizeMB = AwsS3Util.MIN_PART_SIZE_MB; } }
From source file:com.emc.vipr.s3.s3api.java
License:Open Source License
public static ViPRS3Client getS3Client(String S3_ACCESS_KEY_ID, String S3_SECRET_KEY, String S3_ENDPOINT, String S3_ViPR_NAMESPACE) { BasicAWSCredentials creds = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY); S3ClientOptions opt = new S3ClientOptions(); opt.setPathStyleAccess(true);//ww w .j av a2s. c o m ViPRS3Client client = new ViPRS3Client(S3_ENDPOINT, creds); client.setS3ClientOptions(opt); if (S3_ViPR_NAMESPACE != null) { client.setNamespace(S3_ViPR_NAMESPACE); } return client; }
From source file:com.emc.vipr.s3.sample.AWSS3Factory.java
License:Open Source License
public static AmazonS3 getS3Client() { BasicAWSCredentials creds = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY); ClientConfiguration cc = new ClientConfiguration(); //cc.setProxyHost("localhost"); //cc.setProxyPort(8888); // Force use of v2 Signer. cc.setSignerOverride("S3SignerType"); AmazonS3 client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(creds)) .withClientConfiguration(cc).withPathStyleAccessEnabled(true) // Path-style bucket naming is highly recommended .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(S3_ENDPOINT, null)).build(); return client; }