Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   *
   * Licensed under the Apache License, Version 2.0 (the "License").
   * You may not use this file except in compliance with the License.
   * A copy of the License is located at
   *
   *  http://aws.amazon.com/apache2.0
   *
  * or in the "license" file accompanying this file. This file is distributed
  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  * express or implied. See the License for the specific language governing
  * permissions and limitations under the License.
  */
 package com.amazonaws.auth.policy.internal;
 
 import java.io.Writer;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
Serializes an AWS policy object to a JSON string, suitable for sending to an AWS service.
 
 public class JsonPolicyWriter {

    
The JSON Generator to generator a JSON string
 
     private JsonGenerator generator = null;

    
The output writer to which the JSON String is written
 
     private Writer writer;

    
Logger used to log exceptions that occurs while writing the Json policy
 
     private static final Log log = LogFactory.getLog("com.amazonaws.auth.policy");

    
Constructs a new instance of JSONPolicyWriter.
 
     public JsonPolicyWriter() {
          = new StringWriter();
         try {
              = Jackson.jsonGeneratorOf();
         } catch (IOException ioe) {
             throw new AmazonClientException(
                     "Unable to instantiate JsonGenerator."ioe);
         }
 
     }

    
Converts the specified AWS policy object to a JSON string, suitable for passing to an AWS service.

Parameters:
policy The AWS policy object to convert to a JSON string.
Returns:
The JSON string representation of the specified policy object.
Throws:
java.lang.IllegalArgumentException If the specified policy is null or invalid and cannot be serialized to a JSON string.
 
     public String writePolicyToString(Policy policy) {
 
         if(!isNotNull(policy))
             throw new IllegalArgumentException("Policy cannot be null");
 
         try {
             return jsonStringOf(policy);
         } catch (Exception e) {
             String message = "Unable to serialize policy to JSON string: "
                     + e.getMessage();
             throw new IllegalArgumentException(messagee);
         } finally {
             try { .close(); } catch (Exception e) { }
         }
     }

    
Converts the given Policy into a JSON String.

Parameters:
policy the policy to be converted.
Returns:
a JSON String of the specified policy object.
    private String jsonStringOf(Policy policythrows JsonGenerationException,
            IOException {
        .writeStartObject();
        if (isNotNull(policy.getId()))
            writeJsonKeyValue(.policy.getId());
        for (Statement statement : policy.getStatements()) {
            .writeStartObject();
            if (isNotNull(statement.getId())) {
                writeJsonKeyValue(.statement.getId());
            }
            writeJsonKeyValue(.statement
                    .getEffect().toString());
            List<Principalprincipals = statement.getPrincipals();
            if (isNotNull(principals) && !principals.isEmpty())
                writePrincipals(principals);
            List<Actionactions = statement.getActions();
            if (isNotNull(actions) && !actions.isEmpty())
                writeActions(actions);
            List<Resourceresources = statement.getResources();
            if (isNotNull(resources) && !resources.isEmpty())
                writeResources(resources);
            List<Conditionconditions = statement.getConditions();
            if (isNotNull(conditions) && !conditions.isEmpty())
                writeConditions(conditions);
            .writeEndObject();
        }
        writeJsonArrayEnd();
        .writeEndObject();
        .flush();
        return .toString();
    }

    
Writes the list of conditions to the JSONGenerator.

Parameters:
conditions the conditions to be written.
    private void writeConditions(List<Conditionconditions)
            throws JsonGenerationExceptionIOException {
        Map<StringConditionsByKeyconditionsByType = groupConditionsByTypeAndKey(conditions);
        ConditionsByKey conditionsByKey;
        for (Map.Entry<StringConditionsByKeyentry : conditionsByType
                .entrySet()) {
            conditionsByKey = conditionsByType.get(entry.getKey());
            writeJsonObjectStart(entry.getKey());
            for (String key : conditionsByKey.keySet()) {
                writeJsonArray(keyconditionsByKey.getConditionsByKey(key));
            }
            writeJsonObjectEnd();
        }
        writeJsonObjectEnd();
    }

    
Writes the list of Resources to the JSONGenerator.

Parameters:
resources the list of resources to be written.
    private void writeResources(List<Resourceresources)
            throws JsonGenerationExceptionIOException {
        List<StringresourceStrings = new ArrayList<String>();
        for (Resource resource : resources) {
            resourceStrings.add(resource.getId());
        }
        writeJsonArray(.resourceStrings);
    }

    
Writes the list of Actions to the JSONGenerator.

Parameters:
actions the list of the actions to be written.
    private void writeActions(List<Actionactions)
            throws JsonGenerationExceptionIOException {
        List<StringactionStrings = new ArrayList<String>();
        for (Action action : actions) {
            actionStrings.add(action.getActionName());
        }
        writeJsonArray(.actionStrings);
    }

    
Writes the list of Principals to the JSONGenerator.

Parameters:
principals the list of principals to be written.
    private void writePrincipals(List<Principalprincipals)
            throws JsonGenerationExceptionIOException {
        if (principals.size() == 1 && principals.get(0).equals(.)) {
        } else {
            Map<StringList<String>> principalsByScheme = groupPrincipalByScheme(principals);
            List<StringprincipalValues;
            for (Map.Entry<StringList<String>> entry : principalsByScheme.entrySet()) {
                principalValues = principalsByScheme.get(entry.getKey());
                if (principalValues.size() == 1) {
                    writeJsonKeyValue(entry.getKey(), principalValues.get(0));
                } else {
                    writeJsonArray(entry.getKey(), principalValues);
                }
            }
            writeJsonObjectEnd();
        }
    }

    
Groups the list of Principals by the Scheme.

Parameters:
principals the list of Principals
Returns:
a map grouped by scheme of the principal.
            List<Principalprincipals) {
        Map<StringList<String>> principalsByScheme = new HashMap<StringList<String>>();
        String provider;
        List<StringprincipalValues;
        for (Principal principal : principals) {
            provider = principal.getProvider();
            if (!principalsByScheme.containsKey(provider)) {
                principalsByScheme.put(providernew ArrayList<String>());
            }
            principalValues = principalsByScheme.get(provider);
            principalValues.add(principal.getId());
        }
        return principalsByScheme;
    }

    
Inner class to hold condition values for each key under a condition type.
    static class ConditionsByKey {
        private Map<String,List<String>> conditionsByKey;
        public ConditionsByKey(){
             = new HashMap<String,List<String>>();
        }
        public Map<String,List<String>> getConditionsByKey() {
            return ;
        }
        public void setConditionsByKey(Map<String,List<String>> conditionsByKey) {
            this. = conditionsByKey;
        }
        public boolean containsKey(String key){
            return .containsKey(key);
        }
        public List<StringgetConditionsByKey(String key){
            return .get(key);
        }
        public Set<StringkeySet(){
            return .keySet();
        }
        public void addValuesToKey(String keyList<Stringvalues) {
            List<StringconditionValues = getConditionsByKey(key);
            if (conditionValues == null)
                .put(keynew ArrayList<String>(values));
            else
                conditionValues.addAll(values);
        }
    }

    
Groups the list of Conditions by the condition type and condition key.

Parameters:
conditions the list of conditions to be grouped
Returns:
a map of conditions grouped by type and then key.
            List<Conditionconditions) {
        Map<StringConditionsByKeyconditionsByType = new HashMap<StringConditionsByKey>();
        String type;
        String key;
        ConditionsByKey conditionsByKey;
        for (Condition condition : conditions) {
            type = condition.getType();
            key = condition.getConditionKey();
            if (!(conditionsByType.containsKey(type))) {
                conditionsByType.put(typenew ConditionsByKey());
            }
            conditionsByKey = conditionsByType.get(type);
            conditionsByKey.addValuesToKey(keycondition.getValues());
        }
        return conditionsByType;
    }

    
Writes an array along with its values to the JSONGenerator.

Parameters:
arrayName name of the JSON array.
values values of the JSON array.
    private void writeJsonArray(String arrayNameList<Stringvalues)
            throws JsonGenerationExceptionIOException {
        writeJsonArrayStart(arrayName);
        for (String value : values)
            .writeString(value);
        writeJsonArrayEnd();
    }

    
Writes the Start of Object String to the JSONGenerator along with Object Name.

Parameters:
fieldName name of the JSON Object.
    private void writeJsonObjectStart(String fieldName)
            throws JsonGenerationExceptionIOException {
        .writeObjectFieldStart(fieldName);
    }

    
Writes the End of Object String to the JSONGenerator.
    private void writeJsonObjectEnd() throws JsonGenerationExceptionIOException {
        .writeEndObject();
    }

    
Writes the Start of Array String to the JSONGenerator along with Array Name.

Parameters:
fieldName name of the JSON array
    private void writeJsonArrayStart(String fieldName)
            throws JsonGenerationExceptionIOException {
        .writeArrayFieldStart(fieldName);
    }

    
Writes the End of Array String to the JSONGenerator.
    private void writeJsonArrayEnd() throws JsonGenerationExceptionIOException {
        .writeEndArray();
    }

    
Writes the given field and the value to the JsonGenerator

Parameters:
fieldName the JSON field name
value value for the field
    private void writeJsonKeyValue(String fieldNameString value)
            throws JsonGenerationExceptionIOException {
        .writeStringField(fieldNamevalue);
    }

    
Checks if the given object is not null.

Parameters:
object the object compared to null.
Returns:
true if the object is not null else false
    private boolean isNotNull(Object object) {
        return null != object;
    }
New to GrepCode? Check out our FAQ X