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; }
protected String getCanonicalizedHeaderString(SignableRequest<?> request) { final List<String> sortedHeaders = new ArrayList<String>(request.getHeaders() .keySet()); Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER); final Map<String, String> requestHeaders = request.getHeaders(); StringBuilder buffer = new StringBuilder(); for (String header : sortedHeaders) { if (shouldExcludeHeaderFromSigning(header)) { continue; } String key = StringUtils.lowerCase(header); String value = requestHeaders.get(header); StringUtils.appendCompactedString(buffer, key); buffer.append(":"); if (value != null) { StringUtils.appendCompactedString(buffer, value); } buffer.append("\n"); } return buffer.toString(); }
protected String getSignedHeadersString(SignableRequest<?> request) { final List<String> sortedHeaders = new ArrayList<String>(request .getHeaders().keySet()); Collections.sort(sortedHeaders, String.CASE_INSENSITIVE_ORDER); StringBuilder buffer = new StringBuilder(); for (String header : sortedHeaders) { if (shouldExcludeHeaderFromSigning(header)) { continue; } if (buffer.length() > 0) buffer.append(";"); buffer.append(StringUtils.lowerCase(header)); } return buffer.toString(); }
@Override public PutObjectResult putObject(String bucketName, String key, String content) throws AmazonServiceException, SdkClientException { rejectNull(bucketName, "Bucket name must be provided"); rejectNull(key, "Object key must be provided"); rejectNull(content, "String content must be provided"); byte[] contentBytes = content.getBytes(StringUtils.UTF8); InputStream is = new ByteArrayInputStream(contentBytes); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("text/plain"); metadata.setContentLength(contentBytes.length); return putObject(new PutObjectRequest(bucketName, key, is, metadata)); }
@Override public AmazonWebServiceResponse<HeadBucketResult> handle(HttpResponse response) throws Exception { final AmazonWebServiceResponse<HeadBucketResult> awsResponse = new AmazonWebServiceResponse<HeadBucketResult>(); final HeadBucketResult result = new HeadBucketResult(); result.setBucketRegion(response.getHeaders().get(Headers.S3_BUCKET_REGION)); if (!StringUtils.isNullOrEmpty(response.getHeaders().get(Headers.IBM_SSE_KP_ENABLED))){ result.setIBMSSEKPEnabled(Boolean.parseBoolean(response.getHeaders().get(Headers.IBM_SSE_KP_ENABLED))); } if (!StringUtils.isNullOrEmpty(response.getHeaders().get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN))){ result.setIBMSSEKPCrk(response.getHeaders().get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN)); } awsResponse.setResult(result); return awsResponse; }
private static String from(InputStream is) throws IOException { if (is == null) return ""; StringBuilder sb = new StringBuilder(); try { BufferedReader reader = new BufferedReader( new InputStreamReader(is, StringUtils.UTF8)); String line; while ((line = reader.readLine()) != null) { sb.append(line); } } finally { is.close(); } return sb.toString(); }
/** * Converts the contents of an input stream to a String */ private static String convertStreamToString(InputStream inputStream) throws IOException { if (inputStream == null) { return ""; } else { StringBuilder stringBuilder = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StringUtils.UTF8)); while ((line = reader.readLine()) != null) { stringBuilder.append(line); } } finally { inputStream.close(); } return stringBuilder.toString(); } }
/** * @see com.amazonaws.http.HttpResponseHandler#handle(com.amazonaws.http.HttpResponse) */ public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception { AmazonWebServiceResponse<T> awsResponse = parseResponseMetadata(response); responseHeaders = response.getHeaders(); if (responseUnmarshaller != null) { log.trace("Beginning to parse service response XML"); T result = responseUnmarshaller.unmarshall(response.getContent()); log.trace("Done parsing service response XML"); awsResponse.setResult(result); if (result instanceof ObjectListing) { if (!StringUtils.isNullOrEmpty(responseHeaders.get(Headers.IBM_SSE_KP_ENABLED))){ ((ObjectListing) result).setIBMSSEKPEnabled(Boolean.parseBoolean(responseHeaders.get(Headers.IBM_SSE_KP_ENABLED))); } if (!StringUtils.isNullOrEmpty(responseHeaders.get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN))) { ((ObjectListing) result).setIBMSSEKPCrk(responseHeaders.get(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN)); } } } return awsResponse; }
/** * Determines the mimetype of a file by looking up the file's extension in * an internal listing to find the corresponding mime type. If the file has * no extension, or the extension is not available in the listing contained * in this class, the default mimetype <code>application/octet-stream</code> * is returned. * <p> * A file extension is one or more characters that occur after the last * period (.) in the file's name. If a file has no extension, Guesses the * mimetype of file data based on the file's extension. * * @param fileName * The name of the file whose extension may match a known * mimetype. * * @return The file's mimetype based on its extension, or a default value of * <code>application/octet-stream</code> if a mime type value cannot * be found. */ public String getMimetype(String fileName) { int lastPeriodIndex = fileName.lastIndexOf("."); if (lastPeriodIndex > 0 && lastPeriodIndex + 1 < fileName.length()) { String ext = StringUtils.lowerCase(fileName.substring(lastPeriodIndex + 1)); if (extensionToMimetypeMap.keySet().contains(ext)) { String mimetype = (String) extensionToMimetypeMap.get(ext); if (log.isDebugEnabled()) { log.debug("Recognised extension '" + ext + "', mimetype is: '" + mimetype + "'"); } return mimetype; } else { if (log.isDebugEnabled()) { log.debug("Extension '" + ext + "' is unrecognized in mime type listing" + ", using default mime type: '" + MIMETYPE_OCTET_STREAM + "'"); } } } else { if (log.isDebugEnabled()) { log.debug("File name has no extension, mime type cannot be recognised for: " + fileName); } } return MIMETYPE_OCTET_STREAM; }
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(); } }
@Override public AWSCredentials getCredentials() { // if profile is specified, use that final String profile = configuration.get(AWSConstants.PROFILE); if(!StringUtils.isNullOrEmpty(profile)) { return new ProfileCredentialsProvider(profile).getCredentials(); } // then try access key and secret final String accessKeyId = configuration.get(AWSConstants.ACCESS_KEY_ID); final String secretAccessKey = configuration.get(AWSConstants.SECRET_ACCESS_KEY); if(!StringUtils.isNullOrEmpty(accessKeyId) && !StringUtils.isNullOrEmpty(secretAccessKey)) { return new BasicAWSCredentials(accessKeyId, secretAccessKey); } // fall back to default return new DefaultAWSCredentialsProviderChain().getCredentials(); }
@Override public AWSCredentials getCredentials() { String accessKey = null; if (config.hasPath(GobblinAWSConfigurationKeys.SERVICE_ACCESS_KEY)) { accessKey = config.getString(GobblinAWSConfigurationKeys.SERVICE_ACCESS_KEY); } String secretKey = null; if (config.hasPath(GobblinAWSConfigurationKeys.SERVICE_SECRET_KEY)) { secretKey = PasswordManager.getInstance(ConfigUtils.configToState(config)) .readPassword(config.getString(GobblinAWSConfigurationKeys.SERVICE_SECRET_KEY)); } accessKey = StringUtils.trim(accessKey); secretKey = StringUtils.trim(secretKey); if (StringUtils.isNullOrEmpty(accessKey) || StringUtils.isNullOrEmpty(secretKey)) { throw new AmazonClientException(String.format("Unable to load AWS credentials from config (%s and %s)", GobblinAWSConfigurationKeys.SERVICE_ACCESS_KEY, GobblinAWSConfigurationKeys.SERVICE_SECRET_KEY)); } return new BasicAWSCredentials(accessKey, secretKey); }
@Override public boolean mapShortCode(String code, String paramString) throws IOException { if(!enabled) { throw new IllegalStateException("Shortlink feature disabled"); } try { // does object exist? client.getObjectMetadata(bucket, OBJECT_PREFIX + code); } catch (AmazonS3Exception e) { if (e.getStatusCode() != 404) { log.warn(e); return false; } } byte[] paramStringBytes = paramString.getBytes(StringUtils.UTF8); InputStream is = new ByteArrayInputStream(paramStringBytes); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("text/plain"); metadata.setContentLength(paramStringBytes.length); client.putObject(new PutObjectRequest(bucket, OBJECT_PREFIX + code, is, metadata)); return true; }
@Override public void start() { if (RegionUtils.getRegion(region) == null) { addError(format("Region not set or invalid for appender '%s'", getName())); return; } if (StringUtils.isNullOrEmpty(logGroup)) { addError(format("Log group name not set for appender '%s'", getName())); return; } if (StringUtils.isNullOrEmpty(logStream)) { addError(format("Log stream name not set for appender '%s'", getName())); return; } setConverter(new StringPayloadConverter(getCharset(), isBinary())); super.start(); }
/** * Returns the service name of this AWS http client by first looking it up from the SDK internal * configuration, and if not found, derive it from the class name of the immediate subclass of * {@link AmazonWebServiceClient}. No configuration is necessary if the simple class name of the * http client follows the convention of <code>(Amazon|AWS).*(JavaClient|Client)</code>. */ private String computeServiceName() { final String httpClientName = getHttpClientName(); String service = ServiceNameFactory.getServiceName(httpClientName); if (service != null) { return service; // only if it is so explicitly configured } // Otherwise, make use of convention over configuration int j = httpClientName.indexOf("JavaClient"); if (j == -1) { j = httpClientName.indexOf("Client"); if (j == -1) { throw new IllegalStateException( "Unrecognized suffix for the AWS http client class name " + httpClientName); } } int i = httpClientName.indexOf(AMAZON); int len; if (i == -1) { i = httpClientName.indexOf(AWS); if (i == -1) { throw new IllegalStateException( "Unrecognized prefix for the AWS http client class name " + httpClientName); } len = AWS.length(); } else { len = AMAZON.length(); } if (i >= j) { throw new IllegalStateException( "Unrecognized AWS http client class name " + httpClientName); } String serviceName = httpClientName.substring(i + len, j); return StringUtils.lowerCase(serviceName); }
@Override public String getRegion() throws SdkClientException { File configFile = locationProvider.getLocation(); if (configFile != null && configFile.exists()) { BasicProfile profile = loadProfile(configFile); if (profile != null && !StringUtils.isNullOrEmpty(profile.getRegion())) { return profile.getRegion(); } } return null; }
private void parseNonProxyHosts(String nonProxyHosts) { if (!StringUtils.isNullOrEmpty(nonProxyHosts)) { String[] hosts = nonProxyHosts.split("\\|"); hostPatterns = new String[hosts.length]; for (int i = 0; i < hosts.length; ++i) { hostPatterns[i] = hosts[i].toLowerCase().replace("*", ".*?"); } } }
@Override public AmazonServiceException handle(HttpResponse errorResponse) throws Exception { AmazonServiceException ase = createAse(errorResponse); if (ase == null) { throw new SdkClientException("Unable to unmarshall error response from service"); } ase.setHttpHeaders(errorResponse.getHeaders()); if (StringUtils.isNullOrEmpty(ase.getErrorCode())) { ase.setErrorCode(errorResponse.getStatusCode() + " " + errorResponse.getStatusText()); } return ase; }
private AWSCredentialsProvider fromAssumeRole() { if (StringUtils.isNullOrEmpty(profile.getRoleSourceProfile())) { throw new SdkClientException(String.format( "Unable to load credentials from profile [%s]: Source profile name is not specified", profile.getProfileName())); } final BasicProfile sourceProfile = allProfiles .getProfile(this.profile.getRoleSourceProfile()); if (sourceProfile == null) { throw new SdkClientException(String.format( "Unable to load source profile [%s]: Source profile was not found [%s]", profile.getProfileName(), profile.getRoleSourceProfile())); } AWSCredentials sourceCredentials = new ProfileStaticCredentialsProvider(sourceProfile) .getCredentials(); final String roleSessionName = (this.profile.getRoleSessionName() == null) ? "aws-sdk-java-" + System.currentTimeMillis() : this.profile.getRoleSessionName(); RoleInfo roleInfo = new RoleInfo().withRoleArn(this.profile.getRoleArn()) .withRoleSessionName(roleSessionName) .withExternalId(this.profile.getRoleExternalId()) .withLongLivedCredentials(sourceCredentials); return profileCredentialsService.getAssumeRoleCredentialsProvider(roleInfo); }
/** * TODO The order would make more sense as System Property, Environment Variable, Default * Profile name but we have to keep the current order for backwards compatiblity. Consider * changing this in a future major version. */ public final String loadProfileName() { final String profileEnvVarOverride = getEnvProfileName(); if (!StringUtils.isNullOrEmpty(profileEnvVarOverride)) { return profileEnvVarOverride; } else { final String profileSysPropOverride = getSysPropertyProfileName(); if (!StringUtils.isNullOrEmpty(profileSysPropOverride)) { return profileSysPropOverride; } else { return DEFAULT_PROFILE_NAME; } } }
/** * Loads the credential profiles from the given input stream. * * @param is input stream from where the profile details are read. */ private AllProfiles loadProfiles(InputStream is) throws IOException { ProfilesConfigFileLoaderHelper helper = new ProfilesConfigFileLoaderHelper(); Map<String, Map<String, String>> allProfileProperties = helper .parseProfileProperties(new Scanner(is, StringUtils.UTF8.name())); // Convert the loaded property map to credential objects Map<String, BasicProfile> profilesByName = new LinkedHashMap<String, BasicProfile>(); for (Entry<String, Map<String, String>> entry : allProfileProperties.entrySet()) { String profileName = entry.getKey(); Map<String, String> properties = entry.getValue(); if (profileName.startsWith("profile ")) { LOG.warn( "The legacy profile format requires the 'profile ' prefix before the profile name. " + "The latest code does not require such prefix, and will consider it as part of the profile name. " + "Please remove the prefix if you are seeing this warning."); } assertParameterNotEmpty(profileName, "Unable to load properties from profile: Profile name is empty."); profilesByName.put(profileName, new BasicProfile(profileName, properties)); } return new AllProfiles(profilesByName); }
private AWSCredentials fromStaticCredentials() { //IBM bx Credentials loaded if (!StringUtils.isNullOrEmpty(profile.getIBMApiKey())){ return new BasicIBMOAuthCredentials(profile.getIBMApiKey(), profile.getIBMServiceInstanceId()); } if (StringUtils.isNullOrEmpty(profile.getAwsAccessIdKey())) { throw new SdkClientException(String.format( "Unable to load credentials into profile [%s]: AWS Access Key ID is not specified.", profile.getProfileName())); } if (StringUtils.isNullOrEmpty(profile.getAwsSecretAccessKey())) { throw new SdkClientException(String.format( "Unable to load credentials into profile [%s]: AWS Secret Access Key is not specified.", profile.getAwsSecretAccessKey())); } if (profile.getAwsSessionToken() == null) { return new BasicAWSCredentials(profile.getAwsAccessIdKey(), profile.getAwsSecretAccessKey()); } else { if (profile.getAwsSessionToken().isEmpty()) { throw new SdkClientException(String.format( "Unable to load credentials into profile [%s]: AWS Session Token is empty.", profile.getProfileName())); } return new BasicSessionCredentials(profile.getAwsAccessIdKey(), profile.getAwsSecretAccessKey(), profile.getAwsSessionToken()); } }
protected List<String> getHeadersForStringToSign(SignableRequest<?> request) { List<String> headersToSign = new ArrayList<String>(); for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) { String key = entry.getKey(); String lowerCaseKey = StringUtils.lowerCase(key); if (lowerCaseKey.startsWith("x-amz") || lowerCaseKey.equals("host")) { headersToSign.add(key); } } Collections.sort(headersToSign); return headersToSign; }
protected boolean shouldUseHttpsScheme(SignableRequest<?> request) throws SdkClientException { try { String protocol = StringUtils.lowerCase(request.getEndpoint().toURL().getProtocol()); if (protocol.equals("http")) { return false; } else if (protocol.equals("https")) { return true; } else { throw new SdkClientException("Unknown request endpoint protocol " + "encountered while signing request: " + protocol); } } catch (MalformedURLException e) { throw new SdkClientException("Unable to parse request endpoint during signing", e); } }
@Override public AWSCredentials getCredentials() { //Load IBM properties String accessKey = StringUtils.trim(System.getProperty(ACCESS_KEY_SYSTEM_PROPERTY)); String secretKey = StringUtils.trim(System.getProperty(SECRET_KEY_SYSTEM_PROPERTY)); String apiKey = StringUtils.trim(System.getProperty(SDKGlobalConfiguration.IBM_API_KEY_SYSTEM_PROPERTY)); String serviceInstance = StringUtils.trim(System.getProperty(SDKGlobalConfiguration.IBM_SERVICE_INSTANCE_ID_SYSTEM_PROPERTY)); if (!StringUtils.isNullOrEmpty(apiKey) && tokenManager == null) { BasicIBMOAuthCredentials oAuthCreds = new BasicIBMOAuthCredentials(apiKey, serviceInstance); tokenManager = oAuthCreds.getTokenManager(); return oAuthCreds; } else if ((!StringUtils.isNullOrEmpty(apiKey) && tokenManager != null)) { return new BasicIBMOAuthCredentials(tokenManager, serviceInstance); } if (StringUtils.isNullOrEmpty(accessKey) || StringUtils.isNullOrEmpty(secretKey)) { throw new SdkClientException( "Unable to load AWS credentials from Java system " + "properties (" + ACCESS_KEY_SYSTEM_PROPERTY + " and " + SECRET_KEY_SYSTEM_PROPERTY + ")"); } return new BasicAWSCredentials(accessKey, secretKey); }
protected String getCanonicalizedEndpoint(URI endpoint) { String endpointForStringToSign = StringUtils.lowerCase(endpoint.getHost()); /* * Apache HttpClient will omit the port in the Host header for default * port values (i.e. 80 for HTTP and 443 for HTTPS) even if we * explicitly specify it, so we need to be careful that we use the same * value here when we calculate the string to sign and in the Host * header we send in the HTTP request. */ if (SdkHttpUtils.isUsingNonDefaultPort(endpoint)) { endpointForStringToSign += ":" + endpoint.getPort(); } return endpointForStringToSign; }
@Override public ByteBuffer adapt(String source) { if (source == null) { return null; } else { return ByteBuffer.wrap(source.getBytes(StringUtils.UTF8)); } }
@Test public void testClob() throws IOException { IonParser parser = parse("{{\"abc123\"}}"); assertEquals(JsonToken.VALUE_EMBEDDED_OBJECT, parser.nextToken()); assertEquals(ByteBuffer.wrap("abc123".getBytes(StringUtils.UTF8)), parser.getEmbeddedObject()); assertNull(parser.nextToken()); }
/** * Headers are case insensitive so the request id should still be parsed in this test */ @Test public void handle_UnmarshallerReturnsException_WithCaseInsensitiveRequestId() throws Exception { httpResponse.setStatusCode(500); httpResponse.addHeader(StringUtils.upperCase(HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER), "1234"); expectUnmarshallerMatches(); when(unmarshaller.unmarshall((JsonNode) anyObject())) .thenReturn(new CustomException("error")); AmazonServiceException ase = responseHandler.handle(httpResponse); assertEquals("1234", ase.getRequestId()); }
public AmazonWebServiceResponse<String> handle(HttpResponse response) throws Exception { AmazonWebServiceResponse<String> awsResponse = parseResponseMetadata(response); int bytesRead; byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); InputStream content = response.getContent(); while ((bytesRead = content.read(buffer)) > 0) { builder.append(new String(buffer, 0, bytesRead, StringUtils.UTF8)); } awsResponse.setResult(builder.toString()); return awsResponse; }
/** * Reads and stores the mime type setting corresponding to a file extension, by reading * text from an InputStream. If a mime type setting already exists when this method is run, * the mime type value is replaced with the newer one. * * @param is * * @throws IOException */ public void loadAndReplaceMimetypes(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is, StringUtils.UTF8)); String line = null; while ((line = br.readLine()) != null) { line = line.trim(); if (line.startsWith("#") || line.length() == 0) { // Ignore comments and empty lines. } else { StringTokenizer st = new StringTokenizer(line, " \t"); if (st.countTokens() > 1) { String mimetype = st.nextToken(); while (st.hasMoreTokens()) { String extension = st.nextToken(); extensionToMimetypeMap.put(StringUtils.lowerCase(extension), mimetype); if (log.isDebugEnabled()) { log.debug("Setting mime type for extension '" + StringUtils.lowerCase(extension) + "' to '" + mimetype + "'"); } } } else { if (log.isDebugEnabled()) { log.debug("Ignoring mimetype with no associated file extensions: '" + line + "'"); } } } } }
public @NotNull AgentRunnerBuildParametersModel createModel(@NotNull final Map<String, String> runnerParameters) { final String bucketName = StringUtils.trim(runnerParameters.get(PluginConstants.UI_PARAM_BUCKET_NAME)); final String credentialsPublicKey = StringUtils.trim(runnerParameters.get(PluginConstants.UI_PARAM_CREDENTIALS_PUB_KEY)); final String credentialsPrivateKey = StringUtils.trim(runnerParameters.get(PluginConstants.UI_PARAM_CREDENTIALS_PRIVATE_KEY)); final String sourcePaths = runnerParameters.get(PluginConstants.UI_PARAM_CONTENT_PATHS); final boolean needToEmptyBucket = Boolean.valueOf(runnerParameters.get(PluginConstants.UI_PARAM_EMPTY_BUCKET)); final String httpHeaderCacheControl = StringUtil.nullIfEmpty(StringUtils.trim(runnerParameters.get(PluginConstants.UI_PARAM_HTTP_HEADERS_CACHE_CONTROL))); final String httpProxy = StringUtils.trim(runnerParameters.get(PluginConstants.UI_PARAM_HTTP_PROXY)); return new AgentRunnerBuildParametersModel(bucketName, credentialsPublicKey, credentialsPrivateKey, needToEmptyBucket, sourcePaths, httpHeaderCacheControl, httpProxy); }
@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)); }
@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)); }
/** * Generates secret hash. Uses HMAC SHA256. * * @param userId REQUIRED: User ID * @param clientId REQUIRED: Client ID * @param clientSecret REQUIRED: Client secret * @return secret hash as a {@code String}, {@code null } if {@code clinetSecret if null} */ public static String getSecretHash(String userId, String clientId, String clientSecret) { // Arguments userId and clientId have to be not-null. if (userId == null) { throw new CognitoParameterInvalidException("user ID cannot be null"); } if (clientId == null) { throw new CognitoParameterInvalidException("client ID cannot be null"); } // Return null as secret hash if clientSecret is null. if (clientSecret == null) { return null; } SecretKeySpec signingKey = new SecretKeySpec(clientSecret.getBytes(StringUtils.UTF8), HMAC_SHA_256); try { Mac mac = Mac.getInstance(HMAC_SHA_256); mac.init(signingKey); mac.update(userId.getBytes(StringUtils.UTF8)); byte[] rawHmac = mac.doFinal(clientId.getBytes(StringUtils.UTF8)); return new String(Base64.encode(rawHmac)); } catch (Exception e) { throw new CognitoInternalErrorException("errors in HMAC calculation"); } }
public 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 CognitoInternalErrorException("Hash of A and B cannot be zero"); } // x = H(salt | H(poolName | userId | ":" | password)) messageDigest.reset(); messageDigest.update(poolName.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 = null; try { hkdf = Hkdf.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { throw new CognitoInternalErrorException(e.getMessage(), e); } hkdf.init(S.toByteArray(), u.toByteArray()); byte[] key = hkdf.deriveKey(DERIVED_KEY_INFO, DERIVED_KEY_SIZE); return key; }
AlexaClient(final AlexaClientBuilder builder) { this.millisFromCurrentDate = builder.timestamp.getTime() - new Date().getTime(); this.locale = builder.locale; apiEndpoint = apiEndpoints.getOrDefault(builder.apiEndpoint, apiEndpoints.get(NA)); this.application = new Application(builder.applicationId); this.user = User.builder().withUserId(builder.uid).withAccessToken(builder.accessToken).build(); this.device = builder.device; this.debugFlagSessionAttributeName = StringUtils.isNullOrEmpty(builder.debugFlagSessionAttributeName) ? Optional.empty() : Optional.of(builder.debugFlagSessionAttributeName); this.endpoint = builder.endpoint; this.yLaunch = builder.yLaunch; }
void preBuild() { Validate.notNull(endpoint, "Endpoint must not be null."); if (StringUtils.isNullOrEmpty(applicationId)) { applicationId = generateApplicationId(); } if (locale == null) { locale = Locale.US; } if (StringUtils.isNullOrEmpty(uid)) { uid = generateUserId(); } if (timestamp == null) { timestamp = new Date(); } if (device == null) { SupportedInterfaces supportedInterfaces = null; if (!interfaces.isEmpty()) { final SupportedInterfaces.Builder supportedInterfacesBuilder = SupportedInterfaces.builder(); interfaces.forEach(supportedInterfacesBuilder::addSupportedInterface); supportedInterfaces = supportedInterfacesBuilder.build(); } else { supportedInterfaces = SupportedInterfaces.builder().build(); } device = Device.builder().withSupportedInterfaces(supportedInterfaces).withDeviceId(deviceId).build(); } }
public static AWSCredentialsProvider createAwsCredentialsProvider(final String accessKey, final String secretKey) { if (!StringUtils.isNullOrEmpty(accessKey) && StringUtils.isNullOrEmpty(secretKey)) { return new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return new BasicAWSCredentials(accessKey, secretKey); } @Override public void refresh() { } }; } return new DefaultAWSCredentialsProviderChain(); }
/** * Test method for {@link com.github.abhinavmishra14.aws.s3.service.AwsS3IamService#generateObjectUrlAsString(java.lang.String,java.lang.String)}. * * @throws IOException Signals that an I/O exception has occurred. */ @Test public void testGenerateObjectUrlAsString() throws IOException { String url = awsS3IamService.generateObjectUrlAsString(AWS_S3_BUCKET, AWSUtilConstants.SAMPLE_FILE_NAME); assertEquals(true,!StringUtils.isNullOrEmpty(url)); assertEquals(true,url.contains(AWS_S3_BUCKET+".s3.amazonaws.com")); assertEquals(true,url.contains(AWSUtilConstants.SAMPLE_FILE_NAME)); }