Example usage for com.fasterxml.jackson.databind ObjectMapper writerWithView

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writerWithView

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writerWithView.

Prototype

public ObjectWriter writerWithView(Class<?> serializationView) 

Source Link

Document

Factory method for constructing ObjectWriter that will serialize objects using specified JSON View (filter).

Usage

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

private void handleMethodCallsSequential(List<ExtDirectRequest> directRequests, HttpServletRequest request,
        HttpServletResponse response, Locale locale) throws IOException {
    List<Object> directResponses = new ArrayList<Object>(directRequests.size());
    boolean streamResponse = this.configurationService.getConfiguration().isStreamResponse();

    ObjectMapper objectMapper = this.configurationService.getJsonHandler().getMapper();

    for (ExtDirectRequest directRequest : directRequests) {
        ExtDirectResponse directResponse = handleMethodCall(directRequest, request, response, locale);
        streamResponse = streamResponse || directResponse.isStreamResponse();
        Class<?> jsonView = directResponse.getJsonView();
        if (jsonView == null) {
            directResponses.add(directResponse);
        } else {/*from w w w  .j  a v a 2  s  .  c o  m*/
            String jsonResult = objectMapper.writerWithView(jsonView)
                    .writeValueAsString(directResponse.getResult());
            directResponses.add(new ExtDirectResponseRaw(directResponse, jsonResult));
        }
    }

    writeJsonResponse(response, directResponses, null, streamResponse);
}

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

@SuppressWarnings("resource")
public void writeJsonResponse(HttpServletResponse response, Object responseObject, Class<?> jsonView,
        boolean streamResponse, boolean isMultipart) throws IOException {

    ObjectMapper objectMapper = this.configurationService.getJsonHandler().getMapper();

    if (isMultipart) {
        response.setContentType(RouterController.TEXT_HTML.toString());
        response.setCharacterEncoding(RouterController.TEXT_HTML.getCharset().name());

        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        bos.write("<html><body><textarea>".getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        String responseJson;//from w  ww  .ja v  a  2s .c  om
        if (jsonView == null) {
            responseJson = objectMapper.writeValueAsString(responseObject);
        } else {
            responseJson = objectMapper.writerWithView(jsonView).writeValueAsString(responseObject);
        }

        responseJson = responseJson.replace("&quot;", "\\&quot;");
        bos.write(responseJson.getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        String frameDomain = this.configurationService.getConfiguration().getFrameDomain();
        String frameDomainScript = "";
        if (frameDomain != null) {
            frameDomainScript = String
                    .format(this.configurationService.getConfiguration().getFrameDomainScript(), frameDomain);
        }
        bos.write(("</textarea>" + frameDomainScript + "</body></html>")
                .getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        response.setContentLength(bos.size());
        FileCopyUtils.copy(bos.toByteArray(), response.getOutputStream());
    } else {

        response.setContentType(APPLICATION_JSON.toString());
        response.setCharacterEncoding(APPLICATION_JSON.getCharset().name());

        ServletOutputStream outputStream = response.getOutputStream();

        if (!streamResponse) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(bos, JsonEncoding.UTF8);

            if (jsonView == null) {
                objectMapper.writeValue(jsonGenerator, responseObject);
            } else {
                objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
            }

            response.setContentLength(bos.size());
            outputStream.write(bos.toByteArray());
            jsonGenerator.close();
        } else {
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(outputStream,
                    JsonEncoding.UTF8);
            if (jsonView == null) {
                objectMapper.writeValue(jsonGenerator, responseObject);
            } else {
                objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
            }
            jsonGenerator.close();
        }

        outputStream.flush();
    }
}

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

private void handleMethodCallsConcurrent(List<ExtDirectRequest> directRequests, HttpServletRequest request,
        HttpServletResponse response, Locale locale) throws IOException {

    List<Future<ExtDirectResponse>> futures = new ArrayList<Future<ExtDirectResponse>>(directRequests.size());
    for (ExtDirectRequest directRequest : directRequests) {
        Callable<ExtDirectResponse> callable = createMethodCallCallable(directRequest, request, response,
                locale);/*from  w w  w.  ja  v  a  2s.c o  m*/
        futures.add(this.configurationService.getConfiguration().getBatchedMethodsExecutorService()
                .submit(callable));
    }

    ObjectMapper objectMapper = this.configurationService.getJsonHandler().getMapper();
    List<Object> directResponses = new ArrayList<Object>(directRequests.size());
    boolean streamResponse = this.configurationService.getConfiguration().isStreamResponse();
    for (Future<ExtDirectResponse> future : futures) {
        try {
            ExtDirectResponse directResponse = future.get();
            streamResponse = streamResponse || directResponse.isStreamResponse();
            Class<?> jsonView = directResponse.getJsonView();
            if (jsonView == null) {
                directResponses.add(directResponse);
            } else {
                String jsonResult = objectMapper.writerWithView(jsonView)
                        .writeValueAsString(directResponse.getResult());
                directResponses.add(new ExtDirectResponseRaw(directResponse, jsonResult));
            }
        } catch (InterruptedException e) {
            log.error("Error invoking method", e);
        } catch (ExecutionException e) {
            log.error("Error invoking method", e);
        }
    }
    writeJsonResponse(response, directResponses, null, streamResponse);
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

public static String generateJavascript(ModelBean model, OutputConfig outputConfig) {

    if (!outputConfig.isDebug()) {
        JsCacheKey key = new JsCacheKey(model, outputConfig);

        SoftReference<String> jsReference = jsCache.get(key);
        if (jsReference != null && jsReference.get() != null) {
            return jsReference.get();
        }//from  ww w .j  av a  2  s.c  o  m
    }

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);

    if (!outputConfig.isSurroundApiWithQuotes()) {
        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesExtJs5Mixin.class);
        } else {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesMixin.class);
        }
        mapper.addMixInAnnotations(ApiObject.class, ApiObjectMixin.class);
    } else {
        if (outputConfig.getOutputFormat() != OutputFormat.EXTJS5) {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithApiQuotesMixin.class);
        }
    }

    Map<String, Object> modelObject = new LinkedHashMap<String, Object>();
    modelObject.put("extend", model.getExtend());

    if (!model.getAssociations().isEmpty()) {
        Set<String> usesClasses = new HashSet<String>();
        for (AbstractAssociation association : model.getAssociations()) {
            usesClasses.add(association.getModel());
        }

        usesClasses.remove(model.getName());

        if (!usesClasses.isEmpty()) {
            modelObject.put("uses", usesClasses);
        }
    }

    Map<String, Object> configObject = new LinkedHashMap<String, Object>();
    ProxyObject proxyObject = new ProxyObject(model, outputConfig);

    Map<String, ModelFieldBean> fields = model.getFields();
    Set<String> requires = new HashSet<String>();

    if (!model.getValidations().isEmpty() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        requires = addValidatorsToField(fields, model.getValidations());
    }

    if (proxyObject.hasContent() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        requires.add("Ext.data.proxy.Direct");
    }

    if (StringUtils.hasText(model.getIdentifier()) && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        if ("sequential".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Sequential");
        } else if ("uuid".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Uuid");
        } else if ("negative".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Negative");
        }
    }

    if (requires != null && !requires.isEmpty()) {
        configObject.put("requires", requires);
    }

    if (StringUtils.hasText(model.getIdentifier())) {
        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
                || outputConfig.getOutputFormat() == OutputFormat.TOUCH2) {
            configObject.put("identifier", model.getIdentifier());
        } else {
            configObject.put("idgen", model.getIdentifier());
        }
    }

    if (StringUtils.hasText(model.getIdProperty()) && !model.getIdProperty().equals("id")) {
        configObject.put("idProperty", model.getIdProperty());
    }

    if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
            && StringUtils.hasText(model.getVersionProperty())) {
        configObject.put("versionProperty", model.getVersionProperty());
    }

    if (StringUtils.hasText(model.getClientIdProperty())) {

        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
                || outputConfig.getOutputFormat() == OutputFormat.EXTJS4) {
            configObject.put("clientIdProperty", model.getClientIdProperty());
        } else if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2
                && !"clientId".equals(model.getClientIdProperty())) {
            configObject.put("clientIdProperty", model.getClientIdProperty());
        }
    }

    for (ModelFieldBean field : fields.values()) {
        field.updateTypes(outputConfig);
    }

    List<Object> fieldConfigObjects = new ArrayList<Object>();
    for (ModelFieldBean field : fields.values()) {
        if (field.hasOnlyName(outputConfig)) {
            fieldConfigObjects.add(field.getName());
        } else {
            fieldConfigObjects.add(field);
        }
    }
    configObject.put("fields", fieldConfigObjects);

    if (!model.getAssociations().isEmpty()) {
        configObject.put("associations", model.getAssociations());
    }

    if (!model.getValidations().isEmpty() && !(outputConfig.getOutputFormat() == OutputFormat.EXTJS5)) {
        configObject.put("validations", model.getValidations());
    }

    if (proxyObject.hasContent()) {
        configObject.put("proxy", proxyObject);
    }

    if (outputConfig.getOutputFormat() == OutputFormat.EXTJS4
            || outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        modelObject.putAll(configObject);
    } else {
        modelObject.put("config", configObject);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Ext.define(\"").append(model.getName()).append("\",");
    if (outputConfig.isDebug()) {
        sb.append("\n");
    }

    String configObjectString;
    Class<?> jsonView = JsonViews.ExtJS4.class;
    if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2) {
        jsonView = JsonViews.Touch2.class;
    } else if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        jsonView = JsonViews.ExtJS5.class;
    }

    try {
        if (outputConfig.isDebug()) {
            configObjectString = mapper.writerWithDefaultPrettyPrinter().withView(jsonView)
                    .writeValueAsString(modelObject);
        } else {
            configObjectString = mapper.writerWithView(jsonView).writeValueAsString(modelObject);
        }

    } catch (JsonGenerationException e) {
        throw new RuntimeException(e);
    } catch (JsonMappingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    sb.append(configObjectString);
    sb.append(");");

    String result = sb.toString();

    if (outputConfig.isUseSingleQuotes()) {
        result = result.replace('"', '\'');
    }

    if (!outputConfig.isDebug()) {
        jsCache.put(new JsCacheKey(model, outputConfig), new SoftReference<String>(result));
    }
    return result;
}