Java Code Examples for com.amazonaws.util.StringUtils

The following examples show how to use com.amazonaws.util.StringUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: alexa-meets-polly   Source File: ConvertService.java    License: Apache License 2.0 7 votes vote down vote up
public static AmazonS3 getS3Client(final String region, final String roleArn) {
    final Regions awsRegion = StringUtils.isNullOrEmpty(region) ? Regions.US_EAST_1 : Regions.fromName(region);

    if (StringUtils.isNullOrEmpty(roleArn)) {
        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).build();
    } else {
        final AssumeRoleRequest assumeRole = new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("io-klerch-mp3-converter");

        final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withRegion(awsRegion).build();
        final Credentials credentials = sts.assumeRole(assumeRole).getCredentials();

        final BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(
                credentials.getAccessKeyId(),
                credentials.getSecretAccessKey(),
                credentials.getSessionToken());

        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build();
    }
}
 
Example 2
/**
 * Transforms the raw string to LocalDate using the provided default format
 *
 * @param value raw value to be transformed to LocalDate
 * @param dateFormat customer specified or inferred dateformat
 * @param defaultTimeZone default timezone to be applied
 * @return LocalDate object parsed from value
 */
public static LocalDate stringToLocalDate(String value, String dateFormat,
                                          ZoneId defaultTimeZone)
{
    if (StringUtils.isNullOrEmpty(dateFormat)) {
        logger.info("Unable to parse {} as Date type due to invalid dateformat", value);
        return null;
    }
    Date dateTransformedValue = stringToDate(value, dateFormat);
    if (dateTransformedValue == null) {
        return null;
    }
    return dateTransformedValue.toInstant()
            .atZone(defaultTimeZone)
            .toLocalDate();
}
 
Example 3
@Override
public AWSCredentials getCredentials() {
    String accessKey = environment.getProperty(ACCESS_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_ACCESS_KEY_ENV_VAR, String.class, (String) null));

    String secretKey = environment.getProperty(SECRET_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_SECRET_KEY_ENV_VAR, String.class, (String) null));
    accessKey = StringUtils.trim(accessKey);
    secretKey = StringUtils.trim(secretKey);
    String sessionToken = StringUtils.trim(environment.getProperty(AWS_SESSION_TOKEN_ENV_VAR, String.class, (String) null));

    if (StringUtils.isNullOrEmpty(accessKey) || StringUtils.isNullOrEmpty(secretKey)) {
        throw new SdkClientException(
            "Unable to load AWS credentials from environment " +
                "(" + ACCESS_KEY_ENV_VAR + " (or " + ALTERNATE_ACCESS_KEY_ENV_VAR + ") and " +
                SECRET_KEY_ENV_VAR + " (or " + ALTERNATE_SECRET_KEY_ENV_VAR + "))");
    }

    return sessionToken == null ?
        new BasicAWSCredentials(accessKey, secretKey)
        :
        new BasicSessionCredentials(accessKey, secretKey, sessionToken);
}
 
Example 4
Source Project: pacbot   Source File: CloudInsightSqlServer.java    License: Apache License 2.0 6 votes vote down vote up
public static Connection getDBConnection() throws SQLException {
	String hostName = getClouldInsightSqlServer();
	String dbName = "cloudinsightbillingdb";
	String user = getClouldInsightUser();
	String password = getClouldInsightPassWord();

	if (StringUtils.isNullOrEmpty(hostName) || StringUtils.isNullOrEmpty(user)
			|| StringUtils.isNullOrEmpty(password)) {
		throw new RuntimeException(
				" Cloud insight server mandatory configuration CLOUD_INSIGHT_SQL_SERVER/CLOUD_INSIGHT_USER/CLOUD_INSIGHT_PASSWORD ");
	}
	String url = String.format(
			"jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;encrypt=true;"
					+ "hostNameInCertificate=*.database.windows.net;loginTimeout=30;",
			hostName, dbName, user, password);
	Connection connection = null;

	connection = DriverManager.getConnection(url);
	return connection;
}
 
Example 5
Source Project: github-bucket   Source File: RepositoryS3.java    License: ISC License 6 votes vote down vote up
private boolean isUploadFile(Iterator<S3ObjectSummary> iter, String path, String hash) {
    while (iter.hasNext()) {
        S3ObjectSummary fileS3 = iter.next();
        // Filename should look like this:
        // a/b
        if (!fileS3.getKey().equals(path)) {
            // If this is another file, then continue!
            continue;
        }
        // Remove the file from the S3 list as it does not need to be processed further
        iter.remove();
        // Upload if the hashes differ
        return StringUtils.isNullOrEmpty(hash) || !fileS3.getETag().equals(hash);
    }
    return true;
}
 
Example 6
Source Project: pipeline-aws-plugin   Source File: WithAWSStep.java    License: Apache License 2.0 6 votes vote down vote up
private void withFederatedUserId(@Nonnull EnvVars localEnv) {
	if (!StringUtils.isNullOrEmpty(this.step.getFederatedUserId())) {
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);
		GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
		getFederationTokenRequest.setDurationSeconds(this.step.getDuration());
		getFederationTokenRequest.setName(this.step.getFederatedUserId());
		getFederationTokenRequest.setPolicy(ALLOW_ALL_POLICY);

		GetFederationTokenResult federationTokenResult = sts.getFederationToken(getFederationTokenRequest);

		Credentials credentials = federationTokenResult.getCredentials();
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, credentials.getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, credentials.getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, credentials.getSessionToken());
		this.envVars.overrideAll(localEnv);
	}

}
 
Example 7
Source Project: pipeline-aws-plugin   Source File: WithAWSStep.java    License: Apache License 2.0 6 votes vote down vote up
private void withRole(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getRole())) {
		
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);

		AssumeRole assumeRole = IamRoleUtils.validRoleArn(this.step.getRole()) ? new AssumeRole(this.step.getRole()) :
				new AssumeRole(this.step.getRole(), this.createAccountId(sts), IamRoleUtils.selectPartitionName(this.step.getRegion()));
		assumeRole.withDurationSeconds(this.step.getDuration());
		assumeRole.withExternalId(this.step.getExternalId());
		assumeRole.withPolicy(this.step.getPolicy());
		assumeRole.withSamlAssertion(this.step.getSamlAssertion(), this.step.getPrincipalArn());
		assumeRole.withSessionName(this.createRoleSessionName());

		this.getContext().get(TaskListener.class).getLogger().format("Requesting assume role");
		AssumedRole assumedRole = assumeRole.assumedRole(sts);
		this.getContext().get(TaskListener.class).getLogger().format("Assumed role %s with id %s %n ", assumedRole.getAssumedRoleUser().getArn(), assumedRole.getAssumedRoleUser().getAssumedRoleId());

		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, assumedRole.getCredentials().getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, assumedRole.getCredentials().getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, assumedRole.getCredentials().getSessionToken());
		this.envVars.overrideAll(localEnv);
	}
}
 
Example 8
Source Project: github-bucket   Source File: RepositoryS3.java    License: ISC License 6 votes vote down vote up
private boolean isUploadFile(Iterator<S3ObjectSummary> iter, String path, String hash) {
    while (iter.hasNext()) {
        S3ObjectSummary fileS3 = iter.next();
        // Filename should look like this:
        // a/b
        if (!fileS3.getKey().equals(path)) {
            // If this is another file, then continue!
            continue;
        }
        // Remove the file from the S3 list as it does not need to be processed further
        iter.remove();
        // Upload if the hashes differ
        return StringUtils.isNullOrEmpty(hash) || !fileS3.getETag().equals(hash);
    }
    return true;
}
 
Example 9
Source Project: rdf-delta   Source File: PatchStoreProviderZkS3.java    License: Apache License 2.0 6 votes vote down vote up
private static DetailsS3 accessS3(LocalServerConfig configuration) {
    // Access and checking.
    String bucketName = configuration.getProperty(pBucketName);
    if ( StringUtils.isNullOrEmpty(bucketName) )
        throw new IllegalArgumentException("Missing required property: "+pBucketName);

    String region = configuration.getProperty(pRegion);
    if ( StringUtils.isNullOrEmpty(region) )
        throw new IllegalArgumentException("Missing required property: "+pRegion);

    String prefixStr = configuration.getProperty(pPrefix);
    if ( StringUtils.isNullOrEmpty(prefixStr) )
        prefixStr = DEFAULT_PREFIX;
    String prefix = (prefixStr!=null) ? prefixStr : DEFAULT_PREFIX;
    AmazonS3 client = S3.buildS3(configuration);
    return new DetailsS3(bucketName, prefix, client);
    //return access.computeIfAbsent(bucketName, n->new DetailsS3(bucketName, prefix, client));
}
 
Example 10
@Test
public void defaultSalt() throws Exception {
    // Tests all the different ways to get the default salt

    testCase trial = testCases[0];
    HmacKeyDerivationFunction kdf1 = HmacKeyDerivationFunction.getInstance(trial.algo);
    kdf1.init(trial.ikm, null);
    HmacKeyDerivationFunction kdf2 = HmacKeyDerivationFunction.getInstance(trial.algo);
    kdf2.init(trial.ikm, new byte[0]);
    HmacKeyDerivationFunction kdf3 = HmacKeyDerivationFunction.getInstance(trial.algo);
    kdf3.init(trial.ikm);
    HmacKeyDerivationFunction kdf4 = HmacKeyDerivationFunction.getInstance(trial.algo);
    kdf4.init(trial.ikm, new byte[32]);

    byte[] testBytes = "Test".getBytes(StringUtils.UTF8);
    byte[] key1 = kdf1.deriveKey(testBytes, 16);
    byte[] key2 = kdf2.deriveKey(testBytes, 16);
    byte[] key3 = kdf3.deriveKey(testBytes, 16);
    byte[] key4 = kdf4.deriveKey(testBytes, 16);

    assertArrayEquals(key1, key2);
    assertArrayEquals(key1, key3);
    assertArrayEquals(key1, key4);
}
 
Example 11
/**
 * Transforms the raw string to LocalDateTime using the provided default format
 *
 * @param value raw value to be transformed to LocalDateTime
 * @param dateFormat customer specified or inferred dateformat
 * @param defaultTimeZone default timezone to be applied
 * @return LocalDateTime or ZonedDateTime object parsed from value
 */
public static Object stringToDateTime(String value, String dateFormat, ZoneId defaultTimeZone)
{
    if (StringUtils.isNullOrEmpty(dateFormat)) {
        logger.warn("Unable to parse {} as DateTime type due to invalid date format", value);
        return null;
    }
    Date dateTransformedValue = stringToDate(value, dateFormat);
    if (dateTransformedValue == null) {
        return null;
    }
    return dateTransformedValue.toInstant()
            .atZone(defaultTimeZone)
            .toLocalDateTime();
}
 
Example 12
private byte[] getPasswordAuthenticationKey(String userId,
                                            String userPassword,
                                            BigInteger B,
                                            BigInteger salt) {
    // Authenticate the password
    // u = H(A, B)
    MessageDigest messageDigest = THREAD_MESSAGE_DIGEST.get();
    messageDigest.reset();
    messageDigest.update(A.toByteArray());
    BigInteger u = new BigInteger(1, messageDigest.digest(B.toByteArray()));
    if (u.equals(BigInteger.ZERO)) {
        throw new SecurityException("Hash of A and B cannot be zero");
    }

    // x = H(salt | H(poolName | userId | ":" | password))
    messageDigest.reset();
    messageDigest.update(this.userPoolID.split("_", 2)[1].getBytes(StringUtils.UTF8));
    messageDigest.update(userId.getBytes(StringUtils.UTF8));
    messageDigest.update(":".getBytes(StringUtils.UTF8));
    byte[] userIdHash = messageDigest.digest(userPassword.getBytes(StringUtils.UTF8));

    messageDigest.reset();
    messageDigest.update(salt.toByteArray());
    BigInteger x = new BigInteger(1, messageDigest.digest(userIdHash));
    BigInteger S = (B.subtract(k.multiply(g.modPow(x, N))).modPow(a.add(u.multiply(x)), N)).mod(N);

    Hkdf hkdf;
    try {
        hkdf = Hkdf.getInstance("HmacSHA256");
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(e.getMessage(), e);
    }
    hkdf.init(S.toByteArray(), u.toByteArray());
    byte[] key = hkdf.deriveKey(DERIVED_KEY_INFO, DERIVED_KEY_SIZE);
    return key;
}
 
Example 13
private void flushBatch(final String streamName, final LambdaLogger logger) {
    final PutRecordsResult result = this.kinesisClient.putRecords(new PutRecordsRequest()
            .withStreamName(streamName)
            .withRecords(this.kinesisBatch));

    result.getRecords().forEach(r -> {
        if (!(StringUtils.hasValue(r.getErrorCode()))) {
            String successMessage = "Successfully processed record with sequence number: " + r.getSequenceNumber()
                    + ", shard id: " + r.getShardId();
            logger.log(successMessage);
        } else {
            this.documentAddedCount--;

            String errorMessage = "Did not process record with sequence number: " + r.getSequenceNumber()
                    + ", error code: " + r.getErrorCode()
                    + ", error message: " + r.getErrorMessage();
            logger.log(errorMessage);
            this.isError = true;
        }
    });


    // You may also implement a retry logic only for failed records (e.g. Create a list for failed records,
    // add error records to that list and finally retry all failed records until a max retry count is reached.)
    /*
    if (result.getFailedRecordCount() != null && result.getFailedRecordCount() > 0) {
        result.getRecords().forEach(r -> {
            if ((r != null) && (StringUtils.hasValue(r.getErrorCode()))) {
                // add this record to the retry list.
            }
        });
    }
    */
}
 
Example 14
Source Project: pacbot   Source File: CommonUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the date from string.
 *
 * @param dateInString the date in string
 * @param format the format
 * @return the date from string
 * @throws ParseException the parse exception
 */
public static Date getDateFromString(final String dateInString, final String format)
        throws java.text.ParseException {
    String dateDormatter = "MM/dd/yyyy";
    if (!StringUtils.isNullOrEmpty(format)) {
        dateDormatter = format;
    }
    SimpleDateFormat formatter = new SimpleDateFormat(dateDormatter);
    return formatter.parse(dateInString);
}
 
Example 15
Source Project: pacbot   Source File: CommonUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Date format.
 *
 * @param dateInString the date in string
 * @param formatFrom the format from
 * @param formatTo the format to
 * @return the date
 * @throws ParseException the parse exception
 */
public static Date dateFormat(final String dateInString, String formatFrom, String formatTo)
        throws java.text.ParseException {
    String dateDormatter = "MM/dd/yyyy";
    if (StringUtils.isNullOrEmpty(formatFrom)) {
        formatFrom = dateDormatter;
    }
    if (StringUtils.isNullOrEmpty(formatTo)) {
        formatTo = dateDormatter;
    }
    DateFormat dateFromFormater = new SimpleDateFormat(formatFrom);
    DateFormat dateToFormater = new SimpleDateFormat(formatTo);
    return dateToFormater.parse(dateToFormater.format(dateFromFormater.parse(dateInString)));
}
 
Example 16
Source Project: pacbot   Source File: MailUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
* Formate common fix body.
*
* @param silentautoFixTrans the silentauto fix trans
* @param ruleParam the rule param
* @param resourceOwner the resource owner
* @return the string
*/
public static String formateCommonFixBody(List<AutoFixTransaction> silentautoFixTrans,Map<String, String> ruleParam,ResourceOwner resourceOwner) {
    TemplateEngine templateEngine = new TemplateEngine();
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setTemplateMode("HTML");
    templateResolver.setSuffix(".html");
    templateEngine.setTemplateResolver(templateResolver);
    
    List<String> columnsList = Arrays.asList(CommonUtils.getPropValue(PacmanSdkConstants.PACMAN_MAIL_TEMPLATE_COLUMNS
            + ruleParam.get(PacmanSdkConstants.RULE_ID)).split("\\s*,\\s*"));
   
    Context context = new Context(); 
  
    context.setVariable("columns", columnsList);
    context.setVariable("resources", silentautoFixTrans);
    String policyUrl = getPolicyKnowledgeBasePathURL(ruleParam);
    String name =CommonUtils.getPropValue(PacmanSdkConstants.SEND_EMAIL_SILENT_FIX_ADMIN
            + ruleParam.get(PacmanSdkConstants.RULE_ID));
    
    if(StringUtils.isNullOrEmpty(name)){
  	 name = resourceOwner.getName(); 
    }
    String postFixMessage = CommonUtils.getPropValue(PacmanSdkConstants.EMAIL_FIX_MESSAGE_PREFIX
            + ruleParam.get(PacmanSdkConstants.RULE_ID));
    context.setVariable("AUTOFIX_POST_FIX_MESSAGE", postFixMessage);
    context.setVariable("POLICY_URL", policyUrl);
    context.setVariable("NAME", "Hello "+name);
    context.setVariable("RESOURCE_TYPE", " Resource Type : "+ruleParam.get(PacmanSdkConstants.TARGET_TYPE));
    context.setVariable("AUTO_FIX_APPLIED", "Total AutoFixs Applied : "+silentautoFixTrans.size());
    StringWriter writer = new StringWriter();
    
  if(CommonUtils.getPropValue("pacman.auto.fix.common.email.notifications."
            + ruleParam.get(PacmanSdkConstants.RULE_ID)).equals("commonTemplate")){
    	templateEngine.process("/template/autofix-user-notification-action-common.html", context, writer);
}else{
    	templateEngine.process("/template/autofix-silent-autodelete-usernotification-info.html", context, writer);
    }
    return writer.toString();
    
}
 
Example 17
Source Project: pacbot   Source File: UnusedSgAutoFix.java    License: Apache License 2.0 5 votes vote down vote up
/** (non-Javadoc)
 * 
 * @see
 * com.tmobile.pacman.commons.autofix.BaseFix#addDetailsToTransactionLog()*/
 
@Override
public AutoFixTransaction addDetailsToTransactionLog(Map<String, String> annotation) {
	LinkedHashMap<String,String> transactionParams = new LinkedHashMap();
	if (!StringUtils.isNullOrEmpty(annotation.get("_resourceid"))) {
		transactionParams.put("resourceId", annotation.get("_resourceid"));
	} else {
		transactionParams.put("resourceId", "No Data");
	}
	if (!StringUtils.isNullOrEmpty(annotation.get("accountid"))) {
		transactionParams.put("accountId", annotation.get("accountid"));
	} else {
		transactionParams.put("accountId", "No Data");
	}
	if (!StringUtils.isNullOrEmpty(annotation.get("region"))) {
		transactionParams.put("region", annotation.get("region"));
	} else {
		transactionParams.put("region", "No Data");
	}
	if (!StringUtils.isNullOrEmpty(annotation.get("groupname"))) {
	transactionParams.put("groupName", annotation.get("groupname"));
	}else{
		transactionParams.put("groupName", "No Data");
	}
	return new AutoFixTransaction(null,transactionParams);
}
 
Example 18
Source Project: pacbot   Source File: UnusedElasticIPAutofix.java    License: Apache License 2.0 5 votes vote down vote up
@Override
  public AutoFixTransaction addDetailsToTransactionLog(Map<String, String> annotation) {
  	LinkedHashMap<String,String> transactionParams = new LinkedHashMap();
  	if(!StringUtils.isNullOrEmpty(annotation.get("_resourceid"))){
transactionParams.put("resourceId", annotation.get("_resourceid"));
  	}else{
  		transactionParams.put("resourceId","No Data");	
  	}
  	if(!StringUtils.isNullOrEmpty(annotation.get("accountid"))){
transactionParams.put("accountId", annotation.get("accountid"));
  	}else{
  		transactionParams.put("accountId", "No Data");
  	}
  	
  	if(!StringUtils.isNullOrEmpty(annotation.get("region"))){
transactionParams.put("region", annotation.get("region"));
  	}else{
  		transactionParams.put("region", "No Data");	
  	}
  	
  	if(!StringUtils.isNullOrEmpty(annotation.get("allocationId"))){
transactionParams.put("allocationId", annotation.get(PacmanSdkConstants.ALLOCATION_ID));
  	}else{
  		transactionParams.put("allocationId", "No Data");	
  	}
return new AutoFixTransaction(null,transactionParams);
  }
 
Example 19
Source Project: pacbot   Source File: RecommendationCollector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Upload recommendations with resource ids.
 *
 * @param recommendationsWithResourceId the recommendations with resource id
 * @param parentInfo the parent info
 * @param errors the errors
 */
private void uploadRecommendationsWithResourceIds(List<Map<String,Object>> recommendationsWithResourceId, Map<String, String> parentInfo, List<String> errors) {
	
	LOGGER.info("Started Uploading for recommendations with resource id {} ",recommendationsWithResourceId.size());
	String createTemplate = "{ \"index\" : { \"_index\" : \"%s\", \"_type\" : \"%s\", \"_id\" : \"%s\", \"_parent\" : \"%s\" } }%n";
	StringBuilder bulkRequest = new StringBuilder();
	int i=0;
	for(Map<String,Object> recommendationObj : recommendationsWithResourceId) {
		String type = recommendationObj.get("type").toString();
		String parentInfoId = recommendationObj.get("_resourceid")+"_"+recommendationObj.get(Constants.ACCOUNTID);
		StringBuilder doc = new StringBuilder(ESManager.createESDoc(recommendationObj));
		if (doc != null) {
			if(!StringUtils.isNullOrEmpty(parentInfo.get(parentInfoId))) {
				ESManager.createType("aws_" + type, Constants.RECOMMENDATION, type);
                bulkRequest.append(String.format(createTemplate,"aws_"+type,Constants.RECOMMENDATION,parentInfo.get(parentInfoId)+"_"+recommendationObj.get(Constants.RECOMMENDATION_ID)+"_"+Math.random(),parentInfo.get(parentInfoId)));
                bulkRequest.append(doc + "\n");
			}
        }
		i++;
		if (i % 100 == 0 || bulkRequest.toString().getBytes().length / (1024 * 1024) > 5) {
			if (bulkRequest.length() > 0) {
 			LOGGER.info("Uploading {}", i);
             ESManager.bulkUpload(errors,bulkRequest.toString());
             bulkRequest = new StringBuilder();
			}
        }
	}
	if (bulkRequest.length() > 0) {
		LOGGER.info("Uploading {}", i);
        ESManager.bulkUpload(errors,bulkRequest.toString());
    }
	LOGGER.info("Completed Uploading for recommendations with resource id");
}
 
Example 20
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:mysql://" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += "/" + dbname;
    }
    return url;
}
 
Example 21
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:oracle:thin:@//" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += "/" + dbname;
    }
    return url;
}
 
Example 22
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:sqlserver://" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += ";databaseName=" + dbname + ";";
    }
    return url;
}
 
Example 23
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:postgresql://" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += "/" + dbname;
    }
    return url;
}
 
Example 24
@Override
public String constructUrlFromEndpointPortDatabase(String endpoint, String port, String dbname) {
    String url = "jdbc:mariadb://" + endpoint;
    if (!StringUtils.isNullOrEmpty(port)) {
        url += ":" + port;
    }
    if (!StringUtils.isNullOrEmpty(dbname)) {
        url += "/" + dbname;
    }
    return url;
}
 
Example 25
Source Project: bazel-buildfarm   Source File: AwsMetricsPublisher.java    License: Apache License 2.0 5 votes vote down vote up
public AwsMetricsPublisher(MetricsConfig metricsConfig) {
  super(metricsConfig.getClusterId());
  snsTopicOperations = metricsConfig.getAwsMetricsConfig().getOperationsMetricsTopic();
  awsAccessKeyId = metricsConfig.getAwsMetricsConfig().getAwsAccessKeyId();
  awsSecretKey = metricsConfig.getAwsMetricsConfig().getAwsSecretKey();
  region = metricsConfig.getAwsMetricsConfig().getRegion();
  snsClientMaxConnections = metricsConfig.getAwsMetricsConfig().getSnsClientMaxConnections();
  if (!StringUtils.isNullOrEmpty(snsTopicOperations)
      && snsClientMaxConnections > 0
      && !StringUtils.isNullOrEmpty(awsAccessKeyId)
      && !StringUtils.isNullOrEmpty(awsSecretKey)
      && !StringUtils.isNullOrEmpty(region)) {
    snsClient = initSnsClient();
  }
}
 
Example 26
Source Project: alexa-meets-polly   Source File: AbstractTranslator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final Optional<String> getTargetLangCodeIfSupported(final String language) {
    return Optional.ofNullable(language)
            // map language to target-language-code
            .map(l -> this.yamlReader.getRandomUtterance(l.toLowerCase().replace(" ", "_")).orElse(""))
            // if source and target language are equal target language is not supported
            .filter(c -> !StringUtils.isNullOrEmpty(c) && !c.equalsIgnoreCase(sourceLanguageCode));
}
 
Example 27
Source Project: alexa-meets-polly   Source File: AbstractTranslator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final Optional<String> translate(final String term, final String language) {
    return getTargetLangCodeIfSupported(language)
            // return text as is or delegate translation to child in case source and target language differ
            .map(targetLanguageCode -> targetLanguageCode.equalsIgnoreCase(sourceLanguageCode) ? term : doTranslate(term, targetLanguageCode))
            // translation must be not null or empty
            .filter(translation -> !StringUtils.isNullOrEmpty(translation));
}
 
Example 28
Source Project: pipeline-aws-plugin   Source File: WithAWSStep.java    License: Apache License 2.0 5 votes vote down vote up
private void withCredentials(@Nonnull Run<?, ?> run, @Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getCredentials())) {
		StandardUsernamePasswordCredentials usernamePasswordCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				StandardUsernamePasswordCredentials.class, run, Collections.emptyList());

		AmazonWebServicesCredentials amazonWebServicesCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				AmazonWebServicesCredentials.class, run, Collections.emptyList());
		if (usernamePasswordCredentials != null) {
			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, usernamePasswordCredentials.getUsername());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, usernamePasswordCredentials.getPassword().getPlainText());
		} else if (amazonWebServicesCredentials != null) {
			AWSCredentials awsCredentials;

			if (StringUtils.isNullOrEmpty(this.step.getIamMfaToken())) {
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials");
				awsCredentials = amazonWebServicesCredentials.getCredentials();
			} else {
				// Since the getCredentials does its own roleAssumption, this is all it takes to get credentials
				// with this token.
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials utilizing MFA Token");
				awsCredentials = amazonWebServicesCredentials.getCredentials(this.step.getIamMfaToken());
				BasicSessionCredentials basicSessionCredentials = (BasicSessionCredentials) awsCredentials;
				localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, basicSessionCredentials.getSessionToken());
			}

			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, awsCredentials.getAWSAccessKeyId());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, awsCredentials.getAWSSecretKey());
		} else {
			throw new RuntimeException("Cannot find a Username with password credential with the ID " + this.step.getCredentials());
		}
	} else if (!StringUtils.isNullOrEmpty(this.step.getSamlAssertion())) {
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, "access_key_not_used_will_pass_through_SAML_assertion");
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, "secret_access_key_not_used_will_pass_through_SAML_assertion");
	}
	this.envVars.overrideAll(localEnv);
}
 
Example 29
Source Project: pipeline-aws-plugin   Source File: WithAWSStep.java    License: Apache License 2.0 5 votes vote down vote up
private void withRegion(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getRegion())) {
		this.getContext().get(TaskListener.class).getLogger().format("Setting AWS region %s %n ", this.step.getRegion());
		localEnv.override(AWSClientFactory.AWS_DEFAULT_REGION, this.step.getRegion());
		localEnv.override(AWSClientFactory.AWS_REGION, this.step.getRegion());
		this.envVars.overrideAll(localEnv);
	}
}
 
Example 30
Source Project: pipeline-aws-plugin   Source File: WithAWSStep.java    License: Apache License 2.0 5 votes vote down vote up
private void withEndpointUrl(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getEndpointUrl())) {
		this.getContext().get(TaskListener.class).getLogger().format("Setting AWS endpointUrl %s %n ", this.step.getEndpointUrl());
		localEnv.override(AWSClientFactory.AWS_ENDPOINT_URL, this.step.getEndpointUrl());
		this.envVars.overrideAll(localEnv);
	}
}