org.apache.streams.converter.TypeConverterUtil.java Source code

Java tutorial

Introduction

Here is the source code for org.apache.streams.converter.TypeConverterUtil.java

Source

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 *
 *   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.apache.streams.converter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.streams.jackson.StreamsJacksonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * TypeConverterUtil supports TypeConverterProcessor in converting between String json and
 * jackson-compatible POJO objects
 */
public class TypeConverterUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(TypeConverterUtil.class);

    public static Object convert(Object object, Class outClass) {
        return TypeConverterUtil.convert(object, outClass, StreamsJacksonMapper.getInstance());
    }

    public static Object convert(Object object, Class outClass, ObjectMapper mapper) {
        ObjectNode node = null;
        Object outDoc = null;
        if (object instanceof String) {
            try {
                node = mapper.readValue((String) object, ObjectNode.class);
            } catch (IOException e) {
                LOGGER.warn(e.getMessage());
                LOGGER.warn(object.toString());
            }
        } else {
            node = mapper.convertValue(object, ObjectNode.class);
        }

        if (node != null) {
            try {
                if (outClass == String.class)
                    outDoc = mapper.writeValueAsString(node);
                else
                    outDoc = mapper.convertValue(node, outClass);

            } catch (Throwable e) {
                LOGGER.warn(e.getMessage());
                LOGGER.warn(node.toString());
            }
        }

        return outDoc;
    }
}