@Override public void handle(Context ctx) throws Exception { String token = null; List<Voice> voices = new ArrayList<>(); while (true) { DescribeVoicesResult result; if (token == null) { result = polly.describeVoices(new DescribeVoicesRequest()); } else { result = polly.describeVoices(new DescribeVoicesRequest().withNextToken(token)); } voices.addAll(result.getVoices()); if (result.getNextToken() != null) { token = result.getNextToken(); } else { ctx.render(Jackson.toJsonString(voices)); break; } } }
private void handleErrorResponse(InputStream errorStream, int statusCode, String responseMessage) throws IOException { String errorCode = null; // Parse the error stream returned from the service. if(errorStream != null) { String errorResponse = IOUtils.toString(errorStream); try { JsonNode node = Jackson.jsonNodeOf(errorResponse); JsonNode code = node.get("code"); JsonNode message = node.get("message"); if (code != null && message != null) { errorCode = code.asText(); responseMessage = message.asText(); } } catch (Exception exception) { LOG.debug("Unable to parse error stream"); } } AmazonServiceException ase = new AmazonServiceException(responseMessage); ase.setStatusCode(statusCode); ase.setErrorCode(errorCode); throw ase; }
/** * Returns the json string in the latest format. */ private String toJsonString() { Map<String, String> map = new HashMap<String, String>(); byte[] encryptedCEK = getEncryptedCEK(); map.put(Headers.CRYPTO_KEY_V2, Base64.encodeAsString(encryptedCEK)); byte[] iv = cipherLite.getIV(); map.put(Headers.CRYPTO_IV, Base64.encodeAsString(iv)); map.put(Headers.MATERIALS_DESCRIPTION, kekMaterialDescAsJson()); // The CRYPTO_CEK_ALGORITHM, CRYPTO_TAG_LENGTH and // CRYPTO_KEYWRAP_ALGORITHM were not available in the Encryption Only // (EO) implementation ContentCryptoScheme scheme = getContentCryptoScheme(); map.put(Headers.CRYPTO_CEK_ALGORITHM, scheme.getCipherAlgorithm()); int tagLen = scheme.getTagLengthInBits(); if (tagLen > 0) map.put(Headers.CRYPTO_TAG_LENGTH, String.valueOf(tagLen)); String keyWrapAlgo = getKeyWrappingAlgorithm(); if (keyWrapAlgo != null) map.put(Headers.CRYPTO_KEYWRAP_ALGORITHM, keyWrapAlgo); return Jackson.toJsonString(map); }
public TripEvent(String payload) { super(payload); JsonNode json = Jackson.fromJsonString(payload, JsonNode.class); this.tripId = json.get("trip_id").asLong(); this.timestamp = new DateTime(json.get("dropoff_datetime").asText()).getMillis(); }
/** * Converts the specified JSON string to an AWS policy object. * * For more information see, @see * http://docs.aws.amazon.com/AWSSdkDocsJava/latest * /DeveloperGuide/java-dg-access-control.html * * @param jsonString * the specified JSON string representation of this AWS access * control policy. * * @return An AWS policy object. * * @throws IllegalArgumentException * If the specified JSON string is null or invalid and cannot be * converted to an AWS policy object. */ public Policy createPolicyFromJsonString(String jsonString) { if (jsonString == null) { throw new IllegalArgumentException("JSON string cannot be null"); } JsonNode policyNode; JsonNode idNode; JsonNode statementNodes; Policy policy = new Policy(); List<Statement> statements = new LinkedList<Statement>(); try { policyNode = Jackson.jsonNodeOf(jsonString); idNode = policyNode.get(JsonDocumentFields.POLICY_ID); if (isNotNull(idNode)) { policy.setId(idNode.asText()); } statementNodes = policyNode.get(JsonDocumentFields.STATEMENT); if (isNotNull(statementNodes)) { for (JsonNode node : statementNodes) { statements.add(statementOf(node)); } } } catch (Exception e) { String message = "Unable to generate policy object fron JSON string " + e.getMessage(); throw new IllegalArgumentException(message, e); } policy.setStatements(statements); return policy; }
/** * Constructs a new instance of JSONPolicyWriter. */ public JsonPolicyWriter() { writer = new StringWriter(); try { generator = Jackson.jsonGeneratorOf(writer); } catch (IOException ioe) { throw new SdkClientException( "Unable to instantiate JsonGenerator.", ioe); } }
@Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getHttpMethod()).append(" "); builder.append(getEndpoint()).append(" "); String resourcePath = getResourcePath(); if (resourcePath == null) { builder.append("/"); } else { if (!resourcePath.startsWith("/")) { builder.append("/"); } builder.append(resourcePath); } builder.append(" "); if (!getParameters().isEmpty()) { builder.append("Parameters: (") .append(Jackson.toJsonString(parameters)); } if (!getHeaders().isEmpty()) { builder.append("Headers: ("); for (String key : getHeaders().keySet()) { String value = getHeaders().get(key); builder.append(key).append(": ").append(value).append(", "); } builder.append(") "); } return builder.toString(); }
static InstanceInfo doGetInstanceInfo(String json) { if (null != json) { try { InstanceInfo instanceInfo = Jackson.fromJsonString(json, InstanceInfo.class); return instanceInfo; } catch (Exception e) { log.warn("Unable to parse dynamic EC2 instance info (" + json + ") : " + e.getMessage(), e); } } return null; }
/** * Policies with multiple conditions that use the same comparison type must * be merged together in the JSON format, otherwise there will be two keys * with the same name and one will override the other. */ @Test public void testMultipleConditionKeysForConditionType() throws Exception { Policy policy = new Policy(); policy.withStatements(new Statement(Effect.Allow) .withResources( new Resource( "arn:aws:sqs:us-east-1:987654321000:MyQueue")) .withPrincipals(Principal.AllUsers) .withActions(new TestAction("foo")) .withConditions( new StringCondition(StringComparisonType.StringNotLike, "key1", "foo"), new StringCondition(StringComparisonType.StringNotLike, "key1", "bar"))); JsonNode jsonPolicy = Jackson.jsonNodeOf(policy.toJson()); JsonNode statementArray = jsonPolicy.get("Statement"); assertEquals(statementArray.size(),1); JsonNode conditions = statementArray.get(0).get("Condition"); assertEquals(conditions.size(),1); JsonNode stringLikeCondition = conditions.get(StringComparisonType.StringNotLike.toString()); assertTrue(stringLikeCondition.has("key1")); assertFalse(stringLikeCondition.has("key2")); assertValidStatementIds(policy); }
/** * Tests serializing a more complex policy object with multiple statements. */ @Test public void testMultipleStatements() throws Exception { Policy policy = new Policy("S3PolicyId1"); policy.withStatements( new Statement(Effect.Allow) .withPrincipals(Principal.AllUsers) .withActions(new TestAction("action1")) .withResources(new Resource("resource")) .withConditions( new IpAddressCondition("192.168.143.0/24"), new IpAddressCondition( IpAddressComparisonType.NotIpAddress, "192.168.143.188/32")), new Statement(Effect.Deny).withPrincipals(Principal.AllUsers) .withActions(new TestAction("action2")) .withResources(new Resource("resource")) .withConditions(new IpAddressCondition("10.1.2.0/24"))); JsonNode jsonPolicy = Jackson.jsonNodeOf(policy.toJson()); assertTrue(jsonPolicy.has("Id")); JsonNode statementArray = jsonPolicy.get("Statement"); assertEquals(statementArray.size(),2); assertValidStatementIds(policy); JsonNode statement; for (int i = 0; i < statementArray.size(); i++) { statement = statementArray.get(i); assertTrue(statement.has("Sid")); assertTrue(statement.has("Effect")); assertTrue(statement.has("Principal")); assertTrue(statement.has("Action")); assertTrue(statement.has("Resource")); assertTrue(statement.has("Condition")); } }
@SuppressWarnings("unchecked") @Test public void test() throws Exception { InternalConfigJsonHelper b = new InternalConfigJsonHelper(); b.setDefaultSigner(new SignerConfigJsonHelper("AWS4SignerType")); b.setServiceSigners( new JsonIndex<SignerConfigJsonHelper, SignerConfig>("cloudfront", new SignerConfigJsonHelper("CloudFrontSignerType")), new JsonIndex<SignerConfigJsonHelper, SignerConfig>("ec2", new SignerConfigJsonHelper("QueryStringSignerType")), new JsonIndex<SignerConfigJsonHelper, SignerConfig>("s3", new SignerConfigJsonHelper("S3SignerType")) ); b.setRegionSigners( new JsonIndex<SignerConfigJsonHelper, SignerConfig>("cn-north-1", new SignerConfigJsonHelper("AWS4SignerType"))); b.setServiceRegionSigners( new JsonIndex<SignerConfigJsonHelper, SignerConfig>("ec2/cn-north-1", new SignerConfigJsonHelper("AWS4SignerType"))); b.setServiceRegionSigners( new JsonIndex<SignerConfigJsonHelper, SignerConfig>("cloudfront/cn-north-1", new SignerConfigJsonHelper("AWS4SignerType"))); b.setHttpClients( new JsonIndex<HttpClientConfigJsonHelper, HttpClientConfig>( "AmazonMobiusClient", new HttpClientConfigJsonHelper("mobius-transform", "mobius-transform-endpoint")), new JsonIndex<HttpClientConfigJsonHelper, HttpClientConfig>( "AmazonAffineJavaClient", new HttpClientConfigJsonHelper("affine-transform", "affine-transform-endpoint"))); String json = Jackson.toJsonPrettyString(b); p(json); InternalConfigJsonHelper b2 = Jackson.getObjectMapper().readValue(json, InternalConfigJsonHelper.class); String json2 = Jackson.toJsonPrettyString(b2); assertEquals(json, json2); }
@Test public void test() throws Exception { p(Jackson.toJsonPrettyString(new SignerConfig("AWS3SignerType"))); String json = Jackson.toJsonPrettyString(new SignerConfig("AWS3SignerType")); SignerConfig copy = Jackson.getObjectMapper().readValue(json, SignerConfigJsonHelper.class).build(); String json2 = Jackson.toJsonPrettyString(copy); assertEquals(json, json2); }
private String toJsonStringEO() { Map<String, String> map = new HashMap<String, String>(); byte[] encryptedCEK = getEncryptedCEK(); map.put(Headers.CRYPTO_KEY, Base64.encodeAsString(encryptedCEK)); byte[] iv = cipherLite.getIV(); map.put(Headers.CRYPTO_IV, Base64.encodeAsString(iv)); map.put(Headers.MATERIALS_DESCRIPTION, kekMaterialDescAsJson()); return Jackson.toJsonString(map); }
/** * Returns the key-encrypting-key material description as a non-null json * string; */ private String kekMaterialDescAsJson() { Map<String, String> kekMaterialDesc = getKEKMaterialsDescription(); if (kekMaterialDesc == null) kekMaterialDesc = Collections.emptyMap(); return Jackson.toJsonString(kekMaterialDesc); }
private ContentCryptoMaterial ccmFromJson(String json) { @SuppressWarnings("unchecked") Map<String, String> instruction = Collections.unmodifiableMap( Jackson.fromJsonString(json, Map.class)); return ContentCryptoMaterial.fromInstructionFile( instruction, kekMaterialsProvider, cryptoConfig.getCryptoProvider(), false, // existing CEK not necessarily key-wrapped kms ); }
private S3Object decipherWithInstructionFile(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved, S3ObjectWrapper instructionFile) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } String json = instructionFile.toJsonString(); @SuppressWarnings("unchecked") Map<String, String> matdesc = Collections.unmodifiableMap(Jackson.fromJsonString(json, Map.class)); ContentCryptoMaterial cekMaterial = ContentCryptoMaterial.fromInstructionFile( matdesc, kekMaterialsProvider, cryptoConfig.getCryptoProvider(), cryptoRange, // range is sometimes necessary to compute the adjusted IV extraMatDesc, keyWrapExpected, kms ); securityCheck(cekMaterial, retrieved); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, matdesc); return adjusted.getS3Object(); }
private String extractInstanceType(String jobFlowJsonString, String targetInstanceRole) { JsonNode jobFlowJson = Jackson.jsonNodeOf(jobFlowJsonString); JsonNode instanceGroups = jobFlowJson.get("instanceGroups"); for (int i = 0; i < instanceGroups.size(); i++) { JsonNode instanceGroup = instanceGroups.get(i); String instanceRole = instanceGroup.get("instanceRole").asText(); if (targetInstanceRole.equalsIgnoreCase(instanceRole)) { String instanceType = instanceGroup.get("instanceType").asText(); log.info(instanceRole + " instance type: " + instanceType); return instanceType; } } return null; }
public static final String proxyIntegration(int statusCode, String[] headers, String body) { ObjectMapper mapper = Jackson.getObjectMapper(); ObjectNode json = mapper.createObjectNode(); json.put("statusCode", statusCode); ArrayNode array = mapper.createArrayNode(); Arrays.stream(headers).forEach(header -> array.add(header)); json.put("headers", array); json.put("body", body); return json.toString(); }
public String toJsonString() { try { return Jackson.getObjectMapper().writeValueAsString(this); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }
@Override public String toString() { return Jackson.toJsonString(this); }
/** * Returns the serialized representation of the paused transfer state. */ public final String serialize() { return Jackson.toJsonString(this); }
@Override public String toString() { return Jackson.toJsonString(this.getConfigurations()); }
/** * Returns the corresponding kek material description from the given json; * or null if the input is null. */ @SuppressWarnings("unchecked") private static Map<String, String> matdescFromJson(String json) { Map<String, String> map = Jackson.fromJsonString(json, Map.class); return map == null ? null : Collections.unmodifiableMap(map); }
/** * @return a JSON representation of this object */ public String toJson() { return Jackson.toJsonString(this); }
@Deprecated @Override public String toString() { return Jackson.toJsonString(this); }
/** * Executes a lambda function and returns the result of the execution. */ @Override public cfData execute( cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException { AmazonKey amazonKey = getAmazonKey( _session, argStruct ); // Arguments to extract String payload = getNamedStringParam( argStruct, "payload", null ); String functionName = getNamedStringParam( argStruct, "function", null ); String qualifier = getNamedStringParam( argStruct, "qualifier", null ); try { // Construct the Lambda Client InvokeRequest invokeRequest = new InvokeRequest(); invokeRequest.setInvocationType( InvocationType.RequestResponse ); invokeRequest.setLogType( LogType.Tail ); invokeRequest.setFunctionName( functionName ); invokeRequest.setPayload( payload ); if ( qualifier != null ) { invokeRequest.setQualifier( qualifier ); } // Lambda client must be created with credentials BasicAWSCredentials awsCreds = new BasicAWSCredentials( amazonKey.getKey(), amazonKey.getSecret() ); AWSLambda awsLambda = AWSLambdaClientBuilder.standard() .withRegion( amazonKey.getAmazonRegion().toAWSRegion().getName() ) .withCredentials( new AWSStaticCredentialsProvider( awsCreds ) ).build(); // Execute and process the results InvokeResult result = awsLambda.invoke( invokeRequest ); // Convert the returned result ByteBuffer resultPayload = result.getPayload(); String resultJson = new String( resultPayload.array(), "UTF-8" ); Map<String, Object> resultMap = Jackson.fromJsonString( resultJson, Map.class ); return tagUtils.convertToCfData( resultMap ); } catch ( Exception e ) { throwException( _session, "AmazonLambdaExecute: " + e.getMessage() ); return cfBooleanData.FALSE; } }
/** * Writes the serialized representation of the paused transfer state to the * given <code>OutputStream</code>. Caller of this method should explicitly * close the <code>OutputStream</code>. */ public final void serialize(OutputStream out) throws IOException { out.write(Jackson.toJsonString(this).getBytes(UTF8)); out.flush(); }
/** * <p> * Parse the JSON string into a S3EventNotification object. * </p> * <p> * The function will try its best to parse input JSON string as best as it can. * It will not fail even if the JSON string contains unknown properties. * The function will throw SdkClientException if the input JSON string is * not valid JSON. * </p> * @param json * JSON string to parse. Typically this is the body of your SQS * notification message body. * * @return The resulting S3EventNotification object. */ public static S3EventNotification parseJson(String json) { return Jackson.fromJsonString(json, S3EventNotification.class); }