All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.xlcloud.openstack.model.heat.serialization.OutputDeserializer Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2012 AMG.lab, a Bull Group Company
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.xlcloud.openstack.model.heat.serialization;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Custom deserializer for template outputs. If the received value is a String,
 * it is returned unmodified. If it's a JSON object it is converted to a String.
 * 
 * @author Krzysztof Szafrański, AMG.net
 */
public class OutputDeserializer extends JsonDeserializer {

    private static final Logger LOG = Logger.getLogger(OutputDeserializer.class);
    
    /** {@inheritDoc} */
    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        try {
            boolean isUnwrappingRootValue = ctxt.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE); 
            ObjectMapper mapper = (ObjectMapper) jp.getCodec();
            mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
            
            JsonToken currentToken = jp.getCurrentToken();
            String result = JsonToken.VALUE_STRING.equals(currentToken) ? jp.getText() : new JSONObject(jp.readValueAsTree().toString()).toString(2);
            
            mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, isUnwrappingRootValue);
            return result;
        } catch (JSONException e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy