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

com.sap.cloud.sdk.result.GsonResultElementFactory Maven / Gradle / Ivy

/*
 * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
 */

package com.sap.cloud.sdk.result;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nullable;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;

import lombok.Data;

/**
 * Factory implementation that creates a {@code ResultElement}, based on a given {@code JsonElement}.
 */
@Data
public class GsonResultElementFactory implements ResultElementFactory
{
    protected final GsonBuilder gsonBuilder;

    protected ResultPrimitive newPrimitive( final JsonElement resultElement )
    {
        return new GsonResultPrimitive(resultElement.getAsJsonPrimitive());
    }

    protected ResultObject newObject( final JsonElement resultElement )
    {
        return new GsonResultObject(resultElement.getAsJsonObject(), this);
    }

    protected ResultCollection newCollection( final JsonElement resultElement )
    {
        final List resultElements = new ArrayList<>();

        for( final JsonElement jsonElement : resultElement.getAsJsonArray() ) {
            resultElements.add(create(jsonElement));
        }

        return new DefaultResultCollection(resultElements);
    }

    /**
     * {@inheritDoc}
     */
    @Nullable
    @Override
    public ResultElement create( @Nullable final JsonElement resultElement )
        throws IllegalArgumentException
    {
        if( resultElement == null ) {
            return null;
        }

        if( resultElement.isJsonPrimitive() ) {
            return newPrimitive(resultElement);
        }

        if( resultElement.isJsonObject() ) {
            return newObject(resultElement);
        }

        if( resultElement.isJsonArray() ) {
            return newCollection(resultElement);
        }

        throw new IllegalArgumentException(
            "Failed to convert "
                + JsonElement.class.getSimpleName()
                + " "
                + resultElement
                + " to instance of "
                + ResultElement.class.getSimpleName()
                + ".");
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy