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

org.eclipse.yasson.internal.model.customization.PropertyOrdering Maven / Gradle / Ivy

/*
 * Copyright (c) 2016, 2020 Oracle and/or its affiliates. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0,
 * or the Eclipse Distribution License v. 1.0 which is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
 */

package org.eclipse.yasson.internal.model.customization;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

import jakarta.json.bind.JsonbConfig;
import jakarta.json.bind.config.PropertyOrderStrategy;

import org.eclipse.yasson.internal.model.ClassModel;
import org.eclipse.yasson.internal.model.PropertyModel;

/**
 * Order properties in bean object. {@link jakarta.json.bind.annotation.JsonbPropertyOrder} have always precedence.
 * If configured with {@link JsonbConfig} provided property order strategy will be used.
 */
public class PropertyOrdering {

    private final Consumer> propertyOrderStrategy;

    /**
     * Creates a new instance.
     *
     * @param propertyOrderStrategy Property order strategy. Must be not null.
     */
    public PropertyOrdering(Consumer> propertyOrderStrategy) {
        this.propertyOrderStrategy = Objects.requireNonNull(propertyOrderStrategy);
    }

    /**
     * Sorts class properties either, by class {@link jakarta.json.bind.annotation.JsonbPropertyOrder} annotation,
     * or by {@link PropertyOrderStrategy} if set in {@link JsonbConfig}.
     *
     * @param properties Properties to sort.
     * @param classModel Class model.
     * @return Sorted list of properties.
     */
    public List orderProperties(List properties, ClassModel classModel) {
        Map byReadName = new HashMap<>();
        properties.forEach(propertyModel -> byReadName.put(propertyModel.getPropertyName(), propertyModel));

        String[] order = classModel.getClassCustomization().getPropertyOrder();
        List sortedProperties = new ArrayList<>();
        if (order != null) {
            //if @JsonbPropertyOrder annotation is defined on a class
            for (String propName : order) {
                final PropertyModel remove = byReadName.remove(propName);
                if (remove != null) {
                    sortedProperties.add(remove);
                }
            }
        }

        List readNamesToSort = new ArrayList<>(byReadName.values());
        propertyOrderStrategy.accept(readNamesToSort);
        sortedProperties.addAll(readNamesToSort);
        return sortedProperties;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy