Example usage for com.fasterxml.jackson.core JsonGenerator writeString

List of usage examples for com.fasterxml.jackson.core JsonGenerator writeString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonGenerator writeString.

Prototype

public abstract void writeString(SerializableString text) throws IOException, JsonGenerationException;

Source Link

Document

Method similar to #writeString(String) , but that takes SerializableString which can make this potentially more efficient to call as generator may be able to reuse quoted and/or encoded representation.

Usage

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private void writePossiblePropertyValues(JsonGenerator jgen, String currentVocab,
        ActionInputParameter actionInputParameter, Object[] possiblePropertyValues) throws IOException {
    // Enable the following to list possible values.
    // Problem: how to express individuals only for certain hydra:options
    // not all hydra:options should be taken as uris, sometimes they might be just literals
    // how to make that clear to the client?
    // maybe we must write them out for options
    //        if (possiblePropertyValues.length > 0) {
    //            jgen.writeArrayFieldStart("hydra:option");
    ///*  www .java2s. c  o m*/
    //            for (Object possibleValue : possiblePropertyValues) {
    //                // TODO: apply "hydra:option" : { "@type": "@vocab"} to context for enums
    //                writeScalarValue(jgen, possibleValue, actionInputParameter.getParameterType());
    //            }
    //            jgen.writeEndArray();
    //        }

    if (actionInputParameter.isArrayOrCollection()) {
        jgen.writeBooleanField(getPropertyOrClassNameInVocab(currentVocab, "multipleValues",
                JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"), true);
    }

    //  valueRequired (hard to say, using @Access on Event is for all update requests - or make
    //     specific request beans for different
    //     purposes rather than always passing an instance of e.g. Event?)
    //       -> update is a different use case than create - or maybe have an @Requires("eventStatus")
    //          annotation alongside requestBody to tell which attributes are required or writable, and use Requires over
    //          bean structure, where ctor with least length of args is required and setters are supported
    //          but optional? The bean structure does say what is writable for updates, but not what is required for creation. Right now setters are supportedProperties. For creation we would have to add constructor arguments as supportedProperties.
    //  (/) defaultValue (pre-filled value, e.g. list of selected items for option)
    //  valueName (for iri templates only)
    //  (/) readonlyValue (true for final public field or absence of setter, send fixed value like hidden field?) -> use hydra:readable, hydra:writable
    //  (/) multipleValues
    //  (/) valueMinLength
    //  (/) valueMaxLength
    //  (/) valuePattern
    //  minValue (DateTime support)
    //  maxValue (DateTime support)
    //  (/) stepValue
    final Map<String, Object> inputConstraints = actionInputParameter.getInputConstraints();

    if (actionInputParameter.hasCallValue()) {
        if (actionInputParameter.isArrayOrCollection()) {
            Object[] callValues = actionInputParameter.getCallValues();
            Class<?> componentType = callValues.getClass().getComponentType();
            // only write defaultValue for array of scalars
            if (DataType.isScalar(componentType)) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue",
                        JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
                jgen.writeStartArray();
                for (Object callValue : callValues) {
                    writeScalarValue(jgen, callValue, componentType);
                }
                jgen.writeEndArray();
            }
        } else {
            jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue",
                    JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));

            writeScalarValue(jgen, actionInputParameter.getCallValueFormatted(),
                    actionInputParameter.getNestedParameterType());
        }
    }

    if (!inputConstraints.isEmpty()) {
        final List<String> keysToAppendValue = Arrays.asList(ActionInputParameter.MAX, ActionInputParameter.MIN,
                ActionInputParameter.STEP);
        for (String keyToAppendValue : keysToAppendValue) {
            final Object constraint = inputConstraints.get(keyToAppendValue);
            if (constraint != null) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, keyToAppendValue + "Value",
                        JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
                jgen.writeNumber(constraint.toString());
            }
        }

        final List<String> keysToPrependValue = Arrays.asList(ActionInputParameter.MAX_LENGTH,
                ActionInputParameter.MIN_LENGTH, ActionInputParameter.PATTERN);
        for (String keyToPrependValue : keysToPrependValue) {
            final Object constraint = inputConstraints.get(keyToPrependValue);
            if (constraint != null) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab,
                        "value" + StringUtils.capitalize(keyToPrependValue),
                        JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
                if (ActionInputParameter.PATTERN.equals(keyToPrependValue)) {
                    jgen.writeString(constraint.toString());
                } else {
                    jgen.writeNumber(constraint.toString());
                }
            }
        }

    }

}

From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java

private void writePossiblePropertyValues(JsonGenerator jgen, String currentVocab,
        ActionInputParameter actionInputParameter, @SuppressWarnings("unused") Object[] possiblePropertyValues)
        throws IOException {
    // Enable the following to list possible values.
    // Problem: how to express individuals only for certain hydra:options
    // not all hydra:options should be taken as uris, sometimes they might be just literals
    // how to make that clear to the client?
    // maybe we must write them out for options
    //        if (possiblePropertyValues.length > 0) {
    //            jgen.writeArrayFieldStart("hydra:option");
    ///*from w w w . ja  v a2  s  .  c om*/
    //            for (Object possibleValue : possiblePropertyValues) {
    //                // TODO: apply "hydra:option" : { "@type": "@vocab"} to context for enums
    //                writeScalarValue(jgen, possibleValue, rootParameter.getParameterType());
    //            }
    //            jgen.writeEndArray();
    //        }

    if (actionInputParameter.isArrayOrCollection()) {
        jgen.writeBooleanField(getPropertyOrClassNameInVocab(currentVocab, "multipleValues",
                LdContextFactory.HTTP_SCHEMA_ORG, "schema:"), true);
    }

    //  valueRequired (hard to say, using @Access on Event is for all update requests - or make
    //     specific request beans for different
    //     purposes rather than always passing an instance of e.g. Event?)
    //       -> update is a different use case than create - or maybe have an @Requires("eventStatus")
    //          annotation alongside requestBody to tell which attributes are required or writable, and use
    // Requires over
    //          bean structure, where ctor with least length of args is required and setters are supported
    //          but optional? The bean structure does say what is writable for updates, but not what is required
    // for creation. Right now setters are supportedProperties. For creation we would have to add constructor
    // arguments as supportedProperties.
    //  (/) defaultValue (pre-filled value, e.g. list of selected items for option)
    //  valueName (for iri templates only)
    //  (/) readonlyValue (true for final public field or absence of setter, send fixed value like hidden field?)
    // -> use hydra:readable, hydra:writable
    //  (/) multipleValues
    //  (/) valueMinLength
    //  (/) valueMaxLength
    //  (/) valuePattern
    //  minValue (DateTime support)
    //  maxValue (DateTime support)
    //  (/) stepValue
    final Map<String, Object> inputConstraints = actionInputParameter.getInputConstraints();

    if (actionInputParameter.hasValue()) {
        if (actionInputParameter.isArrayOrCollection()) {
            Object[] callValues = actionInputParameter.getValues();
            Class<?> componentType = callValues.getClass().getComponentType();
            // only write defaultValue for array of scalars
            if (DataType.isSingleValueType(componentType)) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue",
                        LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
                jgen.writeStartArray();
                for (Object callValue : callValues) {
                    writeScalarValue(jgen, callValue, componentType);
                }
                jgen.writeEndArray();
            }
        } else {
            jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue",
                    LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));

            writeScalarValue(jgen, actionInputParameter.getValue(), actionInputParameter.getParameterType());
        }
    }

    if (!inputConstraints.isEmpty()) {
        final List<String> keysToAppendValue = Arrays.asList(Input.MAX, Input.MIN, Input.STEP);
        for (String keyToAppendValue : keysToAppendValue) {
            final Object constraint = inputConstraints.get(keyToAppendValue);
            if (constraint != null) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, keyToAppendValue + "Value",
                        LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
                jgen.writeNumber(constraint.toString());
            }
        }

        final List<String> keysToPrependValue = Arrays.asList(Input.MAX_LENGTH, Input.MIN_LENGTH,
                Input.PATTERN);
        for (String keyToPrependValue : keysToPrependValue) {
            final Object constraint = inputConstraints.get(keyToPrependValue);
            if (constraint != null) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab,
                        "value" + StringUtils.capitalize(keyToPrependValue), LdContextFactory.HTTP_SCHEMA_ORG,
                        "schema:"));
                if (Input.PATTERN.equals(keyToPrependValue)) {
                    jgen.writeString(constraint.toString());
                } else {
                    jgen.writeNumber(constraint.toString());
                }
            }
        }

    }

}

From source file:org.openiot.security.oauth.OAuth20PermissionController.java

@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {

    final String clientId = request.getParameter(OAuthConstants.CLIENT_ID);
    log.debug("clientId : {}", clientId);
    final String accessToken = request.getParameter(OAuthConstants.ACCESS_TOKEN);
    log.debug("accessToken : {}", accessToken);

    final String callerClientId = request.getParameter("caller_client_id");
    log.debug("callerClientId : {}", callerClientId);
    final String callerAccessToken = request.getParameter("caller_access_token");
    log.debug("callerAccessToken : {}", callerAccessToken);

    final JsonFactory jsonFactory = new JsonFactory();
    final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(response.getWriter());

    response.setContentType("application/json");

    // accessToken is required
    if (StringUtils.isBlank(accessToken)) {
        log.error("missing accessToken");
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", OAuthConstants.MISSING_ACCESS_TOKEN);
        jsonGenerator.writeEndObject();/*from ww  w. jav  a  2 s  . c om*/
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // caller accessToken is required
    if (StringUtils.isBlank(callerAccessToken)) {
        log.error("missing caller accessToken");
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", "missing_callerAccessToken");
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // clientId is required
    if (StringUtils.isBlank(clientId)) {
        log.error("missing clientId");
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", MISSING_CLIENT_ID);
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // caller clientId is required
    if (StringUtils.isBlank(callerClientId)) {
        log.error("missing clientId");
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", "missing_callerClientId");
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // get ticket granting ticket
    final TicketGrantingTicket ticketGrantingTicket = (TicketGrantingTicket) this.ticketRegistry
            .getTicket(accessToken);
    if (ticketGrantingTicket == null || ticketGrantingTicket.isExpired()) {
        log.error("expired accessToken : {}", accessToken);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", OAuthConstants.EXPIRED_ACCESS_TOKEN);
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // get ticket granting ticket for the caller
    final TicketGrantingTicket callerTicketGrantingTicket = (TicketGrantingTicket) this.ticketRegistry
            .getTicket(callerAccessToken);
    if (callerTicketGrantingTicket == null || callerTicketGrantingTicket.isExpired()) {
        log.error("expired accessToken : {}", callerAccessToken);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", OAuthConstants.EXPIRED_ACCESS_TOKEN + "_for_caller");
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // name of the CAS service
    final Collection<RegisteredService> services = servicesManager.getAllServices();
    RegisteredService service = null;
    for (final RegisteredService aService : services) {
        if (StringUtils.equals(aService.getName(), clientId)) {
            service = aService;
            break;
        }
    }

    if (service == null) {
        log.error("nonexistent clientId : {}", clientId);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", NONEXISTENT_CLIENT_ID);
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // TODO: check if the TGT is granted to the client?!
    //      final TicketGrantingTicket rawTicket = ((AbstractDistributedTicketRegistry.TicketGrantingTicketDelegator)ticketGrantingTicket).getTicket();
    //      final Field servicesField = rawTicket.getClass().getDeclaredField("services");
    //      servicesField.setAccessible(true);
    //      HashMap<String, Service> servicesMap = new HashMap<String, Service>();
    //      servicesMap = (HashMap<String, Service>) servicesField.get(rawTicket);
    //      log.error("ServiceMaps is empty ? {}", servicesMap.isEmpty());
    //      for(Map.Entry<String, Service> entry : servicesMap.entrySet()){
    //         AbstractWebApplicationService webAppService = (AbstractWebApplicationService) entry.getValue();
    //         log.error("Service for ticket {} is {}", rawTicket.getId(), webAppService.getId());
    //      }
    //      if (!servicesMap.containsKey(service.getId()) || !servicesMap.get(service.getId()).equals(service)) {
    //         log.error("Ticket is not granted to client : {}", clientId);
    //         jsonGenerator.writeStartObject();
    //         jsonGenerator.writeStringField("error", TICKET_NOT_GRANTED);
    //         jsonGenerator.writeEndObject();
    //         jsonGenerator.close();
    //         response.flushBuffer();
    //         return null;
    //      }

    // name of the CAS service for caller
    RegisteredService callerService = null;
    for (final RegisteredService aService : services) {
        if (StringUtils.equals(aService.getName(), callerClientId)) {
            callerService = aService;
            break;
        }
    }

    if (callerService == null) {
        log.error("nonexistent caller clientId : {}", callerClientId);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", NONEXISTENT_CLIENT_ID + "for_caller");
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    final Principal principal = ticketGrantingTicket.getAuthentication().getPrincipal();
    final Map<String, Set<String>> permissions = extractPermissions(callerService.getId(), principal.getId());

    jsonGenerator.writeStartObject();
    jsonGenerator.writeStringField(CasWrapperProfile.ID, principal.getId());

    jsonGenerator.writeArrayFieldStart("role_permissions");

    for (final String roleName : permissions.keySet()) {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeArrayFieldStart(roleName);

        for (final String permission : permissions.get(roleName))
            jsonGenerator.writeString(permission);

        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
    }

    jsonGenerator.writeEndArray();
    jsonGenerator.writeEndObject();
    jsonGenerator.close();
    response.flushBuffer();

    return null;
}