Example usage for com.fasterxml.jackson.annotation PropertyAccessor FIELD

List of usage examples for com.fasterxml.jackson.annotation PropertyAccessor FIELD

Introduction

In this page you can find the example usage for com.fasterxml.jackson.annotation PropertyAccessor FIELD.

Prototype

PropertyAccessor FIELD

To view the source code for com.fasterxml.jackson.annotation PropertyAccessor FIELD.

Click Source Link

Document

Field refers to fields of regular Java objects.

Usage

From source file:org.apache.openaz.xacml.std.json.JSONRequest.java

/**
 * Do the work of converting the {@link org.apache.openaz.xacml.api.Request} object to a string, allowing
 * for pretty-printing if desired. IMPORTANT: This method does NOT close the outputStream. It is the
 * responsibility of the caller to (who opened the stream) to close it.
 *
 * @param request/*from ww w .  j  a v a  2 s.c  o m*/
 * @param outputStream
 * @param prettyPrint
 * @throws java.io.IOException #throws JSONStructureException
 */
public static void convert(Request request, OutputStream outputStream, boolean prettyPrint)
        throws IOException, JSONStructureException {

    if (request == null) {
        throw new NullPointerException("No Request in convert");
    }

    Map<String, Object> requestMap = new HashMap<String, Object>();

    // ReturnPolicyIdList
    requestMap.put("ReturnPolicyIdList", request.getReturnPolicyIdList());
    // Combined
    requestMap.put("CombinedDecision", request.getCombinedDecision());
    // XPath
    if (request.getRequestDefaults() != null) {
        requestMap.put("XPathVersion", request.getRequestDefaults().getXPathVersion());
    }

    // Categories
    Iterator<RequestAttributes> rait = request.getRequestAttributes().iterator();
    List<Map<String, Object>> generalCategoriesList = new ArrayList<Map<String, Object>>();
    while (rait.hasNext()) {
        RequestAttributes ra = rait.next();

        // create a new map for the category
        Map<String, Object> categoryMap = new HashMap<String, Object>();

        // fill in the category
        if (ra.getXmlId() != null) {
            categoryMap.put("Id", ra.getXmlId());
        }
        if (ra.getContentRoot() != null) {
            StringWriter writer = new StringWriter();
            Transformer transformer = null;
            try {
                transformer = TransformerFactory.newInstance().newTransformer();
                transformer.transform(new DOMSource(ra.getContentRoot()), new StreamResult(writer));
            } catch (Exception e) {
                throw new JSONStructureException("Unable to Content node to string; e=" + e);
            }

            String xml = writer.toString();

            categoryMap.put("Content", xml);
        }

        Iterator<Attribute> attrIt = ra.getAttributes().iterator();
        List<Map<String, Object>> attributesList = new ArrayList<Map<String, Object>>();
        while (attrIt.hasNext()) {
            Attribute attr = attrIt.next();
            Map<String, Object> attrMap = new HashMap<String, Object>();
            attrMap.put("AttributeId", attr.getAttributeId().stringValue());
            if (attr.getIssuer() != null) {
                attrMap.put("Issuer", attr.getIssuer());
            }
            attrMap.put("IncludeInResult", attr.getIncludeInResults());
            Collection<AttributeValue<?>> valuesCollection = attr.getValues();
            Iterator<AttributeValue<?>> valuesIt = valuesCollection.iterator();

            if (valuesCollection.size() == 1) {
                // single-value
                AttributeValue<?> attrValue = valuesIt.next();
                attrMap.put("DataType", attrValue.getDataTypeId().stringValue());

                attrMap.put("Value", jsonOutputObject(attrValue.getValue(), attrValue));

            } else if (valuesCollection.size() > 1) {
                // multiple values
                List<Object> attrValueList = new ArrayList<Object>();
                while (valuesIt.hasNext()) {
                    AttributeValue<?> attrValue = valuesIt.next();
                    // assume all have the same type, so last one in list is fine
                    attrMap.put("DataType", attrValue.getDataTypeId().stringValue());

                    attrValueList.add(jsonOutputObject(attrValue.getValue(), attrValue));

                }
                attrMap.put("Value", attrValueList);

            }

            attributesList.add(attrMap);
        }
        if (attributesList.size() > 0) {
            categoryMap.put("Attribute", attributesList);
        }

        // We do not use the "Default" category objects because the XML may have multiples of the same
        // Category.
        // This is fine when the categories are contained in the array of Category objects,
        // but if we use the Default category objects we might end up with multiples of the same Category
        // name,
        // and the Jackson parser does not handle that well.
        // Example: This is ok because the AccessSubjects are independent items within the list:
        // { "Request" : {
        // "Category" : [
        // { "CategoryId" : ""subject", " },
        // { "CategoryId" : ""subject", " }
        // ]
        // }}
        //
        // This is NOT ok because the Subjects are seen as duplicate elements:
        // { "Request" : {
        // "AccessSubject" : {"},
        // "AccessSubject" : {"},
        // }}

        categoryMap.put("CategoryId", ra.getCategory().stringValue());
        generalCategoriesList.add(categoryMap);

    }

    if (generalCategoriesList.size() > 0) {
        requestMap.put("Category", generalCategoriesList);
    }

    // MultiRequests
    if (request.getMultiRequests() != null) {
        Collection<RequestReference> referenceCollection = request.getMultiRequests();

        Map<String, Object> multiRequestMap = new HashMap<String, Object>();
        List<Map<String, Object>> requestReferenceList = new ArrayList<Map<String, Object>>();

        Iterator<RequestReference> rrIt = referenceCollection.iterator();
        while (rrIt.hasNext()) {
            RequestReference rr = rrIt.next();
            Map<String, Object> requestReferenceMap = new HashMap<String, Object>();

            Collection<RequestAttributesReference> rarCollection = rr.getAttributesReferences();
            List<Object> ridList = new ArrayList<Object>();
            Iterator<RequestAttributesReference> rarIt = rarCollection.iterator();
            while (rarIt.hasNext()) {
                RequestAttributesReference rar = rarIt.next();
                ridList.add(rar.getReferenceId());
            }

            if (ridList.size() > 0) {
                requestReferenceMap.put("ReferenceId", ridList);
            }

            if (requestReferenceMap.size() > 0) {
                requestReferenceList.add(requestReferenceMap);
            }

            if (requestReferenceList.size() > 0) {
                multiRequestMap.put("RequestReference", requestReferenceList);
            }
        }

        if (multiRequestMap.size() > 0) {
            requestMap.put("MultiRequests", multiRequestMap);
        }
    }

    //
    // Create the overall Request map
    //
    Map<String, Object> theWholeRequest = new HashMap<String, Object>();
    theWholeRequest.put("Request", requestMap);
    //
    // Create a string buffer
    //
    ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, prettyPrint);
    try (OutputStreamWriter osw = new OutputStreamWriter(outputStream)) {

        // convert the request to json string
        String json = mapper.writeValueAsString(theWholeRequest);

        // write it
        osw.write(json);

        // force output
        osw.flush();
    } catch (Exception e) {
        logger.error("Failed to write to json string: " + e.getLocalizedMessage(), e);
    }

}

From source file:org.apache.openaz.xacml.std.json.JSONResponse.java

/**
 * Read characters from the given <code>InputStream</code> and parse them into an XACML
 * {@link org.apache.openaz.xacml.api.Request} object.
 *
 * @param is/*from w w  w.j  a  v  a 2  s.  co m*/
 * @return
 * @throws JSONStructureException
 */
public static Response load(InputStream is) throws JSONStructureException {

    // TODO - ASSUME that order of members within an object does not matter (Different from XML, in JSON
    // everything is handled as Maps so order does not matter)

    // ensure shorthand map is set up
    if (shorthandMap == null) {
        initShorthandMap();
    }

    // ensure that we have an instance of the DataTypeFactory for generating AttributeValues by DataType
    if (dataTypeFactory == null) {
        try {
            dataTypeFactory = DataTypeFactory.newInstance();
            if (dataTypeFactory == null) {
                throw new NullPointerException("No DataTypeFactory found");
            }
        } catch (FactoryException e) {
            throw new JSONStructureException("Unable to find DataTypeFactory, e=" + e);
        }
    }

    // create a new Response object to be filled in
    StdMutableResponse stdMutableResponse = null;

    String json = null;
    ObjectMapper mapper = null;
    try {

        // read the inputStream into a buffer (trick found online scans entire input looking for
        // end-of-file)
        java.util.Scanner scanner = new java.util.Scanner(is);
        scanner.useDelimiter("\\A");
        json = scanner.hasNext() ? scanner.next() : "";
        scanner.close();

        mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

        // TODO - ASSUME that any duplicated component is a bad thing (probably indicating an error in the
        // incoming JSON)
        mapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);

        Map<?, ?> root = mapper.readValue(json, Map.class);

        //
        // Does the Response exist?
        //
        List<?> resultList = (List<?>) root.remove("Response");
        if (resultList == null) {
            throw new JSONStructureException("No \"Response\" property found.");
        }

        checkUnknown("Top-level message", root);

        stdMutableResponse = new StdMutableResponse();

        // handle each Result object
        for (int resultIndex = 0; resultIndex < resultList.size(); resultIndex++) {
            // each item should be a Map<?,?> containing a Result, otherwise it is an error
            Object resultObj = resultList.get(resultIndex);
            if (resultObj == null || !(resultObj instanceof Map)) {
                throw new JSONStructureException(
                        "Response contains null Result or list instead of Result object");
            }

            StdMutableResult stdMutableResult = new StdMutableResult();

            Map<?, ?> resultMap = (Map<?, ?>) resultObj;

            // Must have a Decision
            Object decisionObject = resultMap.remove("Decision");
            if (decisionObject == null) {
                throw new JSONStructureException("Result must have Decision");
            }
            Decision decision = Decision.get(decisionObject.toString());
            if (decision == null) {
                throw new JSONStructureException(
                        "Unknown value for Decision: '" + decisionObject.toString() + "'");
            }
            stdMutableResult.setDecision(decision);

            // may have Status
            Object statusObject = resultMap.remove("Status");
            if (statusObject != null) {
                if (!(statusObject instanceof Map)) {
                    throw new JSONStructureException(
                            "Status must be an object, not type '" + statusObject.getClass().getName() + "'");
                }
                StdMutableStatus stdMutableStatus = new StdMutableStatus();
                Map<?, ?> statusMap = (Map<?, ?>) statusObject;

                // optional message
                Object messageObject = statusMap.remove("StatusMessage");
                if (messageObject != null) {
                    stdMutableStatus.setStatusMessage(messageObject.toString());
                }

                // optional detail
                Object detailObject = statusMap.remove("StatusDetail");
                if (detailObject != null) {
                    StdMutableStatusDetail statusDetail = new StdMutableStatusDetail();
                    // TODO - PROBLEM: The JSON spec says only that the status Detail is raw XML rather
                    // than a JSON object. Therefore we cannot discriminate what is inside the string we
                    // just got.
                    // TODO Fortunately there is only one thing it can be: a MissingAttributeDetail.
                    // TODO Unfortunately the MissingAttributeDetail contains multiple optional elements
                    // including 0 or more values, which makes it non-trivial to parse the XML
                    // representation.
                    // TODO Unfortunately the JSON spec does not say how the XML is formatted
                    // (with/without whitespace, etc).

                    //
                    // First of all, the String is possible escaped.
                    //
                    // The meaning of "escaped" is defined in section 4.2.3.1 in the JSON spec
                    //
                    String unescapedContent = detailObject.toString().replace("\\\"", "\"");
                    unescapedContent = unescapedContent.replace("\\\\", "\\");

                    // need to add a root element so that the MissingAttributeDetail elements are findable
                    unescapedContent = "<ROOT>" + unescapedContent + "</ROOT>";

                    // logger.info("Escaped content: \n" + unescapedContent);
                    Document doc = null;
                    try (InputStream bis = new ByteArrayInputStream(unescapedContent.getBytes("UTF-8"))) {
                        doc = DOMUtil.loadDocument(bis);
                    } catch (Exception ex) {
                        throw new JSONStructureException(
                                "Unable to parse Content '" + detailObject.toString() + "'");
                    }

                    // ASSUME that this can only be an array of MissingAttributeDetail. Example:
                    // <MissingAttributeDetail
                    // Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
                    // AttributeId="urn:att:xacml:resource:application:motsid"
                    // DataType="http://www.w3.org/2001/XMLSchema#integer">
                    // <AttributeValue
                    // DataType="http://www.w3.org/2001/XMLSchema#integer">56</AttributeValue>
                    // </MissingAttributeDetail>"
                    Element docElement = doc.getDocumentElement();
                    NodeList missingAttributeDetailList = docElement
                            .getElementsByTagName("MissingAttributeDetail");
                    for (int madNodeIndex = 0; madNodeIndex < missingAttributeDetailList
                            .getLength(); madNodeIndex++) {
                        Node madNode = missingAttributeDetailList.item(madNodeIndex);
                        StdMutableMissingAttributeDetail mutableMAD = new StdMutableMissingAttributeDetail();

                        NamedNodeMap attributeMap = madNode.getAttributes();
                        Node attributeNode = attributeMap.getNamedItem("AttributeId");
                        if (attributeNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing AttributeId");
                        }
                        mutableMAD.setAttributeId(new IdentifierImpl(attributeNode.getNodeValue()));
                        Node categoryNode = attributeMap.getNamedItem("Category");
                        if (categoryNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing Category");
                        }
                        mutableMAD.setCategory(new IdentifierImpl(categoryNode.getNodeValue()));
                        Node dataTypeNode = attributeMap.getNamedItem("DataType");
                        if (dataTypeNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing DataType");
                        }
                        mutableMAD.setDataTypeId(new IdentifierImpl(dataTypeNode.getNodeValue()));
                        Node issuerNode = attributeMap.getNamedItem("Issuer");
                        if (issuerNode != null) {
                            mutableMAD.setIssuer(issuerNode.getNodeValue());
                        }

                        // get any value elements
                        NodeList childNodeList = madNode.getChildNodes();
                        for (int childIndex = 0; childIndex < childNodeList.getLength(); childIndex++) {
                            Node childNode = childNodeList.item(childIndex);
                            if (!childNode.getNodeName().equals("AttributeValue")) {
                                continue;
                            }
                            Node childDataTypeNode = childNode.getAttributes().getNamedItem("DataType");
                            if (childDataTypeNode == null) {
                                throw new JSONStructureException(
                                        "MissingAttributeDetail contains AttributeValue '"
                                                + childNode.getNodeValue() + "' with no DataType");
                            }
                            String dataType = childDataTypeNode.getNodeValue();
                            // this probably is not a shorthand, but look it up anyway. The full Ids are
                            // in the table too.
                            Identifier valueDataTypeId = shorthandMap.get(dataType);
                            if (valueDataTypeId == null) {
                                throw new JSONStructureException(
                                        "MissingAttibuteDetail contains AttributeValue with unknown DataType="
                                                + dataType);
                            }
                            // if Id is known then it is reasonable to do the following without checking
                            DataType<?> valueDataType = dataTypeFactory.getDataType(valueDataTypeId);
                            AttributeValue<?> attributeValue;
                            try {
                                // for some reason the value may be the value of a child of this node
                                // rather than the value of this node itself.
                                Node valueNode = childNode;
                                if (valueNode.hasChildNodes()) {
                                    valueNode = valueNode.getFirstChild();
                                }
                                attributeValue = valueDataType.createAttributeValue(valueNode.getNodeValue());
                            } catch (Exception ex) {
                                throw new JSONStructureException(
                                        "Unable to create AttributeValue from MissingAttributeDetail AttributeValue '"
                                                + childNode.getNodeValue() + "', error was: "
                                                + ex.getMessage());
                            }
                            mutableMAD.addAttributeValue(attributeValue);
                        }

                        statusDetail.addMissingAttributeDetail(mutableMAD);
                    }

                    stdMutableStatus.setStatusDetail(statusDetail);
                }

                // optional StatusCode which may contain recursive child StatusCode
                Object statusCodeObject = statusMap.remove("StatusCode");
                if (statusCodeObject != null) {
                    if (!(statusCodeObject instanceof Map)) {
                        throw new JSONStructureException("StatusCode must be object");
                    }
                    StatusCode statusCode = parseStatusCode((Map<?, ?>) statusCodeObject);
                    stdMutableStatus.setStatusCode(statusCode);
                }

                checkUnknown("Status", statusMap);

                stdMutableResult.setStatus(stdMutableStatus);
            }

            // may have Obligations
            Object obligationsObject = resultMap.remove("Obligations");
            if (obligationsObject != null) {
                parseObligationsOrAdvice(obligationsObject, stdMutableResult, true);
            }

            // may have Advice
            Object adviceObject = resultMap.remove("AssociatedAdvice");
            if (adviceObject != null) {
                parseObligationsOrAdvice(adviceObject, stdMutableResult, false);
            }

            // may have Category (a.k.a Attributes)
            // TODO - POSSIBLE NAME CHANGE - XML core calls this "Attributes", but name in JSON standard
            // is questionable.
            // TODO The variables here are named "Attributes" because that is the internal name in our
            // objects (based on the Core spec).
            Object attributesObject = resultMap.remove("Category");
            if (attributesObject != null) {
                if (!(attributesObject instanceof List)) {
                    throw new JSONStructureException("Category must be list");
                }
                List<?> attributesList = (List<?>) attributesObject;

                for (Object categoryObject : attributesList) {
                    if (categoryObject == null || !(categoryObject instanceof Map)) {
                        throw new JSONStructureException("Category array item must be object");
                    }
                    Map<?, ?> categoryMap = (Map<?, ?>) categoryObject;
                    StdMutableAttributeCategory stdMutableAttributeCategory = new StdMutableAttributeCategory();

                    // mandatory CategoryId
                    Object categoryIdObject = categoryMap.remove("CategoryId");
                    if (categoryIdObject == null) {
                        throw new JSONStructureException("Category array item must contain CategoryId");
                    }
                    Identifier categoryId = new IdentifierImpl(categoryIdObject.toString());

                    stdMutableAttributeCategory.setCategory(categoryId);

                    // optional Attributes
                    Object attributeListObject = categoryMap.remove("Attribute");
                    if (attributeListObject != null) {
                        if (!(attributeListObject instanceof List)) {
                            throw new JSONStructureException("Category memeber Attribute must be list");
                        }
                        List<?> attributeList = (List<?>) attributeListObject;
                        // get each attribute and add to category
                        for (Object attributeMapObject : attributeList) {
                            if (attributeMapObject == null || !(attributeMapObject instanceof Map)) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item must be object");
                            }
                            Map<?, ?> attributeMap = (Map<?, ?>) attributeMapObject;

                            StdMutableAttribute stdMutableAttribute = new StdMutableAttribute();

                            // optional IncludeInResult
                            // TODO - Odd situation!!: We are reading a string representing a Result which
                            // includes Attributes.
                            // TODO In this case, what does it mean if "IncludeInResult=false"?
                            // TODO The Attribute is obviously included in this Result because it is in
                            // the file/string we are reading.
                            // TODO Our choice: Always include the Attribute. If the IncludeInResult is
                            // included in the input, set it's value in the object as directed.
                            // TODO This may cause mismatches between a Result read in and a new text
                            // generated from the internal Result object.
                            Object includeInResultObject = attributeMap.remove("IncludeInResult");
                            // the fact that the attribute is in the input means this should be true
                            stdMutableAttribute.setIncludeInResults(true);
                            if (includeInResultObject != null) {
                                // need to check the value in the input
                                try {
                                    boolean include = DataTypes.DT_BOOLEAN.convert(includeInResultObject)
                                            .booleanValue();
                                    // set the value in the object exactly as directed, whether it makes
                                    // sense or not
                                    stdMutableAttribute.setIncludeInResults(include);
                                } catch (DataTypeException e) {
                                    throw new JSONStructureException(
                                            "Category member Attribute list item has IncludeInResult value '"
                                                    + includeInResultObject.toString()
                                                    + "' which is not boolean");
                                }
                            }

                            // category is not part of Attribute in spec - it is used internally to link
                            // attribute to Category
                            stdMutableAttribute.setCategory(categoryId);

                            // mandatory Id
                            Object aaIdObject = attributeMap.remove("AttributeId");
                            if (aaIdObject == null) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item missing AttributeId");
                            }
                            stdMutableAttribute.setAttributeId(new IdentifierImpl(aaIdObject.toString()));

                            // get the optional DataType so we know what to do with the mandatory value
                            Object dataTypeObject = attributeMap.remove("DataType");
                            Identifier dataTypeId = null;
                            if (dataTypeObject != null) {
                                dataTypeId = shorthandMap.get(dataTypeObject.toString());
                                // if there was a DataType given it must be a real one
                                if (dataTypeId == null) {
                                    throw new JSONStructureException(
                                            "Category member Attribute list item has unknown DataType='"
                                                    + dataTypeObject.toString() + "'");
                                }
                            } else {
                                // if DataType not given, use String
                                dataTypeId = DataTypes.DT_STRING.getId();
                            }

                            // mandatory Value
                            Object valueObject = attributeMap.remove("Value");
                            if (valueObject == null) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item missing Value");
                            }
                            AttributeValue<?> attributeValue = null;
                            try {
                                DataType<?> dataType = new StdDataTypeFactory().getDataType(dataTypeId);
                                if (dataType == DataTypes.DT_XPATHEXPRESSION) {
                                    // XPAthExpressions are complex data types that need special
                                    // translation from the JSON form to the internal form
                                    attributeValue = convertMapToXPathExpression(valueObject);

                                } else {
                                    // everything other than XPathExpressions are simple values that the
                                    // DataTypes know how to handle
                                    attributeValue = dataType.createAttributeValue(valueObject);
                                }
                            } catch (DataTypeException e) {
                                throw new JSONStructureException("Category member Attribute list item Value='"
                                        + valueObject.toString() + "' not of type '" + dataTypeId + "'");
                            }
                            stdMutableAttribute.addValue(attributeValue);

                            // optional Issuer
                            Object issuerObject = attributeMap.remove("Issuer");
                            if (issuerObject != null) {
                                stdMutableAttribute.setIssuer(issuerObject.toString());
                            }

                            checkUnknown("Category Attribute list item", attributeMap);
                            stdMutableAttributeCategory.add(stdMutableAttribute);
                        }
                    }

                    checkUnknown("Category", categoryMap);

                    // if none of the attributes are returned, do not return the category either
                    if (stdMutableAttributeCategory.getAttributes().size() > 0) {
                        stdMutableResult.addAttributeCategory(stdMutableAttributeCategory);
                    }
                }
            }

            // may have PolicyIdentifierList
            Object policyIdObject = resultMap.remove("PolicyIdentifier");
            if (policyIdObject != null) {
                if (!(policyIdObject instanceof Map)) {
                    throw new JSONStructureException("PolicyIdentifier must be object");
                }
                Map<?, ?> policyIdMap = (Map<?, ?>) policyIdObject;

                // optional PolicyIdReference list
                Object policyIdReferenceObject = policyIdMap.remove("PolicyIdReference");
                if (policyIdReferenceObject != null) {
                    parseIdReferences(policyIdReferenceObject, stdMutableResult, false);
                }

                // optional PolicySetIdReferenceList
                Object policySetIdReferenceObject = policyIdMap.remove("PolicySetIdReference");
                if (policySetIdReferenceObject != null) {
                    parseIdReferences(policySetIdReferenceObject, stdMutableResult, true);
                }

                checkUnknown("PolicyIdentifier", policyIdMap);

            }

            checkUnknown("Result", resultMap);

            // add this result to the Response
            stdMutableResponse.add(stdMutableResult);

        }

        return stdMutableResponse;

    } catch (JsonParseException e) {
        throw new JSONStructureException("Unable to parse JSON '" + json + "', exception: " + e, e);
    } catch (JsonMappingException e) {
        throw new JSONStructureException("Unable to map JSON '" + json + "', exception: " + e, e);
    } catch (IOException e) {
        throw new JSONStructureException("Unable to read JSON input, exception: " + e, e);
    }

    // all done
    // return new StdRequest(stdMutableRequest);

    // throw new JSONStructureException("JSONResponse load string and load from file not implemented");
}

From source file:org.apache.openaz.xacml.std.json.JSONResponse.java

/**
 * Do the work of converting the {@link org.apache.openaz.xacml.api.Response} object to a string, allowing
 * for pretty-printing if desired. IMPORTANT: This method does NOT close the outputStream. It is the
 * responsibility of the caller to (who opened the stream) to close it.
 *
 * @param response//ww  w.  j  a  va2  s.  c o  m
 * @param outputStream
 * @param prettyPrint
 * @throws java.io.IOException #throws JSONStructureException
 */
public static void convert(Response response, OutputStream outputStream, boolean prettyPrint)
        throws IOException, JSONStructureException {

    // TODO - ASSUME that order of members within an object does not matter (Different from XML, in JSON
    // everything is handled as Maps so order does not matter)

    // TODO - ASSUME that the spec will fix inconsistency between AttributeId and Id (both are mentioned);
    // for now use "AttributeId" as it is clearer.

    // ensure shorthand map is set up
    if (outputShorthandMap == null) {
        initOutputShorthandMap();
    }

    if (response == null) {
        throw new JSONStructureException("No Request in convert");
    }

    if (response.getResults() == null || response.getResults().size() == 0) {
        // must be at least one result
        throw new JSONStructureException("No Result in Response");
    }

    String json = null;
    ArrayList<Map<String, Object>> responses = new ArrayList<Map<String, Object>>();

    //
    // Process each Result object
    //

    Iterator<Result> iter = response.getResults().iterator();
    while (iter.hasNext()) {
        Result result = iter.next();
        Map<String, Object> responseTree = new HashMap<String, Object>();
        if (result.getDecision() == null) {
            throw new JSONStructureException("No Decision in Result");
        }
        responseTree.put("Decision", result.getDecision().toString());

        if (result.getStatus() != null) {
            // if the StatusCode object as a whole is missing it defaults to OK, but if it exists it must
            // have an actual code value
            if (result.getStatus().getStatusCode() == null) {
                throw new JSONStructureException("No Identifier given in StatusCode");
            }
            Identifier statusCodeId = result.getStatus().getStatusCode().getStatusCodeValue();

            // if there is a status code, it must agree with the decision
            // Permit/Deny/NotAllowed must all be OK
            // Indeterminate must not be OK
            if (statusCodeId.equals(StdStatusCode.STATUS_CODE_OK.getStatusCodeValue())
                    && !(result.getDecision() == Decision.DENY || result.getDecision() == Decision.PERMIT
                            || result.getDecision() == Decision.NOTAPPLICABLE)
                    || !statusCodeId.equals(StdStatusCode.STATUS_CODE_OK.getStatusCodeValue())
                            && !(result.getDecision() == Decision.INDETERMINATE
                                    || result.getDecision() == Decision.INDETERMINATE_DENY
                                    || result.getDecision() == Decision.INDETERMINATE_DENYPERMIT
                                    || result.getDecision() == Decision.INDETERMINATE_PERMIT)) {
                throw new JSONStructureException("StatusCode '" + statusCodeId.stringValue()
                        + "' does not match Decision '" + result.getDecision().toString());
            }

            //
            // Create the status
            //
            Map<String, Object> statusTree = new HashMap<String, Object>();
            Map<String, Object> statusValue = new HashMap<String, Object>();
            statusValue.put("Value", statusCodeId.stringValue());
            addChildStatusCodes(result.getStatus().getStatusCode(), statusValue);
            statusTree.put("StatusCode", statusValue);
            String message = result.getStatus().getStatusMessage();
            if (message != null) {
                statusTree.put("StatusMessage", message);
            }

            /*
             * StatusDetail - special information The XACML 3.0 core spec says that the StatusDetail field
             * depends on the StatusCode: StatusCode == missing-attribute => may have StatusDetail which
             * is a list of MissingAttributeDetail structures StatusCode == anything else => no
             * StatusDetail allowed This greatly simplifies handling the StatusDetail because the
             * MissingAttributeDetail structure is well-defined. Thus the statement in the specs (both
             * core and RESTful/JSON) that this can contain arbitrary XML is not correct.
             */
            if (result.getStatus().getStatusDetail() != null) {

                String statusDetailXMLString = "";

                // cross-check that rules defined in XACML Core spec section 5.5.7 re: when StatusDetail
                // may/may-not be included have been followed
                if (result.getStatus().isOk()) {
                    throw new JSONStructureException("Status '" + result.getStatus().getStatusCode().toString()
                            + "' must not return StatusDetail");
                } else if (result.getStatus().getStatusCode().equals(XACML3.ID_STATUS_MISSING_ATTRIBUTE)
                        && result.getStatus().getStatusDetail().getMissingAttributeDetails() == null) {
                    throw new JSONStructureException("Status '" + result.getStatus().getStatusCode().toString()
                            + "' has StatusDetail without MissingAttributeDetail");
                } else if (result.getStatus().getStatusCode().equals(XACML3.ID_STATUS_SYNTAX_ERROR)) {
                    throw new JSONStructureException("Status '" + result.getStatus().getStatusCode().toString()
                            + "' must not return StatusDetail");
                } else if (result.getStatus().getStatusCode().equals(XACML3.ID_STATUS_PROCESSING_ERROR)) {
                    throw new JSONStructureException("Status '" + result.getStatus().getStatusCode().toString()
                            + "' must not return StatusDetail");
                }

                // if included, StatusDetail is handled differently for each type of detail message and
                // the contents are formatted into escaped XML rather than objects

                if (result.getStatus().getStatusDetail().getMissingAttributeDetails() != null) {
                    if (!statusCodeId.equals(XACML3.ID_STATUS_MISSING_ATTRIBUTE)) {
                        throw new JSONStructureException(
                                "MissingAttributeDetails can only be included when StatusCode is MISSING_ATTRIBUTES, not '"
                                        + statusCodeId.stringValue());
                    }
                    // ASSUME that a list of length 0 should be treated as having no
                    // MissingAttributeDetails and ignored
                    if (result.getStatus().getStatusDetail().getMissingAttributeDetails().size() > 0) {
                        // TODO - ASSUME no newlines or indentation in XML - NOTE that white-space IS
                        // significant in XML
                        statusDetailXMLString = "";

                        for (MissingAttributeDetail mad : result.getStatus().getStatusDetail()
                                .getMissingAttributeDetails()) {
                            statusDetailXMLString += "<MissingAttributeDetail";

                            if (mad.getCategory() == null || mad.getAttributeId() == null
                                    || mad.getDataTypeId() == null) {
                                throw new JSONStructureException(
                                        "MissingAttributeDetail must have Category, AttributeId and DataType");
                            }
                            statusDetailXMLString += " Category=\"" + mad.getCategory().stringValue() + "\"";
                            statusDetailXMLString += " AttributeId=\"" + mad.getAttributeId().stringValue()
                                    + "\"";
                            // TODO - In this case we do NOT use the shorthand notation for the DataType
                            // because we are generating XML and it is not clear who should will be using
                            // it on client
                            statusDetailXMLString += " DataType=\"" + mad.getDataTypeId().stringValue() + "\"";
                            if (mad.getIssuer() != null) {
                                statusDetailXMLString += " Issuer=\"" + mad.getIssuer() + "\"";
                            }

                            // done with attibutes
                            statusDetailXMLString += ">";

                            // Now get Values and add as child element nodes
                            if (mad.getAttributeValues() != null && mad.getAttributeValues().size() > 0) {
                                for (AttributeValue<?> av : mad.getAttributeValues()) {
                                    statusDetailXMLString += "<AttributeValue";
                                    statusDetailXMLString += " DataType=\"" + av.getDataTypeId() + "\">";
                                    statusDetailXMLString += jsonOutputObject(av.getValue(), av).toString()
                                            + "</AttributeValue>";
                                }
                            }

                        }
                        statusDetailXMLString += "</MissingAttributeDetail>";
                    }
                } else {
                    throw new JSONStructureException(
                            "Unhandled StatusDetail contents (statusDetail exists but is not MissingAttributeDetail)");
                }

                if (statusDetailXMLString.length() > 0) {
                    // make sure all backslashes and double-quotes are escaped
                    // (will only exist in string values)
                    statusDetailXMLString = statusDetailXMLString.replace("\\", "\\\\");
                    statusDetailXMLString = statusDetailXMLString.replace("\"", "\\\"");
                    statusTree.put("StatusDetail", statusDetailXMLString);
                }

            }

            responseTree.put("Status", statusTree);
        }

        //
        // Obligations
        //
        if (result.getObligations() != null && result.getObligations().size() > 0) {
            Iterator<Obligation> iterObs = result.getObligations().iterator();
            List<Object> obligationCollectionList = new ArrayList<Object>();
            while (iterObs.hasNext()) {
                Obligation ob = iterObs.next();
                Map<String, Object> obligationTree = new HashMap<String, Object>();
                if (ob.getId() == null) {
                    throw new JSONStructureException("Obligation must have Id");
                }
                obligationTree.put("Id", ob.getId().stringValue());
                if (ob.getAttributeAssignments() != null && ob.getAttributeAssignments().size() > 0) {
                    Iterator<AttributeAssignment> iterSetObs = ob.getAttributeAssignments().iterator();
                    ArrayList<HashMap<String, Object>> attributes = new ArrayList<HashMap<String, Object>>();
                    while (iterSetObs.hasNext()) {
                        AttributeAssignment entity = iterSetObs.next();
                        HashMap<String, Object> entityTree = new HashMap<String, Object>();
                        if (entity.getAttributeId() == null) {
                            throw new JSONStructureException("Obligation Attribute must have AttributeId");
                        }
                        entityTree.put("AttributeId", entity.getAttributeId().stringValue());
                        if (entity.getCategory() != null) {
                            entityTree.put("Category", entity.getCategory().stringValue());
                        }
                        if (entity.getIssuer() != null) {
                            entityTree.put("Issuer", entity.getIssuer());
                        }
                        AttributeValue<?> value = entity.getAttributeValue();
                        if (value == null || value.getValue() == null) {
                            // Yes it can
                            // throw new JSONStructureException("Obligation Attribute must have Value");
                            entityTree.put("Value", new String(""));
                        } else {
                            // we are "encouraged" to us Shorthand notation for DataType, but it is not
                            // required
                            if (value.getDataTypeId() != null) {
                                //
                                // Don't use shorthand by default, for backwards compatibility
                                // to our pep's.
                                //
                                entityTree.put("DataType", value.getDataTypeId().stringValue());
                            }

                            // Internally the XPathCategory is in the AttributeValue object, but in the
                            // JSON format it is part of the Value (handled by jsonOutputObject() )
                            // so do not handle it here

                            entityTree.put("Value", jsonOutputObject(value.getValue(), value));
                        }
                        attributes.add(entityTree);
                    }
                    obligationTree.put("AttributeAssignment", attributes);
                }
                obligationCollectionList.add(obligationTree);
            }
            responseTree.put("Obligations", obligationCollectionList);
        }

        //
        // Advice
        //
        if (result.getAssociatedAdvice() != null && result.getAssociatedAdvice().size() > 0) {
            Iterator<Advice> iterAAs = result.getAssociatedAdvice().iterator();
            List<Object> adviceCollectionList = new ArrayList<Object>();
            while (iterAAs.hasNext()) {
                Advice advice = iterAAs.next();
                Map<String, Object> adviceTree = new HashMap<String, Object>();
                if (advice.getId() == null) {
                    throw new JSONStructureException("Advice must have Id");
                }
                adviceTree.put("Id", advice.getId().stringValue());
                if (advice.getAttributeAssignments() != null && advice.getAttributeAssignments().size() > 0) {
                    Iterator<AttributeAssignment> iterSetObs = advice.getAttributeAssignments().iterator();
                    ArrayList<HashMap<String, Object>> attributes = new ArrayList<HashMap<String, Object>>();
                    while (iterSetObs.hasNext()) {
                        AttributeAssignment entity = iterSetObs.next();
                        HashMap<String, Object> entityTree = new HashMap<String, Object>();
                        if (entity.getAttributeId() == null) {
                            throw new JSONStructureException("Advice Attribute must have AttributeId");
                        }
                        entityTree.put("AttributeId", entity.getAttributeId().stringValue());
                        if (entity.getCategory() != null) {
                            entityTree.put("Category", entity.getCategory().stringValue());
                        }
                        if (entity.getIssuer() != null) {
                            entityTree.put("Issuer", entity.getIssuer());
                        }
                        AttributeValue<?> value = entity.getAttributeValue();
                        if (value == null || value.getValue() == null) {
                            // NO - it can have a null or empty string etc.
                            // throw new JSONStructureException("Advice Attribute must have Value");
                            entityTree.put("Value", new String(""));
                        } else {
                            // we are "encouraged" to us Shorthand notation for DataType, but it is not
                            // required
                            if (value.getDataTypeId() != null) {
                                //
                                // Don't use shorthand by default, for backwards compatibility
                                // to our pep's.
                                //
                                entityTree.put("DataType", value.getDataTypeId().stringValue());
                            }

                            // Internally the XPathCategory is in the AttributeValue object, but in the
                            // JSON format it is part of the Value (handled by jsonOutputObject() )
                            // so do not handle it here

                            entityTree.put("Value", jsonOutputObject(value.getValue(), value));
                        }
                        attributes.add(entityTree);
                    }
                    adviceTree.put("AttributeAssignment", attributes);
                }
                adviceCollectionList.add(adviceTree);
            }
            responseTree.put("AssociatedAdvice", adviceCollectionList);
        }

        //
        // Attributes
        //
        // (note change in name from XML to JSON spec; this is called Category in the XML)
        //

        if (result.getAttributes() != null && result.getAttributes().size() > 0) {
            Iterator<AttributeCategory> iterAttributes = result.getAttributes().iterator();
            ArrayList<HashMap<String, Object>> categoryArray = new ArrayList<HashMap<String, Object>>();
            while (iterAttributes.hasNext()) {
                AttributeCategory entity = iterAttributes.next();
                HashMap<String, Object> categoryTree = new HashMap<String, Object>();
                categoryTree.put("CategoryId", entity.getCategory().stringValue());

                // The JSON and XML spec both imply that we can return Content here, but they do not say
                // so explicitly and give no indication of when to include/not-include it
                // Also we should be able to return the xml:Id associated with this attribute, but that
                // does not seem to be available in the AttributeCategory object
                // Note: Our choice is to not include these.
                // There is a question of when they would be included (since IncludeInResult is only on
                // the individual Attribute (singular) objects, not the Attributes),
                // and the Content can be quite lengthy and should not be included by default.
                // We could potentially return these only when at least one of the Attribute components
                // has IncludeInResult=true.
                // However the focus seems to be on returning the individual Attribute objects so the
                // caller can see what the response is referring to, and the Attributes (plural)
                // container is just re-used from the Request object without understanding that the Result
                // should be different or explicitly stating in the Spec what to do with those fields.

                Collection<Attribute> attrs = entity.getAttributes();
                if (attrs != null) {
                    Iterator<Attribute> iterAttrs = attrs.iterator();
                    ArrayList<HashMap<String, Object>> arrayAttributes = new ArrayList<HashMap<String, Object>>();
                    while (iterAttrs.hasNext()) {
                        Attribute attribute = iterAttrs.next();
                        if (!attribute.getIncludeInResults()) {
                            // Would this be an error? This is an internal matter and we arbitrarily
                            // decided to just ignore it.
                            // The attribute will not be included in the output, so the receiver won't
                            // know that this happened.
                            continue;
                        }

                        HashMap<String, Object> theAttribute = new HashMap<String, Object>();
                        // TODO - no need to put this in Result because, by definition, if it is in the
                        // result then this must be true? Since it is optional we do not want to add to
                        // length of JSON output
                        // theAttribute.put("IncludeInResult", true);

                        if (attribute.getAttributeId() == null) {
                            throw new JSONStructureException("Attribute must have AttributeId");
                        }
                        theAttribute.put("AttributeId", attribute.getAttributeId().stringValue());
                        if (attribute.getValues() == null || attribute.getValues().size() == 0) {
                            throw new JSONStructureException("Attribute missing required Value");
                        }
                        Iterator<AttributeValue<?>> valueIterator = attribute.getValues().iterator();

                        // The spec talks about inferring the data type from the value and what to do if
                        // it is a list.
                        // However this is output from the PDP, and the attributes would have been
                        // screened while processing the Request,
                        // so we can assume at this point that we always have a DataType associated with
                        // the values and that the values are
                        // consistent with that DataType (because otherwise the Request would have been
                        // rejected and we would never get here).
                        // However we do need to extract the DataType from one of the Values and that is
                        // done slightly differently
                        // when there is one vs a list.
                        if (attribute.getValues().size() == 1) {
                            // exactly one value, so no need for list of values AND we know exactly what
                            // the DataType is
                            AttributeValue<?> attributeValue = valueIterator.next();
                            if (attributeValue == null || attributeValue.getValue() == null) {
                                throw new JSONStructureException("Attribute must have value");
                            }
                            theAttribute.put("Value",
                                    jsonOutputObject(attributeValue.getValue(), attributeValue));
                            if (attributeValue.getDataTypeId() != null) {
                                // we are "encouraged" to us Shorthand notation for DataType, but it is
                                // not required
                                //
                                // Don't use shorthand by default, for backwards compatibility
                                // to our pep's.
                                //
                                theAttribute.put("DataType", attributeValue.getDataTypeId().stringValue());
                            }
                        } else {
                            // there are multiple values so we have to make a list of the Values
                            List<Object> attrValueList = new ArrayList<Object>();
                            boolean mixedTypes = false;
                            Identifier inferredDataTypeId = null;
                            while (valueIterator.hasNext()) {
                                AttributeValue<?> attrValue = valueIterator.next();
                                if (attrValue == null || attrValue.getValue() == null) {
                                    throw new JSONStructureException("Attribute in array must have value");
                                }
                                attrValueList.add(jsonOutputObject(attrValue.getValue(), attrValue));

                                // try to infer the data type
                                if (attrValue.getDataTypeId() != null) {
                                    if (inferredDataTypeId == null) {
                                        inferredDataTypeId = attrValue.getDataTypeId();
                                    } else {
                                        if (inferredDataTypeId.equals(DataTypes.DT_INTEGER.getId()) && attrValue
                                                .getDataTypeId().equals(DataTypes.DT_DOUBLE.getId())) {
                                            // seeing a double anywhere in a list of integers means the
                                            // type is double
                                            inferredDataTypeId = attrValue.getDataTypeId();
                                        } else if (inferredDataTypeId.equals(DataTypes.DT_DOUBLE.getId())
                                                && attrValue.getDataTypeId()
                                                        .equals(DataTypes.DT_INTEGER.getId())) {
                                            // integers are ok in a list of doubles
                                            continue;
                                        } else if (!inferredDataTypeId.equals(attrValue.getDataTypeId())) {
                                            // all other combinations of types are illegal.
                                            // Note: these attribute values were read from the client's
                                            // Request and were assigned the appropriate DataType at that
                                            // time.
                                            // That DataType would have been the same for each one (e.g.
                                            // String) so there should never be a case where
                                            // there are multiple different types here.
                                            // NOTE THAT IF THIS CHANGES and we want to allow mixed types,
                                            // just replace this throws with
                                            // mixedTypes = true;
                                            throw new JSONStructureException(
                                                    "Mixed DataTypes in Attribute values, '"
                                                            + attrValue.getDataTypeId().stringValue()
                                                            + "' in list of '"
                                                            + inferredDataTypeId.stringValue() + "'");
                                        }
                                    }
                                }
                            }
                            theAttribute.put("Value", attrValueList);

                            if (inferredDataTypeId != null && !mixedTypes) {
                                // list is uniform and we know the type
                                //
                                // Don't use shorthand by default, for backwards compatibility
                                // to our pep's.
                                //
                                theAttribute.put("DataType", inferredDataTypeId.stringValue());
                            }

                        }

                        if (attribute.getIssuer() != null) {
                            theAttribute.put("Issuer", attribute.getIssuer());
                        }

                        arrayAttributes.add(theAttribute);
                    }
                    categoryTree.put("Attribute", arrayAttributes);
                }

                if (categoryTree.size() > 0) {
                    categoryArray.add(categoryTree);
                }
            }
            if (categoryArray.size() > 0) {
                // TODO - Spec changing from Attributes to Category - change is for no good reason other
                // than they didn't like the XML name.
                responseTree.put("Category", categoryArray);
            }
        }

        //
        // PolicyIdentifier
        //
        // (These seem to be handled differently from the XML version where multiple PolicyIdRef and
        // PolicySetIdRef items can be jumbled together in any order.
        // In the XACML JSON spec (5.2.10) it says that the PolicyIdReference and PolicySetIdReference are
        // separate groups
        // where each group is a list of IdReferences.)
        //
        //

        if (result.getPolicyIdentifiers() != null && result.getPolicyIdentifiers().size() > 0
                || result.getPolicySetIdentifiers() != null && result.getPolicySetIdentifiers().size() > 0) {

            Map<String, Object> policyIdentifierCollectionList = new HashMap<String, Object>();
            // handle PolicyIds separately from PolicySetIds
            if (result.getPolicyIdentifiers() != null && result.getPolicyIdentifiers().size() > 0) {
                List<Object> policyIdentifierList = new ArrayList<Object>();
                for (IdReference idRef : result.getPolicyIdentifiers()) {
                    if (idRef == null) {
                        throw new JSONStructureException("PolicyIdReference with null reference");
                    }
                    HashMap<String, Object> entityTree = new HashMap<String, Object>();
                    entityTree.put("Id", idRef.getId().stringValue());
                    if (idRef.getVersion() != null) {
                        entityTree.put("Version", idRef.getVersion().stringValue());
                    }

                    policyIdentifierList.add(entityTree);
                }

                policyIdentifierCollectionList.put("PolicyIdReference", policyIdentifierList);
            }
            // handle PolicySetIds
            if (result.getPolicySetIdentifiers() != null && result.getPolicySetIdentifiers().size() > 0) {
                List<Object> policyIdentifierList = new ArrayList<Object>();
                for (IdReference idRef : result.getPolicySetIdentifiers()) {
                    if (idRef == null) {
                        throw new JSONStructureException("PolicySetIdReference with null reference");
                    }
                    HashMap<String, Object> entityTree = new HashMap<String, Object>();
                    entityTree.put("Id", idRef.getId().stringValue());
                    if (idRef.getVersion() != null) {
                        entityTree.put("Version", idRef.getVersion().stringValue());
                    }

                    policyIdentifierList.add(entityTree);
                }

                policyIdentifierCollectionList.put("PolicySetIdReference", policyIdentifierList);
            }

            responseTree.put("PolicyIdentifier", policyIdentifierCollectionList);
        }

        //
        // Finished
        //
        responses.add(responseTree);
    }

    //
    // Create the overall response
    //
    Map<String, Object> theWholeResponse = new HashMap<String, Object>();
    theWholeResponse.put("Response", responses);
    //
    // Create a string buffer
    //
    ObjectMapper mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, prettyPrint);
    try (OutputStreamWriter osw = new OutputStreamWriter(outputStream)) {
        json = mapper.writeValueAsString(theWholeResponse);

        osw.write(json);

        // force output
        osw.flush();

    } catch (Exception e) {
        logger.error("Failed to write to json string: " + e.getLocalizedMessage(), e);
    }

}

From source file:org.apache.storm.hbase.state.HBaseKeyValueStateProvider.java

StateConfig getStateConfig(Map stormConf) throws Exception {
    StateConfig stateConfig;/*from w  w  w. j  av a2s. co  m*/
    String providerConfig;
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    if (stormConf.containsKey(Config.TOPOLOGY_STATE_PROVIDER_CONFIG)) {
        providerConfig = (String) stormConf.get(Config.TOPOLOGY_STATE_PROVIDER_CONFIG);
        stateConfig = mapper.readValue(providerConfig, StateConfig.class);
    } else {
        stateConfig = new StateConfig();
    }

    // assertion
    assertMandatoryParameterNotEmpty(stateConfig.hbaseConfigKey, "hbaseConfigKey");
    assertMandatoryParameterNotEmpty(stateConfig.tableName, "tableName");
    assertMandatoryParameterNotEmpty(stateConfig.columnFamily, "columnFamily");

    return stateConfig;
}

From source file:org.apereo.portal.dao.usertype.StatisticsJacksonColumnMapper.java

@Override
protected void customizeObjectMapper(ObjectMapper mapper) {
    //Just operate on fields
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);

    //Ignore the empty storedData field in all of the stat summary objects
    filters = new SimpleFilterProvider().addFilter(StoredDataFilterMixIn.FILTER_NAME,
            SimpleBeanPropertyFilter.serializeAllExcept("storedData"));
    mapper.addMixInAnnotations(Object.class, StoredDataFilterMixIn.class);
}

From source file:org.apereo.portal.events.aggr.JpaStatisticalSummaryTest.java

public void testStorelessUnivariateStatistic(StorelessUnivariateStatistic sus, double expected)
        throws Exception {

    assertEquals(expected, sus.getResult(), 0.1);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();/*from   www.  j  a va2s.com*/

    //Configure Jackson to just use fields
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);

    mapper.addMixInAnnotations(Object.class, IgnoreTypeMixIn.class);

    final FilterProvider filters = new SimpleFilterProvider().addFilter("storedDataFilter",
            SimpleBeanPropertyFilter.serializeAllExcept("storedData"));

    final ObjectWriter ssWriter = mapper.writer(filters);
    final ObjectReader ssReader = mapper.reader(sus.getClass());

    final String susString = ssWriter.writeValueAsString(sus);
    System.out.println(susString);
    final StorelessUnivariateStatistic newSus = ssReader.readValue(susString);

    assertEquals(expected, newSus.getResult(), 0.1);
}

From source file:org.finra.herd.tools.common.databridge.DataBridgeManifestReader.java

/**
 * Reads a JSON manifest file into a JSON manifest object.
 *
 * @param jsonManifestFile the JSON manifest file.
 *
 * @return the manifest object.//from   w w w  .ja va 2 s.  c  o m
 * @throws java.io.IOException if any errors were encountered reading the JSON file.
 * @throws IllegalArgumentException if the manifest file has validation errors.
 */
public M readJsonManifest(File jsonManifestFile) throws IOException, IllegalArgumentException {
    // Verify that the file exists and can be read.
    HerdFileUtils.verifyFileExistsAndReadable(jsonManifestFile);

    // Deserialize the JSON manifest.
    BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(jsonManifestFile));
    BufferedReader reader = new BufferedReader(new InputStreamReader(buffer, Charsets.UTF_8));
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    objectMapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
    objectMapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
    M manifest = getManifestFromReader(reader, objectMapper);

    // Validate the manifest and return it.
    validateManifest(manifest);
    return manifest;
}

From source file:org.geoserver.notification.geonode.GeoNodeJsonEncoder.java

@Override
public byte[] encode(Notification notification) throws Exception {
    byte[] ret = null;

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"));
    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    KombuMessage message = new KombuMessage();

    message.setId(new UID().toString());
    message.setType(notification.getType() != null ? notification.getType().name() : null);
    message.setAction(notification.getAction() != null ? notification.getAction().name() : null);
    message.setTimestamp(new Date());
    message.setUser(notification.getUser());
    message.setOriginator(InetAddress.getLocalHost().getHostAddress());
    message.setProperties(notification.getProperties());
    if (notification.getObject() instanceof NamespaceInfo) {
        NamespaceInfo obj = (NamespaceInfo) notification.getObject();
        KombuNamespaceInfo source = new KombuNamespaceInfo();
        source.setId(obj.getId());//ww  w . j ava 2 s.  c o  m
        source.setType("NamespaceInfo");
        source.setName(obj.getName());
        source.setNamespaceURI(obj.getURI());
        message.setSource(source);
    }
    if (notification.getObject() instanceof WorkspaceInfo) {
        WorkspaceInfo obj = (WorkspaceInfo) notification.getObject();
        KombuWorkspaceInfo source = new KombuWorkspaceInfo();
        source.setId(obj.getId());
        source.setType("WorkspaceInfo");
        source.setName(obj.getName());
        source.setNamespaceURI("");
        message.setSource(source);
    }
    if (notification.getObject() instanceof LayerInfo) {
        LayerInfo obj = (LayerInfo) notification.getObject();
        KombuLayerInfo source = new KombuLayerInfo();
        source.setId(obj.getId());
        source.setType("LayerInfo");
        source.setName(obj.getName());
        source.setResourceType(obj.getType() != null ? obj.getType().name() : "");
        BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("name");
        Collection<String> styleNames = CollectionUtils.collect(obj.getStyles(), transformer);
        source.setStyles(StringUtils.join(styleNames.toArray()));
        source.setDefaultStyle(obj.getDefaultStyle() != null ? obj.getDefaultStyle().getName() : "");
        ResourceInfo res = obj.getResource();
        source.setWorkspace(res.getStore() != null
                ? res.getStore().getWorkspace() != null ? res.getStore().getWorkspace().getName() : ""
                : "");
        if (res.getNativeBoundingBox() != null) {
            source.setBounds(new Bounds(res.getNativeBoundingBox()));
        }
        if (res.getLatLonBoundingBox() != null) {
            source.setGeographicBunds(new Bounds(res.getLatLonBoundingBox()));
        }
        message.setSource(source);
    }
    if (notification.getObject() instanceof LayerGroupInfo) {
        LayerGroupInfo obj = (LayerGroupInfo) notification.getObject();
        KombuLayerGroupInfo source = new KombuLayerGroupInfo();
        source.setId(obj.getId());
        source.setType("LayerGroupInfo");
        source.setName(obj.getName());
        source.setWorkspace(obj.getWorkspace() != null ? obj.getWorkspace().getName() : "");
        source.setMode(obj.getType().name());
        String rootStyle = obj.getRootLayerStyle() != null ? obj.getRootLayerStyle().getName() : "";
        source.setRootLayerStyle(rootStyle);
        source.setRootLayer(obj.getRootLayer() != null ? obj.getRootLayer().getPath() : "");
        for (PublishedInfo pl : obj.getLayers()) {
            KombuLayerSimpleInfo kl = new KombuLayerSimpleInfo();
            if (pl instanceof LayerInfo) {
                LayerInfo li = (LayerInfo) pl;
                kl.setName(li.getName());
                String lstyle = li.getDefaultStyle() != null ? li.getDefaultStyle().getName() : "";
                if (!lstyle.equals(rootStyle)) {
                    kl.setStyle(lstyle);
                }
                source.addLayer(kl);
            }
        }
        message.setSource(source);
    }
    if (notification.getObject() instanceof ResourceInfo) {
        ResourceInfo obj = (ResourceInfo) notification.getObject();
        KombuResourceInfo source = null;
        if (notification.getObject() instanceof FeatureTypeInfo) {
            source = new KombuFeatureTypeInfo();
            source.setType("FeatureTypeInfo");
        }
        if (notification.getObject() instanceof CoverageInfo) {
            source = new KombuCoverageInfo();
            source.setType("CoverageInfo");
        }
        if (notification.getObject() instanceof WMSLayerInfo) {
            source = new KombuWMSLayerInfo();
            source.setType("WMSLayerInfo");
        }
        if (source != null) {
            source.setId(obj.getId());
            source.setName(obj.getName());
            source.setWorkspace(obj.getStore() != null
                    ? obj.getStore().getWorkspace() != null ? obj.getStore().getWorkspace().getName() : ""
                    : "");
            source.setNativeName(obj.getNativeName());
            source.setStore(obj.getStore() != null ? obj.getStore().getName() : "");
            if (obj.getNativeBoundingBox() != null) {
                source.setGeographicBunds(new Bounds(obj.getNativeBoundingBox()));
            }
            if (obj.boundingBox() != null) {
                source.setBounds(new Bounds(obj.boundingBox()));
            }
        }
        message.setSource(source);
    }
    if (notification.getObject() instanceof StoreInfo) {
        StoreInfo obj = (StoreInfo) notification.getObject();
        KombuStoreInfo source = new KombuStoreInfo();
        source.setId(obj.getId());
        source.setType("StoreInfo");
        source.setName(obj.getName());
        source.setWorkspace(obj.getWorkspace() != null ? obj.getWorkspace().getName() : "");
        message.setSource(source);
    }
    ret = mapper.writeValueAsBytes(message);
    return ret;

}

From source file:org.openrepose.powerfilter.PowerFilterChain.java

private String convertPojoToJsonString(Object object) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); //http://stackoverflow.com/a/8395924

    return objectMapper.writeValueAsString(object);
}

From source file:org.verdictdb.core.scrambling.ScrambleMeta.java

public String toJsonString() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    String jsonString;/*from  www .  java2 s . c o m*/
    try {
        jsonString = objectMapper.writeValueAsString(this);
        return jsonString;
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return null;
    }
}