<?xml version="1.0" encoding="UTF-8"?>
<!--
~ ============LICENSE_START=======================================================
- ~ Copyright (C) 2025 OpenInfra Foundation Europe. All rights reserved
+ ~ Copyright (C) 2025-2026 OpenInfra Foundation Europe. All rights reserved
~ ================================================================================
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
<version.httpcore>5.3.4</version.httpcore>
<version.io.prometheus>1.3.6</version.io.prometheus>
<version.jackson>2.18.3</version.jackson>
- <version.jacoco>0.8.13</version.jacoco>
+ <version.jacoco>0.8.14</version.jacoco>
<version.jaxb>4.0.5</version.jaxb>
<version.jersey>3.1.10</version.jersey>
<version.jetty>12.0.22</version.jetty>
--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.sql/java.sql=ALL-UNNAMED
-XX:+EnableDynamicAgentLoading
+ -XX:TieredStopAtLevel=3
+ -XX:ReservedCodeCacheSize=256m
+ -XX:ProfiledCodeHeapSize=128m
+ -XX:NonProfiledCodeHeapSize=96m
</surefireArgLine>
</properties>
<version>${version.jackson}</version>
</dependency>
<dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>2.12.1</version>
+ <groupId>com.fasterxml.jackson.datatype</groupId>
+ <artifactId>jackson-datatype-jsr310</artifactId>
+ <version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${version.jersey}</version>
</dependency>
+ <dependency>
+ <groupId>org.glassfish.jersey.media</groupId>
+ <artifactId>jersey-media-json-jackson</artifactId>
+ <version>${version.jersey}</version>
+ </dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
- <version>3.5.3</version>
+ <version>3.5.4</version>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<?xml version="1.0" encoding="UTF-8"?>
<!--
============LICENSE_START=======================================================
- Copyright (C) 2021-2025 OpenInfra Foundation Europe. All rights reserved.
+ Copyright (C) 2021-2026 OpenInfra Foundation Europe. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
<artifactId>policy-models</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation.
+ * Copyright (C) 2023,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@AllArgsConstructor
+@NoArgsConstructor
@ToString
public class AcElementDeployAck {
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022-2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2022-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.models.acm.concepts;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@NoArgsConstructor
@Data
@EqualsAndHashCode
+@JsonIgnoreProperties(ignoreUnknown = true)
public class AutomationCompositionDefinition {
@NonNull
package org.onap.policy.clamp.models.acm.document.base;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.validation.constraints.Pattern;
import java.io.Serial;
+import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString;
import org.onap.policy.common.utils.validation.Assertions;
import org.onap.policy.models.base.PfConceptKey;
+import org.onap.policy.models.base.PfKey;
import org.onap.policy.models.base.PfKeyImpl;
@Data
}
@Override
+ @JsonIgnore
public String getId() {
return name + ":" + version;
}
public void setVersion(@NonNull final String version) {
this.version = Assertions.validateStringParameter(VERSION_TOKEN, version, getVersionRegEx());
}
+
+ @Override
+ @JsonIgnore
+ public PfKeyImpl getKey() {
+ return this;
+ }
+
+ @Override
+ @JsonIgnore
+ public List<PfKey> getKeys() {
+ return super.getKeys();
+ }
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022 Nordix Foundation.
+ * Copyright (C) 2022,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.models.acm.document.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serial;
import java.io.Serializable;
import java.util.ArrayList;
@Serial
private static final long serialVersionUID = 1L;
- @SerializedName("valid_values")
+ @JsonProperty("valid_values")
private List<String> validValues;
private String equal;
- @SerializedName("greater_than")
+ @JsonProperty("greater_than")
private String greaterThan;
- @SerializedName("greater_or_equal")
+ @JsonProperty("greater_or_equal")
private String greaterOrEqual;
- @SerializedName("less_than")
+ @JsonProperty("less_than")
private String lessThan;
- @SerializedName("less_or_equal")
+ @JsonProperty("less_or_equal")
private String lessOrEqual;
- @SerializedName("in_range")
+ @JsonProperty("in_range")
private List<String> rangeValues;
public DocToscaConstraint(ToscaConstraint toscaConstraint) {
package org.onap.policy.clamp.models.acm.document.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.io.Serial;
@NotNull
private String version = PfKey.NULL_KEY_VERSION;
- @SerializedName("derived_from")
+ @JsonProperty("derived_from")
private String derivedFrom;
@SuppressWarnings("squid:S1948")
*
* @return a ToscaEntityKey for this entry
*/
+ @JsonIgnore
public ToscaEntityKey getKey() {
return new ToscaEntityKey(name, version);
}
*
* @return a PfConceptKey for this entry
*/
+ @JsonIgnore
public PfConceptKey getConceptKey() {
return new PfConceptKey(name, version);
}
+ @JsonIgnore
public DocConceptKey getDocConceptKey() {
return new DocConceptKey(name, version);
}
@Override
+ @JsonIgnore
public String getDefinedName() {
return (PfKey.NULL_KEY_NAME.equals(name) ? null : name);
}
@Override
+ @JsonIgnore
public String getDefinedVersion() {
return (PfKey.NULL_KEY_VERSION.equals(version) ? null : version);
}
*
* @return the type of the entity or null if it has no type
*/
+ @JsonIgnore
public String getType() {
return null;
}
*
* @return the type of the entity or null if it has no type
*/
+ @JsonIgnore
public String getTypeVersion() {
return null;
}
package org.onap.policy.clamp.models.acm.document.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import java.io.Serial;
import java.io.Serializable;
private String type;
@NotNull
- @SerializedName("type_version")
+ @JsonProperty("type_version")
private String typeVersion;
@SuppressWarnings("squid:S1948")
package org.onap.policy.clamp.models.acm.document.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.io.Serial;
@NotNull
private String type;
- @SerializedName("type_version")
+ @JsonProperty("type_version")
@NotNull
private String typeVersion;
private String description;
- @SerializedName("default")
+ @JsonProperty("default")
@SuppressWarnings("squid:S1948")
private Object defaultValue;
private ToscaProperty.Status status;
private List<@NotNull @Valid DocToscaConstraint> constraints;
- @SerializedName("key_schema")
+ @JsonProperty("key_schema")
@Valid
private DocToscaSchemaDefinition keySchema;
- @SerializedName("entry_schema")
+ @JsonProperty("entry_schema")
@Valid
private DocToscaSchemaDefinition entrySchema;
metadata = PfUtils.mapMap(toscaProperty.getMetadata(), metadataItem -> metadataItem);
}
+ @JsonIgnore
public DocConceptKey getTypeDocConceptKey() {
return new DocConceptKey(type, typeVersion);
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022 Nordix Foundation.
+ * Copyright (C) 2022,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.models.acm.document.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serial;
import java.io.Serializable;
import java.util.List;
@Data
@NoArgsConstructor
+@JsonIgnoreProperties({"typeDocConceptKey"})
public class DocToscaSchemaDefinition
implements PfAuthorative<ToscaSchemaDefinition>, Serializable, Comparable<DocToscaSchemaDefinition> {
private String name;
private String type;
- @SerializedName("type_version")
+ @JsonProperty("type_version")
private String typeVersion;
private String description;
}
}
+ @JsonIgnore
public DocConceptKey getTypeDocConceptKey() {
return new DocConceptKey(type, typeVersion);
}
package org.onap.policy.clamp.models.acm.document.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.io.Serial;
public static final String DEFAULT_NAME = "tosca";
public static final String DEFAULT_VERSION = "1.0.0";
- @SerializedName("tosca_definitions_version")
+ @JsonProperty("tosca_definitions_version")
@NotBlank
private String toscaDefinitionsVersion;
- @SerializedName("data_types")
+ @JsonProperty("data_types")
private Map<String, @Valid DocToscaDataType> dataTypes;
- @SerializedName("capability_types")
+ @JsonProperty("capability_types")
private Map<String, @Valid DocToscaCapabilityType> capabilityTypes;
- @SerializedName("node_types")
+ @JsonProperty("node_types")
private Map<String, @Valid DocToscaNodeType> nodeTypes;
- @SerializedName("relationship_types")
+ @JsonProperty("relationship_types")
private Map<String, @Valid DocToscaRelationshipType> relationshipTypes;
- @SerializedName("policy_types")
+ @JsonProperty("policy_types")
private Map<String, @Valid DocToscaPolicyType> policyTypes;
- @SerializedName("topology_template")
+ @JsonProperty("topology_template")
@Valid
private DocToscaTopologyTemplate toscaTopologyTemplate;
super.toAuthorative();
toscaServiceTemplate.setToscaDefinitionsVersion(toscaDefinitionsVersion);
- toscaServiceTemplate.setDataTypes(DocUtil.docMapToMap(dataTypes, DocToscaDataType::toAuthorative));
- toscaServiceTemplate
- .setCapabilityTypes(DocUtil.docMapToMap(capabilityTypes, DocToscaCapabilityType::toAuthorative));
- toscaServiceTemplate
- .setRelationshipTypes(DocUtil.docMapToMap(relationshipTypes, DocToscaRelationshipType::toAuthorative));
- toscaServiceTemplate.setNodeTypes(DocUtil.docMapToMap(nodeTypes, DocToscaNodeType::toAuthorative));
- toscaServiceTemplate.setPolicyTypes(DocUtil.docMapToMap(policyTypes, DocToscaPolicyType::toAuthorative));
+ toscaServiceTemplate.setDataTypes(
+ DocUtil.docMapToMap(dataTypes, DocToscaDataType::toAuthorative));
+ toscaServiceTemplate.setCapabilityTypes(
+ DocUtil.docMapToMap(capabilityTypes, DocToscaCapabilityType::toAuthorative));
+ toscaServiceTemplate.setRelationshipTypes(
+ DocUtil.docMapToMap(relationshipTypes, DocToscaRelationshipType::toAuthorative));
+ toscaServiceTemplate.setNodeTypes(
+ DocUtil.docMapToMap(nodeTypes, DocToscaNodeType::toAuthorative));
+ toscaServiceTemplate.setPolicyTypes(
+ DocUtil.docMapToMap(policyTypes, DocToscaPolicyType::toAuthorative));
if (toscaTopologyTemplate != null) {
toscaServiceTemplate.setToscaTopologyTemplate(toscaTopologyTemplate.toAuthorative());
}
new LinkedHashMap<>());
policyTypes = DocUtil.mapToDocMap(toscaServiceTemplate.getPolicyTypes(), DocToscaPolicyType::new,
- new LinkedHashMap<>());
+ new LinkedHashMap<>());
if (toscaServiceTemplate.getToscaTopologyTemplate() != null) {
toscaTopologyTemplate = new DocToscaTopologyTemplate(toscaServiceTemplate.getToscaTopologyTemplate());
package org.onap.policy.clamp.models.acm.document.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import java.io.Serial;
import java.io.Serializable;
private Map<String, @Valid DocToscaParameter> inputs;
- @SerializedName("node_templates")
+ @JsonProperty("node_templates")
private Map<String, @Valid DocToscaNodeTemplate> nodeTemplates;
private Map<String, @Valid DocToscaPolicy> policies;
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022,2024 Nordix Foundation.
+ * Copyright (C) 2022,2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.models.acm.document.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.ws.rs.core.Response;
import java.io.Serial;
import java.util.LinkedHashMap;
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@ToString
+@JsonIgnoreProperties({"typeDocConceptKey"})
public class DocToscaWithTypeAndStringProperties<T extends ToscaWithTypeAndObjectProperties> extends DocToscaEntity<T> {
@Serial
private static final long serialVersionUID = 1L;
+ @JsonProperty("type")
private String type;
- @SerializedName("type_version")
+ @JsonProperty("type_version")
private String typeVersion;
@SuppressWarnings("squid:S1948")
properties = PfUtils.mapMap(authorativeConcept.getProperties(), x -> x);
}
+ @JsonIgnore
public DocConceptKey getTypeDocConceptKey() {
return new DocConceptKey(type, typeVersion);
}
+
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2023-2024 Nordix Foundation.
+ * Copyright (C) 2023-2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// AutomationCompositionElement.
private Map<UUID, AcElementDeployAck> automationCompositionResultMap = new LinkedHashMap<>();
+ /**
+ * Default constructor for Jackson deserialization.
+ */
+ public AutomationCompositionDeployAck() {
+ super(ParticipantMessageType.AUTOMATION_COMPOSITION_DEPLOY_ACK);
+ }
+
/**
* Constructor for instantiating ParticipantRegisterAck class with message name.
*
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2024 Nordix Foundation.
+ * Copyright (C) 2021-2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.UUID;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
+@NoArgsConstructor
public class ParticipantAckMessage {
// The responseTo field should match the original request id in the request.
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2021-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.models.acm.messages.kafka.participant;
+import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import lombok.AccessLevel;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
+@NoArgsConstructor
public class ParticipantMessage {
@Setter(AccessLevel.NONE)
private ParticipantMessageType messageType;
/**
* Time-stamp, in milliseconds, when the message was created. Defaults to the current time.
*/
+ @JsonFormat(shape = JsonFormat.Shape.STRING)
private Instant timestamp = Instant.now();
/**
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2022 Nordix Foundation.
+ * Copyright (C) 2021-2022,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.models.acm.messages.rest.commissioning;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
import java.util.UUID;
import lombok.Getter;
@Getter
@Setter
@ToString(callSuper = true)
+@JsonIgnoreProperties(ignoreUnknown = true)
public class CommissioningResponse extends SimpleResponse {
private UUID compositionId;
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021, 2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2021, 2025-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
if (dbData == null) {
return new DocToscaServiceTemplate();
}
+ if (dbData.isEmpty()) {
+ return null;
+ }
return decode(dbData, DocToscaServiceTemplate.class);
}
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation.
+ * Copyright (C) 2023,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
private static final String TOSCA_SERVICE_TEMPLATE_YAML = "clamp/acm/pmsh/funtional-pmsh-usecase.yaml";
@Test
- void testCopyContructor() {
+ void testCopyConstructor() {
var acDefinition = new AutomationCompositionDefinition();
acDefinition.setCompositionId(UUID.randomUUID());
var nodeTemplateState = new NodeTemplateState();
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2025-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Map;
var docConceptKey = new DocConceptKey();
assertThatThrownBy(() -> docConceptKey.setName(null)). isInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> docConceptKey.setVersion(null)). isInstanceOf(NullPointerException.class);
+ assertEquals("NULL", docConceptKey.getKey().getName());
+ assertThat(docConceptKey.getKeys()).hasSize(1);
}
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2023-2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2023-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
try {
return YAML_TRANSLATOR.decode(ResourceUtils.getResourceAsStream(path), ToscaServiceTemplate.class);
} catch (CoderException e) {
- fail("Cannot read or decode " + path);
+ fail("Cannot read or decode " + e.getMessage());
return null;
}
}
toscaNodeTemplate.setDerivedFrom("parentNodeTemplate");
toscaNodeTemplate.setDescription("Description of nodeTemplate");
toscaNodeTemplate.setVersion("1.2.3");
+ toscaNodeTemplate.setType("org.onap.policy.clamp.acm.TestNodeType");
+ toscaNodeTemplate.setTypeVersion("1.0.0");
var acDefinition = new AutomationCompositionElementDefinition();
acDefinition.setAcElementDefinitionId(id);
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022 Nordix Foundation.
+ * Copyright (C) 2022,2026 OpenInfra Foundation Europe. All rights reserved..
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.acm.participant.a1pms.models;
-import com.fasterxml.jackson.annotation.JsonGetter;
-import com.fasterxml.jackson.annotation.JsonIgnore;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.DefaultValue;
import lombok.AllArgsConstructor;
import lombok.Data;
-import lombok.Getter;
+import lombok.NoArgsConstructor;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
@Data
@AllArgsConstructor
+@NoArgsConstructor
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class A1PolicyServiceEntity {
@NotNull
- @JsonIgnore
+ @JsonProperty("a1PolicyServiceEntityId")
private ToscaConceptIdentifier a1PolicyServiceEntityId;
@NotNull
- @Getter(onMethod_ = {@JsonGetter(value = "service_id")})
+ @JsonProperty("clientId")
private String clientId;
@NotNull
+ @JsonProperty("callbackUrl")
private String callbackUrl;
@NotNull
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022 Nordix Foundation.
+ * Copyright (C) 2022,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
+import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
+@NoArgsConstructor
public class ConfigurationEntity {
@NotNull
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022,2024 Nordix Foundation.
+ * Copyright (C) 2022,2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.acm.element.handler.messages;
+import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.Instant;
import java.util.UUID;
import lombok.AccessLevel;
* Time-stamp, in milliseconds, when the message was created. Defaults to the
* current time.
*/
+ @JsonFormat(shape = JsonFormat.Shape.STRING)
private Instant timestamp = Instant.now();
/**
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.acm.participant.http.main.models;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
-import jakarta.ws.rs.DefaultValue;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
+import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
+@NoArgsConstructor
public class ConfigRequest {
@NotBlank
private List<ConfigurationEntity> configurationEntities;
@Min(value = 1)
- @DefaultValue("20")
+ @JsonProperty(defaultValue = "20")
private int uninitializedToPassiveTimeout;
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
+import lombok.NoArgsConstructor;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
@Data
@AllArgsConstructor
+@NoArgsConstructor
public class ConfigurationEntity {
@NotNull
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation.
+ * Copyright (C) 2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
+import lombok.NoArgsConstructor;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
@Data
@AllArgsConstructor
+@NoArgsConstructor
public class RestParams {
@NotNull
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation.
+ * Copyright (C) 2023,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
+import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
+@NoArgsConstructor
public class ConfigurationEntity {
@NotNull
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation.
+ * Copyright (C) 2023,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.acm.participant.kserve.models;
-import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
+import lombok.NoArgsConstructor;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
@Data
@AllArgsConstructor
+@NoArgsConstructor
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class KserveInferenceEntity {
@NotNull
- @JsonIgnore
+ @JsonProperty("kserveInferenceEntityId")
private ToscaConceptIdentifier kserveInferenceEntityId;
@NotNull
/*-
* ========================LICENSE_START=================================
- * Copyright (C) 2021 Nordix Foundation. All rights reserved.
+ * Copyright (C) 2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ======================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.Map;
import lombok.Data;
+import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
@Data
@RequiredArgsConstructor
+@NoArgsConstructor
public class ChartInfo {
@NonNull
/*-
* ========================LICENSE_START=================================
- * Copyright (C) 2021 Nordix Foundation. All rights reserved.
+ * Copyright (C) 2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ======================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.acm.participant.kubernetes.models;
import java.util.List;
+import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
+@AllArgsConstructor
+@NoArgsConstructor
public class ChartList {
private List<ChartInfo> charts;
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022, 2024-2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2022, 2024-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
.addHeader("Content-Type", "application/json");
}
if (path.equals("/policy/api/v1/policies") && "POST".equals(request.getMethod())
- && request.getBody().size() < 40) {
+ && request.getBody().size() < 410) {
return new MockResponse().setResponseCode(404);
}
if (path.equals("/policy/api/v1/policies") && "POST".equals(request.getMethod())) {
}
@Test
- void testCreateBabPolicy() {
+ void testCreateBadPolicy() {
var badServiceTemplate = new ToscaServiceTemplate();
assertThrows(WebClientException.class, () -> apiHttpClient.createPolicy(badServiceTemplate));
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2023-2024 Nordix Foundation.
+ * Copyright (C) 2023-2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public static AutomationComposition getTestAutomationComposition() {
var automationComposition = new AutomationComposition();
automationComposition.setInstanceId(UUID.randomUUID());
+ automationComposition.setCompositionId(UUID.randomUUID());
var element = new AutomationCompositionElement();
element.setId(UUID.randomUUID());
automationComposition.setElements(Map.of(element.getId(), element));
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2024-2025 Nordix Foundation.
+ * Copyright (C) 2021-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
verify(publisherFirst, times(1)).active(anyList());
verify(publisherSecond, times(1)).active(anyList());
- var sco = CODER.decode("{messageType:" + TOPIC_FIRST + "}", StandardCoderObject.class);
+ var sco = CODER.decode("{\"messageType\":\"" + TOPIC_FIRST + "\"}", StandardCoderObject.class);
activator.getMsgDispatcher().onTopicEvent(null, "msg", sco);
verify(listenerFirst, times(1)).onTopicEvent(any(), any(), any());
- sco = CODER.decode("{messageType:" + TOPIC_SECOND + "}", StandardCoderObject.class);
+ sco = CODER.decode("{\"messageType\":\"" + TOPIC_SECOND + "\"}", StandardCoderObject.class);
activator.getSyncMsgDispatcher().onTopicEvent(null, "msg", sco);
verify(listenerSecond, times(1)).onTopicEvent(any(), any(), any());
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2025-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
CommonTestData.createAutomationCompositionElementDefinitionList(automationComposition);
var parameters = CommonTestData.getParticipantParameters();
var cacheProvider = new CacheProvider(parameters);
+ assertThat(cacheProvider.getMessagesOnHold()).isEmpty();
cacheProvider.addElementDefinition(compositionId, definitions, revisionIdComposition);
var publisher = mock(ParticipantMessagePublisher.class);
<name>${project.artifactId}</name>
<dependencies>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.datatype</groupId>
+ <artifactId>jackson-datatype-jsr310</artifactId>
+ </dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-
-/**
- * Converter for Double values. By default, GSON treats all Objects that are numbers, as
- * Double. This converts Doubles to Integer or Long, if possible. It converts stand-alone
- * Doubles, as well as those found within Arrays and Maps.
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class DoubleConverter {
-
- /**
- * Performs in-place conversion of all values in a list.
- *
- * @param list the list whose values are to be converted
- */
- public static void convertFromDouble(List<Object> list) {
- if (list == null) {
- return;
- }
-
- List<Object> original = new ArrayList<>(list);
-
- list.clear();
- original.forEach(item -> list.add(convertFromDouble(item)));
- }
-
- /**
- * Performs in-place conversion of all values in a map.
- *
- * @param map the map whose values are to be converted
- */
- public static void convertFromDouble(Map<String, Object> map) {
- if (map == null) {
- return;
- }
-
- Set<Entry<String, Object>> set = map.entrySet();
-
- for (Entry<String, Object> entry : set) {
- entry.setValue(convertFromDouble(entry.getValue()));
- }
- }
-
- /**
- * Converts a value. If the value is a List, then it recursively converts the
- * entries of the List. Likewise with a map, however, the map is converted in place.
- *
- * @param value value to be converted
- * @return the converted value
- */
- @SuppressWarnings({"unchecked"})
- public static Object convertFromDouble(Object value) {
- if (value == null) {
- return value;
- }
-
- if (value instanceof List) {
- convertFromDouble((List<Object>) value);
- return value;
- }
-
- if (value instanceof Map) {
- convertFromDouble((Map<String, Object>) value);
- return value;
- }
-
- if (!(value instanceof Double)) {
- return value;
- }
-
- Double num = (Double) value;
- var longval = num.longValue();
-
- if (Double.compare(num.doubleValue(), longval) != 0) {
- // it isn't integral - return unchanged value
- return value;
- }
-
- // it's integral - determine if it's an integer or a long
- var intval = (int) longval;
-
- if (intval == longval) {
- return intval;
- }
-
- return longval;
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import jakarta.ws.rs.Consumes;
-import jakarta.ws.rs.Produces;
-import jakarta.ws.rs.core.MediaType;
-import jakarta.ws.rs.core.MultivaluedMap;
-import jakarta.ws.rs.ext.MessageBodyReader;
-import jakarta.ws.rs.ext.MessageBodyWriter;
-import jakarta.ws.rs.ext.Provider;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import java.nio.charset.StandardCharsets;
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.OffsetDateTime;
-import java.time.OffsetTime;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import lombok.AccessLevel;
-import lombok.Getter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Provider that serializes and de-serializes JSON via gson.
- */
-@Provider
-@Consumes(MediaType.WILDCARD)
-@Produces(MediaType.WILDCARD)
-public class GsonMessageBodyHandler implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
-
- public static final Logger logger = LoggerFactory.getLogger(GsonMessageBodyHandler.class);
-
- /**
- * Object to be used to serialize and de-serialize.
- */
- @Getter(AccessLevel.PROTECTED)
- private final Gson gson;
-
- /**
- * Constructs the object, using a Gson object that translates Doubles inside of Maps
- * into Integer/Long, where possible.
- */
- public GsonMessageBodyHandler() {
- this(configBuilder(new GsonBuilder()).create());
- }
-
- /**
- * Constructs the object.
- *
- * @param gson the Gson object to be used to serialize and de-serialize
- */
- public GsonMessageBodyHandler(Gson gson) {
- this.gson = gson;
-
- logger.info("Using GSON for REST calls");
- }
-
- /**
- * Configures a builder with the adapters normally used by this handler (e.g., mapper
- * that converts Double to Integer).
- *
- * @param builder builder to be configured
- * @return the configured builder
- */
- public static GsonBuilder configBuilder(GsonBuilder builder) {
- return builder.disableHtmlEscaping().registerTypeAdapterFactory(new MapDoubleAdapterFactory())
- .registerTypeAdapter(Instant.class, new InstantTypeAdapter())
- .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter())
- .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeTypeAdapter())
- .registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter())
- .registerTypeAdapter(OffsetTime.class, new OffsetTimeTypeAdapter())
- .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
- .registerTypeAdapter(ZoneOffset.class, new ZoneOffsetTypeAdapter());
- }
-
- @Override
- public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return canHandle(mediaType);
- }
-
- @Override
- public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return -1;
- }
-
- @Override
- public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
- MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
-
- try (var writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
- Type jsonType = (type.equals(genericType) ? type : genericType);
- gson.toJson(object, jsonType, writer);
- }
- }
-
- @Override
- public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return canHandle(mediaType);
- }
-
- /**
- * Determines if this provider can handle the given media type.
- *
- * @param mediaType the media type of interest
- * @return {@code true} if this provider handles the given media type, {@code false}
- * otherwise
- */
- private boolean canHandle(MediaType mediaType) {
- if (mediaType == null) {
- return true;
- }
-
- String subtype = mediaType.getSubtype();
-
- if ("json".equalsIgnoreCase(subtype) || "javascript".equals(subtype)) {
- return true;
- }
-
- return subtype.endsWith("+json") || "x-json".equals(subtype) || "x-javascript".equals(subtype);
- }
-
- @Override
- public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
- MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
-
- try (var streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
- Type jsonType = (type.equals(genericType) ? type : genericType);
- return gson.fromJson(streamReader, jsonType);
- }
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import com.google.gson.TypeAdapter;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonToken;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import java.time.Instant;
-
-/**
- * GSON Type Adapter for "Instant" fields, that encodes them as milliseconds.
- */
-public class InstantAsMillisTypeAdapter extends TypeAdapter<Instant> {
-
- @Override
- public void write(JsonWriter out, Instant value) throws IOException {
- if (value == null) {
- out.nullValue();
- } else {
- out.value(value.toEpochMilli());
- }
- }
-
- @Override
- public Instant read(JsonReader in) throws IOException {
- if (in.peek() == JsonToken.NULL) {
- in.nextNull();
- return null;
- } else {
- var millis = in.nextLong();
- return Instant.ofEpochMilli(millis);
- }
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import java.time.Instant;
-
-/**
- * GSON Type Adapter for "Instant" fields, that uses the standard ISO_INSTANT formatter.
- */
-public class InstantTypeAdapter extends StringTypeAdapter<Instant> {
-
- /**
- * Constructs an adapter.
- */
- public InstantTypeAdapter() {
- super("date", Instant::parse, Instant::toString);
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import com.google.gson.ExclusionStrategy;
-import com.google.gson.FieldAttributes;
-import com.google.gson.JsonElement;
-import java.lang.reflect.GenericArrayType;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Excludes all fields from serialization/deserialization, if the class is managed.
- */
-public class JacksonExclusionStrategy implements ExclusionStrategy {
-
- /**
- * Classes that are explicitly not managed by the GSON jackson adapters.
- */
- // @formatter:off
- private static final Set<Class<?>> unmanaged = new HashSet<>(Arrays.asList(
- boolean.class,
- byte.class,
- short.class,
- int.class,
- long.class,
- float.class,
- double.class,
- char.class,
- Boolean.class,
- Byte.class,
- Short.class,
- Integer.class,
- Long.class,
- Float.class,
- Double.class,
- Character.class,
- String.class));
- // @formatter:on
-
- /**
- * Classes whose subclasses are explicitly not managed by the GSON jackson adapters.
- */
- // @formatter:off
- private static final Set<Class<?>> unmanagedSuper = new HashSet<>(Arrays.asList(
- GenericArrayType.class,
- Map.class,
- Collection.class,
- JsonElement.class));
- // @formatter:on
-
- @Override
- public boolean shouldSkipField(FieldAttributes attrs) {
- return isManaged(attrs.getDeclaringClass());
- }
-
- @Override
- public boolean shouldSkipClass(Class<?> clazz) {
- return false;
- }
-
- /**
- * Determines if a class is managed by this adapter, which typically means that it is
- * <i>not</i> a generic class such as {@link JsonElement} or some type of collection.
- *
- * @param clazz the class to be examined
- * @return {@code true} if the class is managed by this adapter, {@code false}
- * otherwise
- */
- public static boolean isManaged(Class<?> clazz) {
- if (clazz.isArray() || clazz.isEnum() || clazz.isPrimitive() || unmanaged.contains(clazz)) {
- return false;
- }
-
- for (Class<?> sup : unmanagedSuper) {
- if (sup.isAssignableFrom(clazz)) {
- return false;
- }
- }
-
- return true;
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import com.google.gson.Gson;
-import com.google.gson.TypeAdapter;
-import com.google.gson.TypeAdapterFactory;
-import com.google.gson.reflect.TypeToken;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.List;
-import org.onap.policy.common.gson.internal.ClassWalker;
-import org.onap.policy.common.gson.internal.Deserializer;
-import org.onap.policy.common.gson.internal.FieldDeserializer;
-import org.onap.policy.common.gson.internal.FieldSerializer;
-import org.onap.policy.common.gson.internal.JacksonTypeAdapter;
-import org.onap.policy.common.gson.internal.Serializer;
-
-/**
- * Factory that serializes/deserializes class fields following the normal behavior of
- * jackson. Supports the following annotations:
- * <ul>
- * <li>GsonJsonIgnore</li>
- * <li>GsonJsonProperty</li>
- * </ul>
- *
- * <p>Note: {@link JacksonExclusionStrategy} must also be registered with the gson object.
- */
-public class JacksonFieldAdapterFactory implements TypeAdapterFactory {
-
- @Override
- public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
- Class<? super T> clazz = type.getRawType();
-
- if (!JacksonExclusionStrategy.isManaged(clazz)) {
- return null;
- }
-
- var data = new ClassWalker();
- data.walkClassHierarchy(clazz);
-
- if (data.getInProps(Field.class).isEmpty() && data.getOutProps(Field.class).isEmpty()) {
- // no fields to serialize
- return null;
- }
-
- TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
- List<Serializer> sers = makeSerializers(gson, data);
- List<Deserializer> desers = makeDeserializers(gson, data);
-
- return new JacksonTypeAdapter<>(gson, delegate, sers, desers);
- }
-
- /**
- * Creates a complete list of serializers.
- *
- * @param gson the associated gson object
- * @param data data used to configure the serializers
- * @return a list of all serializers
- */
- private List<Serializer> makeSerializers(Gson gson, ClassWalker data) {
- List<Serializer> ser = new ArrayList<>();
-
- data.getOutProps(Field.class).forEach(field -> ser.add(new FieldSerializer(gson, field)));
-
- return ser;
- }
-
- /**
- * Creates a complete list of deserializers.
- *
- * @param gson the associated gson object
- * @param data data used to configure the deserializers
- * @return a list of all deserializers
- */
- private List<Deserializer> makeDeserializers(Gson gson, ClassWalker data) {
- List<Deserializer> deser = new ArrayList<>();
-
- data.getInProps(Field.class).forEach(field -> deser.add(new FieldDeserializer(gson, field)));
-
- return deser;
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Provider used to serialize and deserialize policy objects via gson using jackson
- * default behaviors and annotations.
- */
-public class JacksonHandler extends GsonMessageBodyHandler {
-
- public static final Logger logger = LoggerFactory.getLogger(JacksonHandler.class);
-
- /**
- * Constructs the object.
- */
- public JacksonHandler() {
- this(configBuilder(new GsonBuilder()).create());
- }
-
- /**
- * Constructs the object.
- *
- * @param gson the Gson object to be used to serialize and de-serialize
- */
- public JacksonHandler(Gson gson) {
- super(gson);
- logger.info("Using GSON with Jackson behaviors for REST calls");
- }
-
- /**
- * Configures a builder with the adapters normally used by this handler (e.g.,
- * adapters for GsonJsonXxx annotations).
- *
- * @param builder builder to be configured
- * @return the configured builder
- */
- public static GsonBuilder configBuilder(GsonBuilder builder) {
- return builder.registerTypeAdapterFactory(new JacksonFieldAdapterFactory())
- .registerTypeAdapterFactory(new JacksonMethodAdapterFactory())
- .registerTypeAdapterFactory(new MapDoubleAdapterFactory())
- .setExclusionStrategies(new JacksonExclusionStrategy())
- .disableHtmlEscaping();
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import com.google.gson.Gson;
-import com.google.gson.TypeAdapter;
-import com.google.gson.TypeAdapterFactory;
-import com.google.gson.reflect.TypeToken;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.onap.policy.common.gson.internal.AnyGetterSerializer;
-import org.onap.policy.common.gson.internal.AnySetterDeserializer;
-import org.onap.policy.common.gson.internal.ClassWalker;
-import org.onap.policy.common.gson.internal.Deserializer;
-import org.onap.policy.common.gson.internal.JacksonTypeAdapter;
-import org.onap.policy.common.gson.internal.MethodDeserializer;
-import org.onap.policy.common.gson.internal.MethodSerializer;
-import org.onap.policy.common.gson.internal.Serializer;
-
-/**
- * Factory that serializes/deserializes class methods following the normal behavior of
- * jackson. Supports the following annotations:
- * <ul>
- * <li>GsonJsonIgnore</li>
- * <li>GsonJsonProperty</li>
- * <li>GsonJsonAnyGetter</li>
- * <li>GsonJsonAnySetter</li>
- * </ul>
- */
-public class JacksonMethodAdapterFactory implements TypeAdapterFactory {
-
- @Override
- public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
- Class<? super T> clazz = type.getRawType();
-
- if (!JacksonExclusionStrategy.isManaged(clazz)) {
- return null;
- }
-
- var data = new ClassWalker();
- data.walkClassHierarchy(clazz);
-
- if (data.getInProps(Method.class).isEmpty() && data.getOutProps(Method.class).isEmpty()
- && data.getAnyGetter() == null && data.getAnySetter() == null) {
- // no methods to serialize
- return null;
- }
-
- Set<String> unliftedProps = new HashSet<>();
- unliftedProps.addAll(data.getInNotIgnored());
- unliftedProps.addAll(data.getOutNotIgnored());
-
- TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
- List<Serializer> sers = makeSerializers(gson, data, unliftedProps);
- List<Deserializer> desers = makeDeserializers(gson, data, unliftedProps);
-
- return new JacksonTypeAdapter<>(gson, delegate, sers, desers);
- }
-
- /**
- * Creates a complete list of serializers.
- *
- * @param gson the associated gson object
- * @param data data used to configure the serializers
- * @param unliftedProps properties that should not be lowered by "any-getters"
- * @return a list of all serializers
- */
- private List<Serializer> makeSerializers(Gson gson, ClassWalker data, Set<String> unliftedProps) {
- List<Serializer> ser = new ArrayList<>();
-
- if (data.getAnyGetter() != null) {
- ser.add(new AnyGetterSerializer(gson, unliftedProps, data.getAnyGetter()));
- }
-
- data.getOutProps(Method.class).forEach(method -> ser.add(new MethodSerializer(gson, method)));
-
- return ser;
- }
-
- /**
- * Creates a complete list of deserializers.
- *
- * @param gson the associated gson object
- * @param data data used to configure the deserializers
- * @param unliftedProps properties that should not be lifted by "any-setters"
- * @return a list of all deserializers
- */
- private List<Deserializer> makeDeserializers(Gson gson, ClassWalker data, Set<String> unliftedProps) {
- List<Deserializer> deser = new ArrayList<>();
-
- if (data.getAnySetter() != null) {
- deser.add(new AnySetterDeserializer(gson, unliftedProps, data.getAnySetter()));
- }
-
- data.getInProps(Method.class).forEach(method -> deser.add(new MethodDeserializer(gson, method)));
-
- return deser;
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
-
-/**
- * GSON Type Adapter for "LocalDateTime" fields, that uses the standard
- * ISO_LOCAL_DATE_TIME formatter, by default.
- */
-public class LocalDateTimeTypeAdapter extends StringTypeAdapter<LocalDateTime> {
-
- public LocalDateTimeTypeAdapter() {
- this(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
- }
-
- public LocalDateTimeTypeAdapter(DateTimeFormatter formatter) {
- super("date", string -> LocalDateTime.parse(string, formatter), value -> value.format(formatter));
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import java.time.LocalDate;
-import java.time.format.DateTimeFormatter;
-
-public class LocalDateTypeAdapter extends StringTypeAdapter<LocalDate> {
-
- public LocalDateTypeAdapter() {
- this(DateTimeFormatter.ISO_LOCAL_DATE);
- }
-
- public LocalDateTypeAdapter(DateTimeFormatter formatter) {
- super("date", string -> LocalDate.parse(string, formatter), value -> value.format(formatter));
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import com.google.gson.Gson;
-import com.google.gson.TypeAdapter;
-import com.google.gson.TypeAdapterFactory;
-import com.google.gson.reflect.TypeToken;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Adapter factory for Map<String,Object> and List<String>. By default, GSON treats all Objects, that
- * are numbers, as Double. This recursively walks a map/list and converts Doubles to Integer or Long, if
- * possible.
- */
-public class MapDoubleAdapterFactory implements TypeAdapterFactory {
-
- @Override
- public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
- if (!isMapType(type) && !isListType(type)) {
- return null;
- }
-
- TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
-
- return new MapAdapter<>(delegate);
- }
-
- private <T> boolean isMapType(TypeToken<T> type) {
- if (!Map.class.isAssignableFrom(type.getRawType())) {
- return false;
- }
-
- // only supports Map<String,Object>
-
- if (!(type.getType() instanceof ParameterizedType)) {
- // untyped - assume the parameters are the correct type
- return true;
- }
-
- Type[] actualParams = ((ParameterizedType) type.getType()).getActualTypeArguments();
-
- return (actualParams[0] == String.class && actualParams[1] == Object.class);
- }
-
- private <T> boolean isListType(TypeToken<T> type) {
- if (!List.class.isAssignableFrom(type.getRawType())) {
- return false;
- }
-
- // only supports List<Object>
-
- if (!(type.getType() instanceof ParameterizedType)) {
- // untyped - assume the parameters are the correct type
- return true;
- }
-
- Type[] actualParams = ((ParameterizedType) type.getType()).getActualTypeArguments();
-
- return (actualParams[0] == Object.class);
- }
-
- /**
- * Type adapter that performs conversion from Double to Integer/Long.
- *
- * @param <T> type of object on which this works (always Map.class)
- */
- private static class MapAdapter<T> extends TypeAdapter<T> {
-
- /**
- * Used to perform conversion between JSON and Map<String,Object>.
- */
- private final TypeAdapter<T> delegate;
-
- /**
- * Constructs the object.
- *
- * @param delegate JSON/Map converter
- */
- public MapAdapter(TypeAdapter<T> delegate) {
- this.delegate = delegate;
- }
-
- @Override
- public void write(JsonWriter out, T value) throws IOException {
- delegate.write(out, value);
- }
-
- @Override
- public T read(JsonReader in) throws IOException {
- var value = delegate.read(in);
-
- DoubleConverter.convertFromDouble(value);
-
- return value;
- }
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import java.time.OffsetDateTime;
-import java.time.format.DateTimeFormatter;
-
-public class OffsetDateTimeTypeAdapter extends StringTypeAdapter<OffsetDateTime> {
-
- public OffsetDateTimeTypeAdapter() {
- this(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
- }
-
- public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) {
- super("date", string -> OffsetDateTime.parse(string, formatter), value -> value.format(formatter));
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import java.time.OffsetTime;
-import java.time.format.DateTimeFormatter;
-
-public class OffsetTimeTypeAdapter extends StringTypeAdapter<OffsetTime> {
-
- public OffsetTimeTypeAdapter() {
- this(DateTimeFormatter.ISO_OFFSET_TIME);
- }
-
- public OffsetTimeTypeAdapter(DateTimeFormatter formatter) {
- super("time", string -> OffsetTime.parse(string, formatter), value -> value.format(formatter));
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import com.google.gson.JsonParseException;
-import com.google.gson.TypeAdapter;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonToken;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import java.util.function.Function;
-
-/**
- * GSON Type Adapter for fields that are encoded as Strings.
- */
-public class StringTypeAdapter<T> extends TypeAdapter<T> {
- private final String exMessage;
- private final Function<String, T> deserializer;
- private final Function<T, String> serializer;
-
- /**
- * Constructs an adapter.
- *
- * @param type type of value, used in exception messages
- * @param deserializer function used to deserialize a String into a value
- * @param serializer function used to serialize a value into a String
- */
- public StringTypeAdapter(String type, Function<String, T> deserializer, Function<T, String> serializer) {
- this.exMessage = "invalid " + type;
- this.deserializer = deserializer;
- this.serializer = serializer;
- }
-
- @Override
- public T read(JsonReader in) throws IOException {
- try {
- if (in.peek() == JsonToken.NULL) {
- in.nextNull();
- return null;
- } else {
- return deserializer.apply(in.nextString());
- }
-
- } catch (RuntimeException e) {
- throw new JsonParseException(exMessage, e);
- }
- }
-
- @Override
- public void write(JsonWriter out, T value) throws IOException {
- if (value == null) {
- out.nullValue();
- } else {
- String text = serializer.apply(value);
- out.value(text);
- }
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import java.time.ZoneOffset;
-
-public class ZoneOffsetTypeAdapter extends StringTypeAdapter<ZoneOffset> {
-
- public ZoneOffsetTypeAdapter() {
- super("zone", ZoneOffset::of, ZoneOffset::toString);
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-
-/**
- * GSON Type Adapter for "ZonedDateTime" fields, that uses the standard
- * ISO_ZONED_DATE_TIME formatter.
- */
-public class ZonedDateTimeTypeAdapter extends StringTypeAdapter<ZonedDateTime> {
-
- /**
- * Constructs an adapter that uses the ISO_ZONED_DATE_TIME formatter.
- */
- public ZonedDateTimeTypeAdapter() {
- this(DateTimeFormatter.ISO_ZONED_DATE_TIME);
- }
-
- /**
- * Constructs an adapter that uses the specified formatter for reading and writing.
- *
- * @param formatter date-time formatter
- */
- public ZonedDateTimeTypeAdapter(DateTimeFormatter formatter) {
- super("date", string -> ZonedDateTime.parse(string, formatter), value -> value.format(formatter));
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.annotation;
-
-import static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * Mimics Jackson JsonAnyGetter annotation, but used by gson. This requires the gson
- * object to be configured with the jackson default behaviors (i.e., the associated
- * JacksonXxx strategy and adapters must be registered with the gson object).
- */
-@Retention(RUNTIME)
-@Target(METHOD)
-public @interface GsonJsonAnyGetter {
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.annotation;
-
-import static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * Mimics Jackson JsonAnySetter annotation, but used by gson. This requires the gson
- * object to be configured with the jackson default behaviors (i.e., the associated
- * JacksonXxx strategy and adapters must be registered with the gson object).
- */
-@Retention(RUNTIME)
-@Target(METHOD)
-public @interface GsonJsonAnySetter {
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.annotation;
-
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * Mimics Jackson JsonIgnore annotation, but used by gson. This requires the gson object
- * to be configured with the jackson default behaviors (i.e., the associated JacksonXxx
- * strategy and adapters must be registered with the gson object).
- */
-@Retention(RUNTIME)
-@Target({FIELD, METHOD})
-public @interface GsonJsonIgnore {
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.annotation;
-
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * Mimics Jackson JsonProperty annotation, but used by gson. This requires the gson object
- * to be configured with the jackson default behaviors (i.e., the associated JacksonXxx
- * strategy and adapters must be registered with the gson object).
- */
-@Retention(RUNTIME)
-@Target({FIELD, METHOD})
-public @interface GsonJsonProperty {
-
- /**
- * Property name of this item when placed into a JsonObject.
- * @return the item's serialized name
- */
- String value() default "";
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.TypeAdapter;
-import com.google.gson.reflect.TypeToken;
-import com.google.re2j.Pattern;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.util.function.Supplier;
-import lombok.Getter;
-import org.onap.policy.common.gson.annotation.GsonJsonProperty;
-
-/**
- * Super class of adapters used to serialize and de-serialize an item.
- */
-public class Adapter {
-
- /**
- * Pattern to match valid identifiers.
- */
- private static final Pattern VALID_NAME_PAT = Pattern.compile("[a-zA-Z_]\\w*");
-
- /**
- * Factory to access objects. Overridden by junit tests.
- */
- private static Factory factory = new Factory();
-
- /**
- * Name of the property within the json structure containing the item.
- */
- @Getter
- private final String propName;
-
- /**
- * Gson object that will provide the type converter.
- */
- private final Gson gson;
-
- /**
- * Converter used when reading.
- */
- private final ConvInfo reader;
-
- /**
- * Converter used when writing, allocated lazily, once an actual type is determined.
- */
- private ConvInfo writer = null;
-
- /**
- * Name of the item being lifted - used when throwing exceptions.
- */
- @Getter
- private final String fullName;
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param field field used to access the item from within an object
- */
- public Adapter(Gson gson, Field field) {
- this.propName = detmPropName(field);
- this.reader = new ConvInfo(TypeToken.get(field.getGenericType()));
- this.gson = gson;
- this.fullName = getQualifiedName(field);
-
- /*
- * Turning off sonar, as this is required for emulation of "jackson".
- */
- field.setAccessible(true); // NOSONAR
- }
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param accessor method used to access the item from within an object
- * @param valueType the class of value on which this operates
- */
- public Adapter(Gson gson, Method accessor, Type valueType) {
- boolean forSetter = (accessor.getReturnType() == void.class);
- this.propName = (forSetter ? detmSetterPropName(accessor) : detmGetterPropName(accessor));
- this.reader = new ConvInfo(TypeToken.get(valueType));
- this.gson = gson;
- this.fullName = getQualifiedName(accessor);
-
- /*
- * Turning off sonar, as this is required for emulation of "jackson".
- */
- accessor.setAccessible(true); // NOSONAR
- }
-
- /**
- * Converts an object to a json tree.
- *
- * @param object the object to be converted
- * @return a json tree representing the object
- */
- @SuppressWarnings("unchecked")
- public JsonElement toJsonTree(Object object) {
- // always use a converter for the specific subclass
- Class<? extends Object> clazz = object.getClass();
-
- if (writer == null) {
- // race condition here, but it's ok to overwrite a previous value
- writer = new ConvInfo(TypeToken.get(clazz));
- }
-
- ConvInfo wtr = writer;
-
- TypeAdapter<Object> conv =
- (wtr.clazz == clazz ? wtr.getConverter() : (TypeAdapter<Object>) gson.getAdapter(clazz));
-
- return conv.toJsonTree(object);
- }
-
- /**
- * Converts a json tree to an object.
- *
- * @param tree the tree to be converted
- * @return the object represented by the tree
- */
- public Object fromJsonTree(JsonElement tree) {
- return reader.getConverter().fromJsonTree(tree);
- }
-
- /**
- * Makes an error message, appending the item's full name to the message prefix.
- *
- * @param prefix the message prefix
- * @return the error message
- */
- public String makeError(String prefix) {
- return (prefix + fullName);
- }
-
- /**
- * Determines if the field is managed by the walker.
- *
- * @param field the field to examine
- * @return {@code true} if the field is managed by the walker, {@code false} otherwise
- */
- public static boolean isManaged(Field field) {
- return VALID_NAME_PAT.matcher(factory.getName(field)).matches();
- }
-
- /**
- * Determines if the method is managed by the walker.
- *
- * @param method the method to examine
- * @return {@code true} if the method is managed by the walker, {@code false}
- * otherwise
- */
- public static boolean isManaged(Method method) {
- return VALID_NAME_PAT.matcher(factory.getName(method)).matches();
- }
-
- /**
- * Determines the property name of an item within the json structure.
- *
- * @param field the item within the object
- * @return the json property name for the item or {@code null} if the name is invalid
- */
- public static String detmPropName(Field field) {
- // use the serialized name, if specified
- GsonJsonProperty prop = field.getAnnotation(GsonJsonProperty.class);
- if (prop != null && !prop.value().isEmpty()) {
- return prop.value();
- }
-
- // no name provided - use it as is
- return (isManaged(field) ? factory.getName(field) : null);
- }
-
- /**
- * Determines the property name of an item, within the json structure, associated with
- * a "get" method.
- *
- * @param method method to be invoked to get the item within the object
- * @return the json property name for the item, or {@code null} if the method name is
- * not valid
- */
- public static String detmGetterPropName(Method method) {
-
- return detmPropNameCommon(method, () -> {
-
- if (!isManaged(method)) {
- return null;
- }
-
- String name = factory.getName(method);
-
- if (name.startsWith("get")) {
- return name.substring(3);
-
- } else if (name.startsWith("is")) {
- Class<?> treturn = method.getReturnType();
-
- if (treturn == boolean.class || treturn == Boolean.class) {
- return name.substring(2);
- }
- }
-
- // not a valid name for a "getter" method
- return null;
- });
- }
-
- /**
- * Determines the property name of an item, within the json structure, associated with
- * a "set" method.
- *
- * @param method method to be invoked to set the item within the object
- * @return the json property name for the item, or {@code null} if the method name is
- * not valid
- */
- public static String detmSetterPropName(Method method) {
-
- return detmPropNameCommon(method, () -> {
-
- if (!isManaged(method)) {
- return null;
- }
-
- String name = factory.getName(method);
-
- if (name.startsWith("set")) {
- return name.substring(3);
- }
-
- // not a valid name for a "setter" method
- return null;
- });
- }
-
- /**
- * Determines the property name of an item within the json structure.
- *
- * @param method method to be invoked to get/set the item within the object
- * @param extractor function to extract the name directly from the method name
- * @return the json property name for the item, or {@code null} if the method name is
- * not valid
- */
- private static String detmPropNameCommon(Method method, Supplier<String> extractor) {
-
- // use the property name, if specified
- GsonJsonProperty propName = method.getAnnotation(GsonJsonProperty.class);
- if (propName != null && !propName.value().isEmpty()) {
- return propName.value();
- }
-
- // no name provided - must compute it from the method name
- String name = extractor.get();
-
- if (name == null || name.isEmpty()) {
- // nothing left after stripping the prefix - invalid name
- return null;
- }
-
- // translate the first letter to lower-case
- return name.substring(0, 1).toLowerCase() + name.substring(1);
- }
-
- /**
- * Gets the fully qualified name of a field.
- *
- * @param field field whose name is desired
- * @return the field fully qualified name
- */
- public static String getQualifiedName(Field field) {
- return (field.getDeclaringClass().getName() + "." + factory.getName(field));
- }
-
- /**
- * Gets the fully qualified name of a method.
- *
- * @param method method whose name is desired
- * @return the method's fully qualified name
- */
- public static String getQualifiedName(Method method) {
- return (method.getDeclaringClass().getName() + "." + factory.getName(method));
- }
-
- /**
- * Converter info.
- */
- private class ConvInfo {
-
- /**
- * Type on which the converter works.
- */
- private TypeToken<?> type;
-
- /**
- * Class of object on which the converter works.
- */
- private Class<?> clazz;
-
- /**
- * Converter to use, initialized lazily.
- */
- private TypeAdapter<Object> conv = null;
-
- /**
- * Constructs the object.
- *
- * @param type type of object to be converted
- */
- public ConvInfo(TypeToken<?> type) {
- this.type = type;
- this.clazz = type.getRawType();
- }
-
- @SuppressWarnings("unchecked")
- public final TypeAdapter<Object> getConverter() {
- if (conv == null) {
- // race condition here, but it's ok to overwrite a previous value
- this.conv = (TypeAdapter<Object>) gson.getAdapter(type);
- }
-
- return conv;
- }
- }
-
- /**
- * Factory used to access various objects.
- */
- public static class Factory {
-
- public String getName(Field field) {
- return field.getName();
- }
-
- public String getName(Method method) {
- return method.getName();
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import java.lang.reflect.Method;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * Serializer for methods having a JsonAnyGetter annotation.
- */
-public class AnyGetterSerializer extends Lifter implements Serializer {
-
- public static final String NOT_AN_OBJECT_ERR = "expecting a JsonObject for ";
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param unliftedProps property names that should not be lifted
- * @param getter method used to get the item from within an object
- */
- public AnyGetterSerializer(Gson gson, Set<String> unliftedProps, Method getter) {
- super(gson, unliftedProps, getter, getter.getGenericReturnType());
- }
-
- @Override
- public void addToTree(Object source, JsonObject target) {
- // get the value from the object
- Object value = invoke(source);
- if (value == null) {
- // nothing to lift
- return;
- }
-
- JsonElement inner = toJsonTree(value);
- if (!inner.isJsonObject()) {
- throw new JsonParseException(makeError(NOT_AN_OBJECT_ERR));
- }
-
- // lift items from inner into the target
- copyLiftedItems(inner.getAsJsonObject(), target);
- }
-
- /**
- * Copies lifted items from one tree into another, without removing them from the
- * source tree.
- *
- * @param source tree from which items are to be copied
- * @param target tree into which items are to be copied
- */
- private void copyLiftedItems(JsonObject source, JsonObject target) {
- for (Entry<String, JsonElement> ent : source.entrySet()) {
- String name = ent.getKey();
- if (shouldLift(name)) {
- target.add(name, ent.getValue());
- }
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import java.lang.reflect.Method;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * De-serializer for methods having a JsonAnySetter annotation.
- */
-public class AnySetterDeserializer extends Lifter implements Deserializer {
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param unliftedProps property names that should not be lifted
- * @param setter method used to set the item within an object
- */
- public AnySetterDeserializer(Gson gson, Set<String> unliftedProps, Method setter) {
- super(gson, unliftedProps, setter, setter.getGenericParameterTypes()[1]);
- }
-
- @Override
- public void getFromTree(JsonObject source, Object target) {
- for (Entry<String, JsonElement> ent : source.entrySet()) {
- String name = ent.getKey();
-
- if (shouldLift(name)) {
- Object value = fromJsonTree(ent.getValue());
- invoke(target, name, value);
- }
- }
- }
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.JsonParseException;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import lombok.Getter;
-import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
-import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
-import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
-import org.onap.policy.common.gson.annotation.GsonJsonProperty;
-
-/**
- * Data populated while walking the hierarchy of a class.
- */
-public class ClassWalker {
-
- public static final String ANY_GETTER_MISMATCH_ERR =
- GsonJsonAnyGetter.class.getSimpleName() + " parameter mismatch for: ";
-
- public static final String ANY_SETTER_MISMATCH_ERR =
- GsonJsonAnySetter.class.getSimpleName() + " parameter mismatch for: ";
-
- public static final String ANY_SETTER_TYPE_ERR =
- GsonJsonAnySetter.class.getSimpleName() + " first parameter must be a string: ";
-
- /**
- * Maps an input property name to an item within the class, where item is one of:
- * {@link Field}, {@link Method}, or {@code null}. Entries are overwritten as new
- * items are added.
- */
- private final Map<String, Object> inProps = new HashMap<>();
-
- /**
- * Maps an output property name to an item within the class, where item is one of:
- * {@link Field}, {@link Method}, or {@code null}. Entries are overwritten as new
- * items are added.
- */
- private final Map<String, Object> outProps = new HashMap<>();
-
- /**
- * Maps a method name to a "get" method. Used when overriding properties associated
- * with a method.
- */
- private final Map<String, Method> getters = new HashMap<>();
-
- /**
- * Maps a method name to a "set" method. Used when overriding properties associated
- * with a method.
- */
- private final Map<String, Method> setters = new HashMap<>();
-
- /**
- * Method having {@link GsonJsonAnyGetter} annotation. Overwritten as new "any-getters"
- * are identified.
- */
- @Getter
- private Method anyGetter = null;
-
- /**
- * Method having {@link GsonJsonAnySetter} annotation. Overwritten as new "any-setters"
- * are identified.
- */
- @Getter
- private Method anySetter = null;
-
- /**
- * Gets the names of input properties that are not being ignored.
- *
- * @return the non-ignored input property names
- */
- public List<String> getInNotIgnored() {
- return getNonNull(inProps);
- }
-
- /**
- * Gets the names of output properties that are not being ignored.
- *
- * @return the non-ignored output property names
- */
- public List<String> getOutNotIgnored() {
- return getNonNull(outProps);
- }
-
- /**
- * Gets the property names, associated with a non-null value, from a set of
- * properties.
- *
- * @param props set of properties from which to extract the names
- * @return the property names having a non-null value
- */
- private List<String> getNonNull(Map<String, Object> props) {
- List<String> lst = new ArrayList<>(props.size());
-
- for (Entry<String, Object> ent : props.entrySet()) {
- if (ent.getValue() != null) {
- lst.add(ent.getKey());
- }
- }
-
- return lst;
- }
-
- /**
- * Gets the input properties whose values are of the given class.
- *
- * @param clazz class of properties to get
- * @return the input properties of the given class
- */
- public <T> List<T> getInProps(Class<T> clazz) {
- return getProps(clazz, inProps.values());
- }
-
- /**
- * Gets the output properties whose values are of the given class.
- *
- * @param clazz class of properties to get
- * @return the output properties of the given class
- */
- public <T> List<T> getOutProps(Class<T> clazz) {
- return getProps(clazz, outProps.values());
- }
-
- /**
- * Gets the properties whose values are of the given class.
- *
- * @param clazz class of properties to get
- * @param values values from which to select
- * @return the output properties of the given class
- */
- @SuppressWarnings("unchecked")
- private <T> List<T> getProps(Class<T> clazz, Collection<Object> values) {
- List<T> lst = new ArrayList<>(values.size());
-
- for (Object val : values) {
- if (val != null && val.getClass() == clazz) {
- lst.add((T) val);
- }
- }
-
- return lst;
- }
-
- /**
- * Recursively walks a class hierarchy, including super classes and interfaces,
- * examining each class for various annotations.
- *
- * @param clazz class whose hierarchy is to be walked
- */
- public void walkClassHierarchy(Class<?> clazz) {
- if (clazz == Object.class) {
- return;
- }
-
- // walk interfaces first
- for (Class<?> intfc : clazz.getInterfaces()) {
- walkClassHierarchy(intfc);
- }
-
- // walk superclass next, overwriting previous items
- Class<?> sup = clazz.getSuperclass();
- if (sup != null) {
- walkClassHierarchy(sup);
- }
-
- // finally, examine this class, overwriting previous items
- examine(clazz);
- }
-
- /**
- * Examines a class for annotations, examining fields and then methods.
- *
- * @param clazz class to be examined
- */
- protected void examine(Class<?> clazz) {
- for (Field field : clazz.getDeclaredFields()) {
- examine(field);
- }
-
- for (Method method : clazz.getDeclaredMethods()) {
- examine(method);
- }
- }
-
- /**
- * Examines a field for annotations.
- *
- * @param field field to be examined
- */
- protected void examine(Field field) {
- if (field.isSynthetic()) {
- return;
- }
-
- int mod = field.getModifiers();
-
- if (Modifier.isStatic(mod)) {
- // skip static fields
- return;
- }
-
- if (!Modifier.isPublic(mod) && field.getAnnotation(GsonJsonProperty.class) == null) {
- // private/protected - skip it unless explicitly exposed
- return;
- }
-
- if (Modifier.isTransient(mod) && field.getAnnotation(GsonJsonProperty.class) == null) {
- // transient - skip it unless explicitly exposed
- return;
- }
-
- String name = detmPropName(field);
- if (name == null) {
- // invalid name
- return;
- }
-
- // if ignoring, then insert null into the map, otherwise insert the field
- Field annotField = (field.getAnnotation(GsonJsonIgnore.class) != null ? null : field);
-
- // a field can be both an input and an output
-
- inProps.put(name, annotField);
- outProps.put(name, annotField);
- }
-
- /**
- * Examines a method for annotations.
- *
- * @param method method to be examined
- */
- protected void examine(Method method) {
- if (method.isSynthetic()) {
- return;
- }
-
- int mod = method.getModifiers();
-
- if (Modifier.isStatic(mod)) {
- // static methods are not exposed
- return;
- }
-
- GsonJsonProperty prop = method.getAnnotation(GsonJsonProperty.class);
- GsonJsonAnyGetter get = method.getAnnotation(GsonJsonAnyGetter.class);
- GsonJsonAnySetter set = method.getAnnotation(GsonJsonAnySetter.class);
-
- if (!Modifier.isPublic(mod) && prop == null && get == null && set == null) {
- // private/protected methods are not exposed, unless annotated
- return;
- }
-
-
- if (method.getReturnType() == void.class) {
- // "void" return type - must be a "setter" method
- if (set == null) {
- examineSetter(method);
-
- } else {
- examineAnySetter(method);
- }
-
- } else {
- // must be a "getter" method
- if (get == null) {
- examineGetter(method);
-
- } else {
- examineAnyGetter(method);
- }
- }
- }
-
- /**
- * Examines a "setter" method.
- *
- * @param method method to be examined
- */
- private void examineSetter(Method method) {
- String name = Adapter.detmSetterPropName(method);
- if (name != null && method.getParameterCount() == 1) {
- // remove old name mapping, if any
- Method old = setters.get(method.getName());
- if (old != null) {
- inProps.remove(Adapter.detmSetterPropName(old));
- }
-
- setters.put(method.getName(), method);
-
- // if ignoring, then insert null into the map, otherwise insert the method
- inProps.put(name, (method.getAnnotation(GsonJsonIgnore.class) != null ? null : method));
- }
- }
-
- /**
- * Examines a "getter" method.
- *
- * @param method method to be examined
- */
- private void examineGetter(Method method) {
- String name = Adapter.detmGetterPropName(method);
- if (name != null && method.getParameterCount() == 0) {
- // remove old name mapping, if any
- Method old = getters.get(method.getName());
- if (old != null) {
- outProps.remove(Adapter.detmGetterPropName(old));
- }
-
- getters.put(method.getName(), method);
-
- // if ignoring, then insert null into the map, otherwise insert the method
- outProps.put(name, (method.getAnnotation(GsonJsonIgnore.class) != null ? null : method));
- }
- }
-
- /**
- * Examines a method having a {@link GsonJsonAnySetter} annotation.
- *
- * @param method method to be examined
- */
- private void examineAnySetter(Method method) {
- if (method.getParameterCount() != 2) {
- throw new JsonParseException(ANY_SETTER_MISMATCH_ERR + getFqdn(method));
- }
-
- if (method.getParameterTypes()[0] != String.class) {
- throw new JsonParseException(ANY_SETTER_TYPE_ERR + getFqdn(method));
- }
-
- // if ignoring, then use null, otherwise use the method
- anySetter = (method.getAnnotation(GsonJsonIgnore.class) != null ? null : method);
- }
-
- /**
- * Examines a method having a {@link GsonJsonAnyGetter} annotation.
- *
- * @param method method to be examined
- */
- private void examineAnyGetter(Method method) {
- if (method.getParameterCount() != 0) {
- throw new JsonParseException(ANY_GETTER_MISMATCH_ERR + getFqdn(method));
- }
-
- // if ignoring, then use null, otherwise use the method
- anyGetter = (method.getAnnotation(GsonJsonIgnore.class) != null ? null : method);
- }
-
- /**
- * Gets the fully qualified name of a method.
- *
- * @param method method whose name is desired
- * @return the fully qualified method name
- */
- private String getFqdn(Method method) {
- return (method.getDeclaringClass().getName() + "." + method.getName());
- }
-
- // these may be overridden by junit tests
-
- protected String detmPropName(Field field) {
- return Adapter.detmPropName(field);
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.JsonObject;
-
-/**
- * Super class of all de-serializers.
- */
-@FunctionalInterface
-public interface Deserializer {
-
- /**
- * Gets an value from a tree, converts it, and puts it into a target object.
- *
- * @param source tree from which to get the value
- * @param target where to place the converted value
- */
- void getFromTree(JsonObject source, Object target);
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import java.lang.reflect.Field;
-
-/**
- * De-serializer for fields that are exposed.
- */
-public class FieldDeserializer extends Adapter implements Deserializer {
-
- public static final String SET_ERR = "cannot set field: ";
-
- /**
- * Field within the object.
- */
- private final Field field;
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param field field within the object
- */
- public FieldDeserializer(Gson gson, Field field) {
- super(gson, field);
-
- this.field = field;
-
- /*
- * Turning off sonar, as this is required for emulation of "jackson".
- */
- field.setAccessible(true); // NOSONAR
- }
-
- @Override
- public void getFromTree(JsonObject source, Object target) {
- JsonElement jsonEl = source.get(getPropName());
- if (jsonEl == null || jsonEl.isJsonNull()) {
- return;
- }
-
- Object value = fromJsonTree(jsonEl);
-
- try {
- /*
- * Turning off sonar, as this is required for emulation of "jackson".
- */
- field.set(target, value); // NOSONAR
-
- } catch (IllegalArgumentException | IllegalAccessException e) {
- throw new JsonParseException(makeError(SET_ERR), e);
- }
- }
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonNull;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import java.lang.reflect.Field;
-
-/**
- * Serializer for fields that are exposed.
- */
-public class FieldSerializer extends Adapter implements Serializer {
-
- public static final String GET_ERR = "cannot get field: ";
-
- /**
- * Field within the object.
- */
- private final Field field;
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param field field within the object
- */
- public FieldSerializer(Gson gson, Field field) {
- super(gson, field);
-
- this.field = field;
-
- /*
- * Turning off sonar, as this is required for emulation of "jackson".
- */
- field.setAccessible(true); // NOSONAR
- }
-
- @Override
- public void addToTree(Object source, JsonObject target) {
- Object value;
- try {
- value = getFromObject(source);
-
- } catch (IllegalArgumentException | IllegalAccessException e) {
- throw new JsonParseException(makeError(GET_ERR), e);
- }
-
- JsonElement jsonEl = (value == null ? JsonNull.INSTANCE : toJsonTree(value));
- target.add(getPropName(), jsonEl);
- }
-
- /**
- * Gets the field from the source object. Overridden during junit testing.
- *
- * @param source object containing the field
- * @return the field's value
- * @throws IllegalAccessException if an error occurs
- */
- protected Object getFromObject(Object source) throws IllegalAccessException {
- return field.get(source);
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.TypeAdapter;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import java.util.List;
-
-
-/**
- * Adapter for a single class that implements a jackson-style behavior.
- *
- * @param <T> type of class on which the adapter works
- */
-public class JacksonTypeAdapter<T> extends TypeAdapter<T> {
-
- /**
- * Used to create an object of the given class.
- */
- private final TypeAdapter<T> delegate;
-
- /**
- * Used to serialize/deserialize a JsonElement.
- */
- private final TypeAdapter<JsonElement> elementAdapter;
-
- /**
- * Serializers for each item within the object.
- */
- private final Serializer[] serializers;
-
- /**
- * Deserializers for each item within the object.
- */
- private final Deserializer[] deserializers;
-
- /**
- * Constructs the object.
- *
- * @param gson the associated gson object
- * @param delegate default constructor for the type
- * @param serializers the serializers to use to serialize items within the object
- * @param deserializers the deserializers to use to deserialize items into the object
- */
- public JacksonTypeAdapter(Gson gson, TypeAdapter<T> delegate, List<Serializer> serializers,
- List<Deserializer> deserializers) {
- this.delegate = delegate;
- this.elementAdapter = gson.getAdapter(JsonElement.class);
- this.serializers = serializers.toArray(new Serializer[0]);
- this.deserializers = deserializers.toArray(new Deserializer[0]);
- }
-
- @Override
- public void write(JsonWriter out, T value) throws IOException {
- JsonElement tree = delegate.toJsonTree(value);
-
- if (tree.isJsonObject()) {
- var jsonObj = tree.getAsJsonObject();
-
- // serialize each item from the value into the target tree
- for (Serializer serializer : serializers) {
- serializer.addToTree(value, jsonObj);
- }
- }
-
- elementAdapter.write(out, tree);
- }
-
- @Override
- public T read(JsonReader in) throws IOException {
- JsonElement tree = elementAdapter.read(in);
- var object = delegate.fromJsonTree(tree);
-
- if (tree.isJsonObject()) {
- var jsonObj = tree.getAsJsonObject();
-
- // deserialize each item from the tree into the target object
- for (Deserializer dser : deserializers) {
- dser.getFromTree(jsonObj, object);
- }
- }
-
- return object;
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.util.Set;
-
-/**
- * Super class of serializers and de-serializers that deal with "lifted" data, that is,
- * data that is lifted from a nested json object into the containing object.
- */
-public class Lifter extends MethodAdapter {
-
- /**
- * Names of the properties that are <i>not</i> to be lifted.
- */
- private final Set<String> unliftedProps;
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param unliftedProps property names that should not be lifted
- * @param accessor method used to access the item from within an object
- * @param type the class of value on which this operates
- */
- public Lifter(Gson gson, Set<String> unliftedProps, Method accessor, Type type) {
- super(gson, accessor, type);
-
- this.unliftedProps = unliftedProps;
- }
-
- /**
- * Determines if a property should be lifted.
- *
- * @param propName the name of the property
- * @return {@code true} if the property should be lifted, {@code false} otherwise
- */
- public boolean shouldLift(String propName) {
- return !unliftedProps.contains(propName);
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonParseException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-
-/**
- * Super class of adapters used to serialize and de-serialize a method.
- */
-public class MethodAdapter extends Adapter {
-
- public static final String INVOKE_ERR = "cannot invoke method to serialize/deserialize: ";
-
- /**
- * Method used to access the item within an object.
- */
- private final Method accessor;
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param accessor method used to access the item from within an object
- * @param type the class of value on which this operates
- */
- public MethodAdapter(Gson gson, Method accessor, Type type) {
- super(gson, accessor, type);
-
- this.accessor = accessor;
- }
-
- /**
- * Invokes the accessor method.
- *
- * @param self object on which to invoke the method
- * @param args arguments to be passed to the method
- * @return the method's result
- */
- public Object invoke(Object self, Object... args) {
- try {
- return accessor.invoke(self, args);
-
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- throw new JsonParseException(makeError(INVOKE_ERR), e);
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import java.lang.reflect.Method;
-
-/**
- * De-serializer for methods that are exposed.
- */
-public class MethodDeserializer extends MethodAdapter implements Deserializer {
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param setter method used to set the item within an object
- */
- public MethodDeserializer(Gson gson, Method setter) {
- super(gson, setter, setter.getGenericParameterTypes()[0]);
- }
-
- @Override
- public void getFromTree(JsonObject source, Object target) {
- JsonElement jsonEl = source.get(getPropName());
- if (jsonEl == null || jsonEl.isJsonNull()) {
- return;
- }
-
- invoke(target, fromJsonTree(jsonEl));
- }
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonObject;
-import java.lang.reflect.Method;
-
-/**
- * Serializer for methods that are exposed.
- */
-public class MethodSerializer extends MethodAdapter implements Serializer {
-
- /**
- * Constructs the object.
- *
- * @param gson Gson object providing type adapters
- * @param getter method used to get the item from within an object
- */
- public MethodSerializer(Gson gson, Method getter) {
- super(gson, getter, getter.getGenericReturnType());
- }
-
- @Override
- public void addToTree(Object source, JsonObject target) {
- Object value = invoke(source);
- target.add(getPropName(), (value == null ? null : toJsonTree(value)));
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.JsonObject;
-
-/**
- * Super class of all serializers.
- */
-@FunctionalInterface
-public interface Serializer {
-
- /**
- * Converts an object and then adds it to a tree.
- *
- * @param source object to be converted
- * @param target tree into which to place the converted object
- */
- void addToTree(Object source, JsonObject target);
-
-}
* ONAP
* ================================================================================
* Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2022-2024 Nordix Foundation.
+ * Modifications Copyright (C) 2022-2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.common.message.bus.event;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import lombok.Getter;
import org.onap.policy.common.capabilities.Startable;
-import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
import org.onap.policy.common.message.bus.event.kafka.KafkaTopicFactories;
import org.onap.policy.common.message.bus.event.kafka.KafkaTopicSink;
import org.onap.policy.common.message.bus.event.kafka.KafkaTopicSource;
return sinks;
}
- @GsonJsonIgnore
+ @JsonIgnore
@Override
public List<KafkaTopicSource> getKafkaTopicSources() {
return KafkaTopicFactories.getSourceFactory().inventory();
}
- @GsonJsonIgnore
+ @JsonIgnore
@Override
public List<NoopTopicSource> getNoopTopicSources() {
return NoopTopicFactories.getSourceFactory().inventory();
}
@Override
- @GsonJsonIgnore
+ @JsonIgnore
public List<KafkaTopicSink> getKafkaTopicSinks() {
return KafkaTopicFactories.getSinkFactory().inventory();
}
- @GsonJsonIgnore
+ @JsonIgnore
@Override
public List<NoopTopicSink> getNoopTopicSinks() {
return NoopTopicFactories.getSinkFactory().inventory();
*
* @return list of managed endpoints
*/
- @GsonJsonIgnore
+ @JsonIgnore
protected List<Startable> getEndpoints() {
final List<Startable> endpoints = new ArrayList<>();
* ================================================================================
* Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
* Modifications Copyright (C) 2018-2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019, 2023-2024 Nordix Foundation.
+ * Modifications Copyright (C) 2019, 2023-2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.common.parameters.topic;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
import java.util.Map;
import lombok.AccessLevel;
* Methods to Check if the property is INVALID.
*/
+ @JsonIgnore
boolean isEnvironmentInvalid() {
return StringUtils.isBlank(environment);
}
+ @JsonIgnore
boolean isAftEnvironmentInvalid() {
return StringUtils.isBlank(aftEnvironment);
}
+ @JsonIgnore
boolean isLatitudeInvalid() {
return StringUtils.isBlank(latitude);
}
+ @JsonIgnore
boolean isLongitudeInvalid() {
return StringUtils.isBlank(longitude);
}
+ @JsonIgnore
public boolean isConsumerInstanceInvalid() {
return StringUtils.isBlank(consumerInstance);
}
+ @JsonIgnore
public boolean isConsumerGroupInvalid() {
return StringUtils.isBlank(consumerGroup);
}
+ @JsonIgnore
public boolean isClientNameInvalid() {
return StringUtils.isBlank(clientName);
}
+ @JsonIgnore
boolean isPartnerInvalid() {
return StringUtils.isBlank(partner);
}
+ @JsonIgnore
boolean isServersInvalid() {
return (servers == null || servers.isEmpty()
|| (servers.size() == 1 && ("".equals(servers.get(0)))));
}
+ @JsonIgnore
public boolean isTopicInvalid() {
return StringUtils.isBlank(topic);
}
+ @JsonIgnore
public boolean isPartitionIdInvalid() {
return StringUtils.isBlank(partitionId);
}
+ @JsonIgnore
public boolean isHostnameInvalid() {
return StringUtils.isBlank(hostname);
}
+ @JsonIgnore
public boolean isPortInvalid() {
return (getPort() <= 0 || getPort() >= 65535);
}
* Methods to Check if the property is Valid.
*/
+ @JsonIgnore
boolean isApiKeyValid() {
return StringUtils.isNotBlank(apiKey);
}
+ @JsonIgnore
boolean isApiSecretValid() {
return StringUtils.isNotBlank(apiSecret);
}
+ @JsonIgnore
boolean isUserNameValid() {
return StringUtils.isNotBlank(userName);
}
+ @JsonIgnore
boolean isPasswordValid() {
return StringUtils.isNotBlank(password);
}
+ @JsonIgnore
public boolean isAdditionalPropsValid() {
return additionalProps != null;
}
-/*
+/*-
* ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.common.utils.coder;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.TypeAdapter;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonWriter;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
-import java.util.List;
-import java.util.Map;
-import lombok.AccessLevel;
-import lombok.AllArgsConstructor;
-import org.onap.policy.common.gson.DoubleConverter;
-import org.onap.policy.common.gson.GsonMessageBodyHandler;
/**
- * JSON encoder and decoder using the "standard" mechanism, which is currently gson.
+ * JSON encoder and decoder using the "standard" mechanism, which is currently jackson.
*/
-@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class StandardCoder implements Coder {
- /**
- * Gson object used to encode and decode messages.
- */
- private static final Gson GSON_STD;
-
- /**
- * Gson object used to encode messages in "pretty" format.
- */
- private static final Gson GSON_STD_PRETTY;
-
- static {
- GsonBuilder builder = GsonMessageBodyHandler.configBuilder(
- new GsonBuilder().registerTypeAdapter(StandardCoderObject.class, new StandardTypeAdapter()));
-
- GSON_STD = builder.create();
- GSON_STD_PRETTY = builder.setPrettyPrinting().create();
+ private static final ObjectMapper MAPPER = createMapper();
+ private static final ObjectMapper MAPPER_PRETTY = createMapper().enable(SerializationFeature.INDENT_OUTPUT);
+
+ private static ObjectMapper createMapper() {
+ ObjectMapper mapper = new ObjectMapper();
+ // Configure to handle empty beans (like test classes with no getters/setters)
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ // Configure to ignore unknown properties (similar to Gson behavior)
+ mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ // Configure to handle null values more gracefully
+ mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
+ // Configure to handle circular references - disable self-reference detection entirely
+ mapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
+ // Don't write self references as null, just ignore them
+ mapper.configure(SerializationFeature.WRITE_SELF_REFERENCES_AS_NULL, false);
+
+ // Register modules for Java 8 time support (JSR310)
+ mapper.findAndRegisterModules();
+
+ return mapper;
}
- /**
- * Gson object used to encode and decode messages.
- */
- protected final Gson gson;
+ protected final ObjectMapper objectMapper;
+ protected final ObjectMapper mapperPretty;
- /**
- * Gson object used to encode messages in "pretty" format.
- */
- protected final Gson gsonPretty;
-
- /**
- * Constructs the object.
- */
public StandardCoder() {
- this(GSON_STD, GSON_STD_PRETTY);
+ this(MAPPER, MAPPER_PRETTY);
+ }
+
+ protected StandardCoder(ObjectMapper mapper, ObjectMapper mapperPretty) {
+ this.objectMapper = mapper;
+ this.mapperPretty = mapperPretty;
}
@Override
public <S, T> T convert(S source, Class<T> clazz) throws CoderException {
if (source == null) {
return null;
-
- } else if (clazz == source.getClass()) {
- // same class - just cast it
+ }
+ if (clazz.isInstance(source)) {
return clazz.cast(source);
-
- } else if (clazz == String.class) {
- // target is a string - just encode the source
- return (clazz.cast(encode(source)));
-
- } else if (source.getClass() == String.class) {
- // source is a string - just decode it
- return decode(source.toString(), clazz);
-
- } else {
- /*
- * Do it the long way: encode to a tree and then decode the tree. This entire
- * method could have been left out and the default Coder.convert() used
- * instead, but this should perform slightly better as it only uses a
- * JsonElement as the intermediate data structure, while Coder.convert() goes
- * all the way to a String as the intermediate data structure.
- */
- try {
- return fromJson(toJsonTree(source), clazz);
- } catch (RuntimeException e) {
- throw new CoderException(e);
- }
+ }
+ if (clazz == String.class) {
+ return clazz.cast(encode(source));
+ }
+ if (source instanceof String) {
+ return decode((String) source, clazz);
+ }
+ try {
+ var node = objectMapper.valueToTree(source);
+ return fromJson(node, clazz);
+ } catch (Exception e) {
+ throw new CoderException(e);
}
}
@Override
public String encode(Object object, boolean pretty) throws CoderException {
try {
- if (pretty) {
- return toPrettyJson(object);
-
- } else {
- return toJson(object);
- }
-
- } catch (RuntimeException e) {
+ return pretty ? toPrettyJson(object) : toJson(object);
+ } catch (Exception e) {
throw new CoderException(e);
}
}
public void encode(Writer target, Object object) throws CoderException {
try {
toJson(target, object);
-
- } catch (RuntimeException e) {
+ } catch (Exception e) {
throw new CoderException(e);
}
}
@Override
public void encode(OutputStream target, Object object) throws CoderException {
+ var writer = makeWriter(target);
try {
- var wtr = makeWriter(target);
- toJson(wtr, object);
-
- // flush, but don't close
- wtr.flush();
-
- } catch (RuntimeException | IOException e) {
+ toJson(writer, object);
+ } catch (Exception e) {
throw new CoderException(e);
}
}
@Override
public void encode(File target, Object object) throws CoderException {
- try (var wtr = makeWriter(target)) {
- toJson(wtr, object);
-
- // no need to flush or close here
-
- } catch (RuntimeException | IOException e) {
+ try (var writer = makeWriter(target)) {
+ toJson(writer, object);
+ } catch (Exception e) {
throw new CoderException(e);
}
}
public <T> T decode(String json, Class<T> clazz) throws CoderException {
try {
return fromJson(json, clazz);
- } catch (RuntimeException e) {
+ } catch (Exception e) {
throw new CoderException(e);
}
}
public <T> T decode(Reader source, Class<T> clazz) throws CoderException {
try {
return fromJson(source, clazz);
-
- } catch (RuntimeException e) {
+ } catch (Exception e) {
throw new CoderException(e);
}
}
@Override
public <T> T decode(InputStream source, Class<T> clazz) throws CoderException {
- try {
- return fromJson(makeReader(source), clazz);
-
- } catch (RuntimeException e) {
+ try (var reader = makeReader(source)) {
+ return fromJson(reader, clazz);
+ } catch (Exception e) {
throw new CoderException(e);
}
}
@Override
public <T> T decode(File source, Class<T> clazz) throws CoderException {
- try (var input = makeReader(source)) {
- return fromJson(input, clazz);
-
- } catch (RuntimeException | IOException e) {
+ try (var reader = makeReader(source)) {
+ return fromJson(reader, clazz);
+ } catch (Exception e) {
throw new CoderException(e);
}
}
- /**
- * Encodes the object as "pretty" json.
- *
- * @param object object to be encoded
- * @return the encoded object
- */
- protected String toPrettyJson(Object object) {
- return gsonPretty.toJson(object);
- }
-
@Override
public StandardCoderObject toStandard(Object object) throws CoderException {
+ if (object instanceof Class) {
+ throw new CoderException("Cannot serialize Class objects");
+ }
try {
- return new StandardCoderObject(gson.toJsonTree(object));
-
- } catch (RuntimeException e) {
+ return new StandardCoderObject(objectMapper.valueToTree(object));
+ } catch (IllegalArgumentException e) {
throw new CoderException(e);
}
}
@Override
public <T> T fromStandard(StandardCoderObject sco, Class<T> clazz) throws CoderException {
+ if (sco == null || clazz == null) {
+ throw new CoderException("null argument");
+ }
try {
- return gson.fromJson(sco.getData(), clazz);
-
- } catch (RuntimeException e) {
+ return objectMapper.treeToValue(sco.getData(), clazz);
+ } catch (Exception e) {
throw new CoderException(e);
}
}
- // the remaining methods are wrappers that can be overridden by junit tests
-
/**
* Makes a writer for the given file.
*
- * @param target file of interest
+ * @param file file of interest
* @return a writer for the file
* @throws FileNotFoundException if the file cannot be created
*/
- protected Writer makeWriter(File target) throws FileNotFoundException {
- return makeWriter(new FileOutputStream(target));
+ protected Writer makeWriter(File file) throws FileNotFoundException {
+ return new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
}
/**
/**
* Makes a reader for the given file.
*
- * @param source file of interest
+ * @param file file of interest
* @return a reader for the file
* @throws FileNotFoundException if the file does not exist
*/
- protected Reader makeReader(File source) throws FileNotFoundException {
- return makeReader(new FileInputStream(source));
+ protected Reader makeReader(File file) throws FileNotFoundException {
+ return new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
}
/**
return new InputStreamReader(source, StandardCharsets.UTF_8);
}
- /**
- * Encodes an object into a json tree, without catching exceptions.
- *
- * @param object object to be encoded
- * @return a json element representing the object
- */
- protected JsonElement toJsonTree(Object object) {
- return gson.toJsonTree(object);
- }
-
/**
* Encodes an object into json, without catching exceptions.
*
* @param object object to be encoded
* @return a json string representing the object
*/
- protected String toJson(Object object) {
- return gson.toJson(object);
+ protected String toJson(Object object) throws JsonProcessingException {
+ return objectMapper.writeValueAsString(object);
}
/**
* @param target target to which to write the encoded json
* @param object object to be encoded
*/
- protected void toJson(Writer target, Object object) {
- gson.toJson(object, object.getClass(), target);
+ protected void toJson(Writer target, Object object) throws IOException {
+ objectMapper.writeValue(target, object);
}
/**
* Decodes a json element into an object, without catching exceptions.
*
- * @param json json element to be decoded
+ * @param node json element to be decoded
* @param clazz class of object to be decoded
* @return the object represented by the given json element
*/
- protected <T> T fromJson(JsonElement json, Class<T> clazz) {
- return convertFromDouble(clazz, gson.fromJson(json, clazz));
+ protected <T> T fromJson(JsonNode node, Class<T> clazz) throws CoderException {
+ try {
+ return objectMapper.treeToValue(node, clazz);
+ } catch (Exception e) {
+ throw new CoderException(e);
+ }
}
/**
* @param clazz class of object to be decoded
* @return the object represented by the given json string
*/
- protected <T> T fromJson(String json, Class<T> clazz) {
- return convertFromDouble(clazz, gson.fromJson(json, clazz));
+ protected <T> T fromJson(String json, Class<T> clazz) throws IOException {
+ return objectMapper.readValue(json, clazz);
}
/**
* @param clazz class of object to be decoded
* @return the object represented by the given json string
*/
- protected <T> T fromJson(Reader source, Class<T> clazz) {
- return convertFromDouble(clazz, gson.fromJson(source, clazz));
+ protected <T> T fromJson(Reader source, Class<T> clazz) throws IOException {
+ return objectMapper.readValue(source, clazz);
}
- /**
- * Converts a value from Double to Integer/Long, walking the value's contents if it's
- * a List/Map. Only applies if the specified class refers to the Object class.
- * Otherwise, it leaves the value unchanged.
- *
- * @param clazz class of object to be decoded
- * @param value value to be converted
- * @return the converted value
- */
- protected <T> T convertFromDouble(Class<T> clazz, T value) {
- if (clazz != Object.class && !Map.class.isAssignableFrom(clazz) && !List.class.isAssignableFrom(clazz)) {
- return value;
- }
-
- return clazz.cast(DoubleConverter.convertFromDouble(value));
+ protected String toPrettyJson(Object object) throws JsonProcessingException {
+ return mapperPretty.writeValueAsString(object);
}
- /**
- * Adapter for standard objects.
- */
- @AllArgsConstructor
- protected static class StandardTypeAdapter extends TypeAdapter<StandardCoderObject> {
-
- /**
- * Used to read/write a JsonElement.
- */
- private static final TypeAdapter<JsonElement> elementAdapter = new Gson().getAdapter(JsonElement.class);
-
- @Override
- public void write(JsonWriter out, StandardCoderObject value) throws IOException {
- elementAdapter.write(out, value.getData());
- }
-
- @Override
- public StandardCoderObject read(JsonReader in) throws IOException {
- return new StandardCoderObject(elementAdapter.read(in));
- }
- }
}
-/*
+/*-
* ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.common.utils.coder;
-import com.google.gson.JsonElement;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.Serial;
import java.io.Serializable;
-import lombok.AccessLevel;
-import lombok.AllArgsConstructor;
-import lombok.Getter;
/**
* Object type used by the {@link StandardCoder}. Different serialization tools have
- * different "standard objects". For instance, GSON uses {@link JsonElement}. This class
+ * different "standard objects". For instance, Jackson uses {@link JsonNode}. This class
* wraps that object so that it can be used without exposing the object, itself.
*/
-@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class StandardCoderObject implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
+ private final transient JsonNode data;
- /**
- * Data wrapped by this.
- */
- /*
- * this should not be transient, but since it isn't serializable, we're stuck with it
- * until there's time to address the issue
- */
- @Getter(AccessLevel.PROTECTED)
- private final transient JsonElement data;
-
- /**
- * Constructs the object.
- */
public StandardCoderObject() {
- data = null;
+ this.data = null;
+ }
+
+ @JsonCreator
+ public StandardCoderObject(JsonNode data) {
+ this.data = data;
+ }
+
+ @JsonValue
+ public JsonNode value() {
+ return data;
}
/**
* @return the field value or {@code null} if the field does not exist or is not a primitive
*/
public String getString(Object... fields) {
-
- JsonElement jel = data;
-
+ JsonNode node = this.data;
for (Object field : fields) {
- if (jel == null) {
+ if (node == null) {
return null;
}
-
if (field instanceof String) {
- jel = getFieldFromObject(jel, field.toString());
-
+ node = getFieldFromObject(node, (String) field);
} else if (field instanceof Integer) {
- jel = getItemFromArray(jel, (int) field);
-
+ node = getItemFromArray(node, (Integer) field);
} else {
throw new IllegalArgumentException("subscript is not a string or integer: " + field);
}
}
-
- return (jel != null && jel.isJsonPrimitive() ? jel.getAsString() : null);
+ return (node != null && (node.isValueNode() || node.isTextual())) ? node.asText() : null;
}
/**
* @param field name of the field from which to extract the item
* @return the item, or {@code null} if the element is not an object or if the field does not exist
*/
- protected JsonElement getFieldFromObject(JsonElement element, String field) {
- if (!element.isJsonObject()) {
- return null;
- }
-
- return element.getAsJsonObject().get(field);
+ protected JsonNode getFieldFromObject(JsonNode element, String field) {
+ return element.isObject() ? element.get(field) : null;
}
/**
* @param index index of the item to extract
* @return the item, or {@code null} if the element is not an array or if the index is out of bounds
*/
- protected JsonElement getItemFromArray(JsonElement element, int index) {
+ protected JsonNode getItemFromArray(JsonNode element, int index) {
if (index < 0) {
throw new IllegalArgumentException("subscript is invalid: " + index);
}
-
- if (!element.isJsonArray()) {
- return null;
- }
-
- var array = element.getAsJsonArray();
-
- if (index >= array.size()) {
+ if (!element.isArray()) {
return null;
}
+ var array = (ArrayNode) element;
+ return index >= array.size() ? null : array.get(index);
+ }
- return array.get(index);
+ protected JsonNode getData() {
+ return this.data;
}
}
/*-
* ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
+ * Modification Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import java.io.Writer;
/**
- * YAML encoder and decoder using the "standard" mechanism, which is currently gson.
+ * YAML encoder and decoder using the "standard" mechanism, which is currently jackson.
* All the methods perform conversion to/from YAML (instead of JSON).
*/
public class StandardYamlCoder extends StandardCoder {
+
private final YamlJsonTranslator translator;
- /**
- * Constructs the object.
- */
public StandardYamlCoder() {
- translator = new YamlJsonTranslator(gson) {
- @Override
- protected <T> T convertFromDouble(Class<T> clazz, T value) {
- return StandardYamlCoder.this.convertFromDouble(clazz, value);
- }
- };
+ this.translator = new YamlJsonTranslator();
}
@Override
protected String toPrettyJson(Object object) {
- // YAML is already "pretty"
return toJson(object);
}
/*-
* ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.common.utils.coder;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonNull;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonPrimitive;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.NullNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.node.ValueNode;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
-import java.time.Instant;
import java.util.ArrayList;
-import java.util.List;
-import java.util.Map.Entry;
-import lombok.AllArgsConstructor;
-import org.onap.policy.common.gson.InstantTypeAdapter;
+import java.util.Iterator;
+import java.util.Map;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.emitter.Emitter;
/**
* YAML-JSON translator. The methods may throw either of the runtime exceptions,
* YAMLException or JsonSyntaxException.
- * <p/>
- * Note: if the invoker wishes Double to be converted to Integer/Long when type
- * Object.class is requested, then a Gson object must be used that will perform the
- * translation. In addition, the {@link #convertFromDouble(Class, Object)} method should
- * be overridden with an appropriate conversion method.
*/
-@AllArgsConstructor
public class YamlJsonTranslator {
- /**
- * Object to be used to translate between YAML and JsonElement.
- */
- private final Gson gson;
+ private final ObjectMapper mapper;
/**
* Constructs the object.
*/
public YamlJsonTranslator() {
- GsonBuilder builder = new GsonBuilder();
- builder.registerTypeAdapter(Instant.class, new InstantTypeAdapter());
- gson = builder.create();
+ this.mapper = new ObjectMapper();
+ this.mapper.findAndRegisterModules(); // for Instant
+ // Configure to handle empty beans
+ this.mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ // Configure to ignore unknown properties (similar to Gson behavior)
+ this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ // Configure to handle null values more gracefully
+ this.mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
+ // Configure to handle circular references
+ this.mapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
}
/**
* @param object POJO to be translated
*/
public void toYaml(Writer target, Object object) {
- var dumper = new DumperOptions();
- var serializer = new Serializer(new Emitter(target, dumper), new Resolver(), dumper, null);
-
try {
+ var json = mapper.valueToTree(object);
+ var yamlNode = makeYaml(json);
+
+ var options = new DumperOptions();
+ var serializer = new Serializer(new Emitter(target, options), new Resolver(), options, null);
serializer.open();
- serializer.serialize(makeYaml(toJsonTree(object)));
+ serializer.serialize(yamlNode);
serializer.close();
-
} catch (IOException e) {
throw new YAMLException(e);
}
}
- /**
- * Translates a POJO into a JsonElement.
- *
- * @param object POJO to be translated
- * @return a JsonElement representing the original object
- */
- protected JsonElement toJsonTree(Object object) {
- return gson.toJsonTree(object);
- }
-
/**
* Translates a YAML string to a POJO.
*
*/
public <T> T fromYaml(Reader source, Class<T> clazz) {
var node = new Yaml().compose(source);
- return fromJson(makeJson(node), clazz);
- }
-
- /**
- * Translates a JsonElement to a POJO of the given class.
- *
- * @param jel element to be translated
- * @param clazz class of POJO to be created
- * @return a POJO representing the original element
- */
- protected <T> T fromJson(JsonElement jel, Class<T> clazz) {
- return convertFromDouble(clazz, gson.fromJson(jel, clazz));
- }
-
- /**
- * Converts a value from Double to Integer/Long, walking the value's contents if it's
- * a List/Map. Only applies if the specified class refers to the Object class.
- * Otherwise, it leaves the value unchanged.
- * <p/>
- * The default method simply returns the original value.
- *
- * @param clazz class of object to be decoded
- * @param value value to be converted
- * @return the converted value
- */
- protected <T> T convertFromDouble(Class<T> clazz, T value) {
- return value;
+ var json = makeJson(node);
+ try {
+ return mapper.treeToValue(json, clazz);
+ } catch (Exception ex) {
+ throw new YAMLException(ex);
+ }
}
/**
- * Converts an arbitrary gson element into a corresponding Yaml node.
+ * Converts an arbitrary json element into a corresponding Yaml node.
*
- * @param jel gson element to be converted
+ * @param node json element to be converted
* @return a yaml node corresponding to the element
*/
- protected Node makeYaml(JsonElement jel) {
- if (jel.isJsonArray()) {
- return makeYamlSequence((JsonArray) jel);
-
- } else if (jel.isJsonObject()) {
- return makeYamlMap((JsonObject) jel);
-
- } else if (jel.isJsonPrimitive()) {
- return makeYamlPrim((JsonPrimitive) jel);
-
- } else {
- return new ScalarNode(Tag.NULL, "", null, null, DumperOptions.ScalarStyle.PLAIN);
+ protected Node makeYaml(JsonNode node) {
+ if (node.isArray()) {
+ return makeYamlSequence((ArrayNode) node);
+ }
+ if (node.isObject()) {
+ return makeYamlMap((ObjectNode) node);
}
+ if (node.isValueNode()) {
+ return makeYamlPrim((ValueNode) node);
+ }
+
+ return new ScalarNode(Tag.NULL, "", null, null, DumperOptions.ScalarStyle.PLAIN);
}
/**
- * Converts an arbitrary gson array into a corresponding Yaml sequence.
+ * Converts an arbitrary json array into a corresponding Yaml sequence.
*
- * @param jel gson element to be converted
+ * @param array json element to be converted
* @return a yaml node corresponding to the element
*/
- protected SequenceNode makeYamlSequence(JsonArray jel) {
- List<Node> nodes = new ArrayList<>(jel.size());
- jel.forEach(item -> nodes.add(makeYaml(item)));
-
- return new SequenceNode(Tag.SEQ, true, nodes, null, null, DumperOptions.FlowStyle.AUTO);
+ protected Node makeYamlSequence(ArrayNode array) {
+ var nodes = new ArrayList<Node>();
+ array.forEach(item -> nodes.add(makeYaml(item)));
+ return new SequenceNode(Tag.SEQ, nodes, DumperOptions.FlowStyle.AUTO);
}
/**
- * Converts an arbitrary gson object into a corresponding Yaml map.
+ * Converts an arbitrary json object into a corresponding Yaml map.
*
- * @param jel gson element to be converted
+ * @param obj json element to be converted
* @return a yaml node corresponding to the element
*/
- protected MappingNode makeYamlMap(JsonObject jel) {
- List<NodeTuple> nodes = new ArrayList<>(jel.size());
-
- for (Entry<String, JsonElement> entry : jel.entrySet()) {
- Node key = new ScalarNode(Tag.STR, entry.getKey(), null, null, DumperOptions.ScalarStyle.PLAIN);
- Node value = makeYaml(entry.getValue());
-
- nodes.add(new NodeTuple(key, value));
+ protected Node makeYamlMap(ObjectNode obj) {
+ var tuples = new ArrayList<NodeTuple>();
+ Iterator<Map.Entry<String, JsonNode>> it = obj.fields();
+
+ while (it.hasNext()) {
+ var entry = it.next();
+ var key = new ScalarNode(Tag.STR, entry.getKey(), null, null, DumperOptions.ScalarStyle.PLAIN);
+ var value = makeYaml(entry.getValue());
+ tuples.add(new NodeTuple(key, value));
}
- return new MappingNode(Tag.MAP, true, nodes, null, null, DumperOptions.FlowStyle.AUTO);
+ return new MappingNode(Tag.MAP, tuples, DumperOptions.FlowStyle.AUTO);
}
/**
- * Converts an arbitrary gson primitive into a corresponding Yaml scalar.
+ * Converts an arbitrary json primitive into a corresponding Yaml scalar.
*
- * @param jel gson element to be converted
+ * @param node json element to be converted
* @return a yaml node corresponding to the element
*/
- protected ScalarNode makeYamlPrim(JsonPrimitive jel) {
+ protected Node makeYamlPrim(ValueNode node) {
Tag tag;
- if (jel.isNumber()) {
- Class<? extends Number> clazz = jel.getAsNumber().getClass();
-
- if (clazz == Double.class || clazz == Float.class) {
- tag = Tag.FLOAT;
-
- } else {
- tag = Tag.INT;
- }
-
- } else if (jel.isBoolean()) {
+ if (node.isNumber()) {
+ tag = (node.isFloatingPointNumber()) ? Tag.FLOAT : Tag.INT;
+ } else if (node.isBoolean()) {
tag = Tag.BOOL;
-
} else {
- // treat anything else as a string
tag = Tag.STR;
}
-
- return new ScalarNode(tag, jel.getAsString(), null, null, DumperOptions.ScalarStyle.PLAIN);
+ return new ScalarNode(tag, node.asText(), null, null, DumperOptions.ScalarStyle.PLAIN);
}
/**
- * Converts an arbitrary Yaml node into a corresponding gson element.
+ * Converts an arbitrary Yaml node into a corresponding json element.
*
* @param node node to be converted
- * @return a gson element corresponding to the node
+ * @return a json element corresponding to the node
*/
- protected JsonElement makeJson(Node node) {
- if (node instanceof MappingNode mappingNode) {
- return makeJsonObject(mappingNode);
-
- } else if (node instanceof SequenceNode sequenceNode) {
- return makeJsonArray(sequenceNode);
-
- } else {
- return makeJsonPrim((ScalarNode) node);
+ protected JsonNode makeJson(Node node) {
+ if (node == null) {
+ return NullNode.getInstance();
}
-
- // yaml doesn't appear to use anchor nodes when decoding so ignore them for now
+ return switch (node) {
+ case MappingNode mapping -> makeJsonObject(mapping);
+ case SequenceNode seq -> makeJsonArray(seq);
+ case ScalarNode scalar -> makeJsonPrim(scalar);
+ default -> throw new IllegalStateException("Unexpected value: " + node);
+ };
}
/**
- * Converts a Yaml sequence into a corresponding gson array.
+ * Converts a Yaml sequence into a corresponding json array.
*
- * @param node node to be converted
- * @return a gson element corresponding to the node
+ * @param seq node to be converted
+ * @return a json element corresponding to the node
*/
- protected JsonArray makeJsonArray(SequenceNode node) {
- List<Node> nodes = node.getValue();
-
- var array = new JsonArray(nodes.size());
- nodes.forEach(subnode -> array.add(makeJson(subnode)));
-
+ protected JsonNode makeJsonArray(SequenceNode seq) {
+ var array = mapper.createArrayNode();
+ for (var n : seq.getValue()) {
+ array.add(makeJson(n));
+ }
return array;
}
/**
* Converts a Yaml map into a corresponding gson object.
*
- * @param node node to be converted
- * @return a gson element corresponding to the node
+ * @param map node to be converted
+ * @return a json element corresponding to the node
*/
- protected JsonObject makeJsonObject(MappingNode node) {
- var obj = new JsonObject();
-
- for (NodeTuple tuple : node.getValue()) {
- var key = tuple.getKeyNode();
- String skey = ((ScalarNode) key).getValue();
-
- obj.add(skey, makeJson(tuple.getValueNode()));
+ protected JsonNode makeJsonObject(MappingNode map) {
+ var obj = mapper.createObjectNode();
+ for (var tuple : map.getValue()) {
+ var key = ((ScalarNode) tuple.getKeyNode()).getValue();
+ obj.set(key, makeJson(tuple.getValueNode()));
}
-
return obj;
}
/**
- * Converts a Yaml scalar into a corresponding gson primitive.
+ * Converts a Yaml scalar into a corresponding json primitive.
*
* @param node node to be converted
- * @return a gson element corresponding to the node
+ * @return a json element corresponding to the node
*/
- protected JsonElement makeJsonPrim(ScalarNode node) {
- try {
- var tag = node.getTag();
-
- if (tag == Tag.INT) {
- return new JsonPrimitive(Long.valueOf(node.getValue()));
-
- } else if (tag == Tag.FLOAT) {
- return new JsonPrimitive(Double.valueOf(node.getValue()));
-
- } else if (tag == Tag.BOOL) {
- return new JsonPrimitive(Boolean.valueOf(node.getValue()));
-
- } else if (tag == Tag.NULL) {
- return JsonNull.INSTANCE;
-
- } else {
- // treat anything else as a string
- return new JsonPrimitive(node.getValue());
+ protected JsonNode makeJsonPrim(ScalarNode node) {
+ var tag = node.getTag();
+ var val = node.getValue();
+
+ // Handle null values explicitly
+ if (tag == Tag.NULL || val == null || "null".equals(val) || val.isEmpty()) {
+ return NullNode.getInstance();
+ }
+ if (tag == Tag.INT) {
+ // Try to parse as int first, then long if it's too big
+ try {
+ return mapper.getNodeFactory().numberNode(Integer.parseInt(val));
+ } catch (NumberFormatException e) {
+ return mapper.getNodeFactory().numberNode(Long.parseLong(val));
}
-
- } catch (NumberFormatException ex) {
- // just treat it as a string
- return new JsonPrimitive(node.getValue());
}
+ if (tag == Tag.FLOAT) {
+ // Try to parse as float first, then double if needed
+ try {
+ float floatVal = Float.parseFloat(val);
+ if (!Float.isInfinite(floatVal)) {
+ return mapper.getNodeFactory().numberNode(floatVal);
+ }
+ } catch (NumberFormatException ignored) {
+ // Fall through to double
+ }
+ return mapper.getNodeFactory().numberNode(Double.parseDouble(val));
+ }
+ if (tag == Tag.BOOL) {
+ return mapper.getNodeFactory().booleanNode(Boolean.parseBoolean(val));
+ }
+ return mapper.getNodeFactory().textNode(val);
}
-}
+
+}
\ No newline at end of file
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * policy-management
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.utils.gson;
-
-import com.google.gson.TypeAdapter;
-import com.google.gson.stream.JsonReader;
-import java.io.IOException;
-
-/**
- * Gson serializer, providing stub implementation of "read".
- *
- * @param <T> type of object that this serializes
- */
-public abstract class GsonSerializer<T> extends TypeAdapter<T> {
- @Override
- public T read(JsonReader in) throws IOException {
- throw new UnsupportedOperationException("read from pseudo TypeAdapter");
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * policy-management
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.utils.gson;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import com.google.re2j.Pattern;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map.Entry;
-import lombok.AccessLevel;
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import org.apache.commons.jexl3.JexlBuilder;
-import org.apache.commons.jexl3.JexlContext;
-import org.apache.commons.jexl3.JexlEngine;
-import org.apache.commons.jexl3.MapContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Utilities used to test encoding and decoding of Policy objects.
- */
-@Getter
-@AllArgsConstructor(access = AccessLevel.PROTECTED)
-public class GsonTestUtils {
-
- private static final Logger logger = LoggerFactory.getLogger(GsonTestUtils.class);
-
- /**
- * Matches script items, of the form ${xxx}, within text.
- */
- private static final Pattern SCRIPT_PAT = Pattern.compile("\\$\\{([^}]+)\\}");
-
- /**
- * Engine used to interpolate strings before they're compared.
- */
- private static JexlEngine engineInstance = null;
-
- /**
- * Used to encode and decode an object via gson.
- */
- private Gson gson;
-
- /**
- * Constructs the object.
- */
- public GsonTestUtils() {
- GsonTestUtils other = new GsonTestUtilsBuilder().build();
-
- gson = other.gson;
- }
-
- /**
- * Serializes and then deserializes an object using gson.
- *
- * @param object the object to be serialized
- * @param clazz the class of object to deserialize
- * @return the deserialized object
- */
- public <T> T gsonRoundTrip(T object, Class<T> clazz) {
- String sgson = gsonEncode(object);
- return gson.fromJson(sgson, clazz);
- }
-
- /**
- * Encodes an object using gson and then compares it to the expected value, after
- * sorting the elements. The class name is used to find the json file, whose contents
- * is interpolated (i.e., script elements, of the form ${obj.xxx}, are expanded).
- *
- * @param object the object to be encoded
- * @param expected the expected value
- */
- public void compareGson(Object object, Class<?> expected) {
- compareGson(object, new File(expected.getSimpleName() + ".json"));
- }
-
- /**
- * Encodes an object using gson and then compares it to the expected value, after
- * sorting the elements. The content of the file is interpolated (i.e., script
- * elements, of the form ${obj.xxx}, are expanded).
- *
- * @param object the object to be encoded
- * @param expected the expected value
- */
- public void compareGson(Object object, File expected) {
- // file is not required to have a full path - find it via getResource()
- var url = object.getClass().getResource(expected.getName());
- if (url == null) {
- throw new JsonParseException(new FileNotFoundException(expected.getName()));
- }
-
- String expectedText;
- try {
- expectedText = readFile(new File(url.getFile()));
-
- } catch (IOException e) {
- throw new JsonParseException("error reading: " + expected, e);
- }
-
- compareGson(object, expectedText);
- }
-
- /**
- * Encodes an object using gson and then compares it to the expected value, after
- * sorting the elements. The expected value is interpolated (i.e., script elements, of
- * the form ${obj.xxx}, are expanded).
- *
- * @param object the object to be encoded
- * @param expected the expected value
- */
- public void compareGson(Object object, String expected) {
- String result = applyScripts(expected, object);
- compareGson(object, gson.fromJson(result, JsonElement.class));
- }
-
- /**
- * Encodes an object using gson and then compares it to the expected value, after
- * sorting the elements.
- *
- * @param object the object to be encoded
- * @param expected the expected value
- */
- public void compareGson(Object object, JsonElement expected) {
- String sgson = gsonEncode(object);
-
- JsonElement gsonjo = reorder(gson.fromJson(sgson, JsonElement.class));
- JsonElement expjo = reorder(expected);
-
- /*
- * As this method is only used within junit tests, it is OK to use assert calls,
- * thus sonar is disabled.
- */
- assertEquals(expjo.toString(), gsonjo.toString()); // NOSONAR
- }
-
- /**
- * Reads the content of a file.
- * @param file file to read
- * @return the content of the file
- * @throws IOException if an error occurs
- */
- protected String readFile(File file) throws IOException {
- return Files.readString(file.toPath());
- }
-
-
- /**
- * Interpolates script elements, of the form ${obj.xxx}, within some text. The script
- * is evaluated via javascript, where "obj" references the object used by each script
- * element.
- *
- * @param object object to be used by the script
- * @param text text to be evaluated
- * @return the text, after interpolating the script elements
- */
- public String applyScripts(String text, Object object) {
- var mat = SCRIPT_PAT.matcher(text);
- if (!mat.find()) {
- // contains no script elements - just return it as is
- return text;
- }
-
- // bind the object to the variable, "obj"
- JexlEngine eng = getEngine();
- JexlContext context = new MapContext();
- context.set("obj", object);
-
- // work our way through the text, interpolating script elements as we go
- var bldr = new StringBuilder();
- var ilast = 0;
- mat.reset();
- while (mat.find(ilast)) {
- // append segment that appears between last match and this
- int inext = mat.start();
- bldr.append(text, ilast, inext);
-
- // next match begins after the current match
- ilast = mat.end();
-
- // interpolate the script
- String script = mat.group(1);
- /*
- * Note: must use "eng" instead of "engineInstance" to ensure that we use
- * the same engine that's associated with the bindings.
- */
- Object result = eng.createExpression(script).evaluate(context);
- bldr.append(result == null ? "null" : result.toString());
- }
-
- // append final segment
- bldr.append(text.substring(ilast));
-
- return bldr.toString();
- }
-
- /**
- * Gets the script engine instance.
- *
- * @return the script engine
- */
- private static JexlEngine getEngine() {
- if (engineInstance == null) {
- // race condition here, but it's ok to overwrite with a new engine
- engineInstance = new JexlBuilder().create();
- }
-
- return engineInstance;
- }
-
- /**
- * Encodes an object using gson.
- *
- * @param object the object to be encoded
- * @return the encoded object
- */
- public String gsonEncode(Object object) {
- String sgson = gson.toJson(object);
- logger.debug("gson={}", sgson);
- return sgson;
- }
-
- /**
- * Recursively re-orders a json object, arranging the keys alphabetically and removing
- * null items.
- *
- * @param jsonObj object from which nulls are to be removed
- * @return a new object, without the null items
- */
- public JsonObject reorder(JsonObject jsonObj) {
- var newjo = new JsonObject();
-
- // sort the keys before copying to the new object
- List<Entry<String, JsonElement>> sortedSet = new ArrayList<>(jsonObj.entrySet());
- sortedSet.sort(Entry.comparingByKey());
-
- for (Entry<String, JsonElement> ent : sortedSet) {
- JsonElement val = ent.getValue();
- if (val.isJsonNull()) {
- continue;
- }
-
- newjo.add(ent.getKey(), reorder(val));
- }
-
- return newjo;
- }
-
- /**
- * Recursively re-orders a json array, arranging the keys alphabetically and removing
- * null items.
- *
- * @param jsonArray array from which nulls are to be removed
- * @return a new array, with null items removed from all elements
- */
- public JsonArray reorder(JsonArray jsonArray) {
- var newarr = new JsonArray();
- for (JsonElement ent : jsonArray) {
- newarr.add(reorder(ent));
- }
-
- return newarr;
- }
-
- /**
- * Recursively re-orders a json element, arranging the keys alphabetically and
- * removing null items.
- *
- * @param jsonEl element from which nulls are to be removed
- * @return a new element, with null items removed
- */
- public JsonElement reorder(JsonElement jsonEl) {
- if (jsonEl == null) {
- return null;
-
- } else if (jsonEl.isJsonObject()) {
- return reorder(jsonEl.getAsJsonObject());
-
- } else if (jsonEl.isJsonArray()) {
- return reorder(jsonEl.getAsJsonArray());
-
- } else {
- return jsonEl;
- }
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * policy-management
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.utils.gson;
-
-import com.google.gson.GsonBuilder;
-import com.google.gson.TypeAdapterFactory;
-import org.onap.policy.common.gson.JacksonHandler;
-
-/**
- * Used to builder a utility class.
- */
-public class GsonTestUtilsBuilder {
- private final GsonBuilder gsonBldr;
-
- /**
- * Constructs the object.
- */
- public GsonTestUtilsBuilder() {
- gsonBldr = new GsonBuilder();
-
- // register jackson behaviors with the builder
- JacksonHandler.configBuilder(gsonBldr);
- }
-
- /**
- * Builds the utility.
- *
- * @return a new utility
- */
- public GsonTestUtils build() {
- return new GsonTestUtils(gsonBldr.create());
- }
-
- /**
- * Adds gson support for serializing a mock of a class.
- *
- * @param clazz mocked class to be supported
- * @param sgson gson serializer
- */
- protected <T> void addMock(Class<T> clazz, TypeAdapterFactory sgson) {
- gsonBldr.registerTypeAdapterFactory(sgson);
- }
-}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2026 OpenInfra Foundation Europe. All rights reserved.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.utils.jackson;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.NullNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.re2j.Pattern;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import lombok.Getter;
+
+/**
+ * Utilities used to test encoding and decoding of Policy objects.
+ */
+@Getter
+public class JacksonTestUtils {
+
+ /**
+ * Matches script items, of the form ${xxx}, within text.
+ */
+ private static final Pattern SCRIPT_PAT = Pattern.compile("\\$\\{([^}]+)\\}");
+
+ /**
+ * Engine used to interpolate strings before they're compared.
+ */
+
+ private final ObjectMapper objectMapper;
+
+ /**
+ * Constructs the object.
+ */
+ public JacksonTestUtils() {
+ this.objectMapper = new ObjectMapper();
+ }
+
+ /**
+ * Encodes an object using jackson and then compares it to the expected value, after
+ * sorting the elements. The class name is used to find the json file, whose contents
+ * is interpolated (i.e., script elements, of the form ${obj.xxx}, are expanded).
+ *
+ * @param object the object to be encoded
+ * @param expected the expected value
+ */
+ public void compareJson(Object object, Class<?> expected) throws JsonParseException {
+ compareJson(object, new File(expected.getSimpleName() + ".json"));
+ }
+
+ /**
+ * Encodes an object using jackson and then compares it to the expected value, after
+ * sorting the elements. The content of the file is interpolated (i.e., script
+ * elements, of the form ${obj.xxx}, are expanded).
+ *
+ * @param object the object to be encoded
+ * @param expected the expected value
+ */
+ public void compareJson(Object object, File expected) throws JsonParseException {
+ var url = object.getClass().getResource(expected.getName());
+ if (url == null) {
+ throw new JsonParseException(new FileNotFoundException(expected.getName()).getMessage());
+ }
+
+ String expectedText;
+ try {
+ expectedText = readFile(new File(url.getFile()));
+ } catch (IOException e) {
+ throw new JsonParseException("error reading: " + e.getMessage());
+ }
+
+ compareJson(object, expectedText);
+ }
+
+ /**
+ * Encodes an object using jackson and then compares it to the expected value, after
+ * sorting the elements. The expected value is interpolated (i.e., script elements, of
+ * the form ${obj.xxx}, are expanded).
+ *
+ * @param object the object to be encoded
+ * @param expected the expected value
+ */
+ public void compareJson(Object object, String expected) throws JsonParseException {
+ try {
+ compareJson(object, objectMapper.readTree(expected));
+ } catch (IOException e) {
+ throw new JsonParseException(e.getMessage());
+ }
+ }
+
+ /**
+ * Encodes an object using jackson and then compares it to the expected value, after
+ * sorting the elements.
+ *
+ * @param object the object to be encoded
+ * @param expected the expected value
+ */
+ public void compareJson(Object object, JsonNode expected) throws JsonParseException {
+ try {
+ var json = objectMapper.writeValueAsString(object);
+
+ var actualNode = reorder(objectMapper.readTree(json));
+ var expectedNode = reorder(expected);
+
+ /*
+ * As this method is only used within junit tests, it is OK to use assert calls,
+ * thus sonar is disabled.
+ */
+ assertEquals(expectedNode.toString(), actualNode.toString()); // NOSONAR
+ } catch (IOException e) {
+ throw new JsonParseException(e.getMessage());
+ }
+ }
+
+
+
+ /**
+ * Reads the content of a file.
+ * @param file file to read
+ * @return the content of the file
+ * @throws IOException if an error occurs
+ */
+ protected String readFile(File file) throws IOException {
+ return Files.readString(file.toPath());
+ }
+
+
+ /**
+ * Recursively re-orders a JSON object, arranging the keys alphabetically
+ * and removing null items.
+ */
+ public ObjectNode reorder(ObjectNode jsonObj) {
+ var newObj = objectMapper.createObjectNode();
+
+ // Collect and sort fields by key
+ List<Map.Entry<String, JsonNode>> fields = new ArrayList<>();
+ jsonObj.fields().forEachRemaining(fields::add);
+ fields.sort(Map.Entry.comparingByKey());
+
+ for (var entry : fields) {
+ var value = entry.getValue();
+ if (value == null || value.isNull()) {
+ continue;
+ }
+
+ newObj.set(entry.getKey(), reorder(value));
+ }
+
+ return newObj;
+ }
+
+ /**
+ * Recursively re-orders a JSON array, removing null items
+ * from all elements.
+ */
+ public ArrayNode reorder(ArrayNode jsonArray) {
+ var newArr = objectMapper.createArrayNode();
+
+ for (var element : jsonArray) {
+ if (element == null || element.isNull()) {
+ continue;
+ }
+ newArr.add(reorder(element));
+ }
+
+ return newArr;
+ }
+
+ /**
+ * Recursively re-orders a JSON node, arranging object keys
+ * alphabetically and removing null items.
+ */
+ public JsonNode reorder(JsonNode jsonNode) {
+ if (jsonNode == null || jsonNode.isNull()) {
+ return NullNode.getInstance();
+ }
+
+ if (jsonNode.isObject()) {
+ return reorder((ObjectNode) jsonNode);
+ }
+
+ if (jsonNode.isArray()) {
+ return reorder((ArrayNode) jsonNode);
+ }
+
+ // Primitive nodes are returned as-is
+ return jsonNode;
+ }
+
+}
* ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
this.name = name;
}
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
@Override
public int hashCode() {
final int prime = 31;
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import org.junit.jupiter.api.Test;
-
-class DoubleConverterTest {
-
- @Test
- void testConvertFromDoubleObject() {
- // these should be unchanged
- assertNull(DoubleConverter.convertFromDouble((Object) null));
- assertEquals("hello", DoubleConverter.convertFromDouble("hello"));
- assertEquals("10.0", DoubleConverter.convertFromDouble("10.0"));
- assertEquals(12.5, DoubleConverter.convertFromDouble(12.5));
- assertEquals(12, DoubleConverter.convertFromDouble(12));
- assertEquals(12L, DoubleConverter.convertFromDouble(12L));
-
- // positive and negative int
- assertEquals(10, DoubleConverter.convertFromDouble(10.0));
- assertEquals(-10, DoubleConverter.convertFromDouble(-10.0));
-
- // positive and negative long
- assertEquals(100000000000L, DoubleConverter.convertFromDouble(100000000000.0));
- assertEquals(-100000000000L, DoubleConverter.convertFromDouble(-100000000000.0));
-
- // list
- List<Object> list = new ArrayList<>();
- list.add("list");
- list.add(null);
- list.add(21.0);
- list = (List<Object>) DoubleConverter.convertFromDouble((Object) list);
- assertEquals("[list, null, 21]", list.toString());
-
- // map
- Map<String, Object> map = new LinkedHashMap<>();
- map.put("map-A", "map-value");
- map.put("map-B", null);
- map.put("map-C", 22.0);
- map = (Map<String, Object>) DoubleConverter.convertFromDouble((Object) map);
- assertEquals("{map-A=map-value, map-B=null, map-C=22}", map.toString());
- }
-
- @Test
- void testConvertFromDoubleList() {
- // null is ok
- DoubleConverter.convertFromDouble((List<Object>) null);
-
- List<Object> list = new ArrayList<>();
- list.add("world");
- list.add(20.0);
-
- List<Object> nested = new ArrayList<>();
- list.add(nested);
- nested.add(30.0);
-
- DoubleConverter.convertFromDouble(list);
-
- assertEquals("[world, 20, [30]]", list.toString());
- }
-
- @Test
- void testConvertFromDoubleMap() {
- // null is ok
- DoubleConverter.convertFromDouble((Map<String, Object>) null);
-
- Map<String, Object> map = new LinkedHashMap<>();
- map.put("keyA", "valueA");
- map.put("keyB", 200.0);
-
- Map<String, Object> nested = new LinkedHashMap<>();
- map.put("keyC", nested);
- nested.put("nested-key", 201.0);
-
- DoubleConverter.convertFromDouble(map);
- assertEquals("{keyA=valueA, keyB=200, keyC={nested-key=201}}", map.toString());
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2025 Nordix Foundation.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import jakarta.ws.rs.core.MediaType;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.time.Instant;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
-import java.time.ZonedDateTime;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-import lombok.ToString;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-class GsonMessageBodyHandlerTest {
- private static final String GEN_TYPE = "some-type";
- private static final String[] subtypes = {"json", "jSoN", "hello+json", "javascript", "x-javascript", "x-json"};
-
- @SuppressWarnings("rawtypes")
- private static final Class GEN_CLASS = MyObject.class;
-
- @SuppressWarnings("unchecked")
- private static final Class<Object> CLASS_OBJ = GEN_CLASS;
-
- private GsonMessageBodyHandler hdlr;
-
- @BeforeEach
- void setUp() {
- hdlr = new GsonMessageBodyHandler();
- }
-
- @Test
- void testIsWriteable() {
- // null media type
- assertTrue(hdlr.isWriteable(null, null, null, null));
-
- for (String subtype : subtypes) {
- assertTrue(hdlr.isWriteable(null, null, null, new MediaType(GEN_TYPE, subtype)), "writeable " + subtype);
-
- }
-
- // the remaining should be FALSE
-
- // null subtype
- assertFalse(hdlr.isWriteable(null, null, null, new MediaType(GEN_TYPE, null)));
-
- // text subtype
- assertFalse(hdlr.isWriteable(null, null, null, MediaType.TEXT_HTML_TYPE));
- }
-
- @Test
- void testGetSize() {
- assertEquals(-1, hdlr.getSize(null, null, null, null, null));
- }
-
- @Test
- void testWriteTo_testReadFrom() throws Exception {
- ByteArrayOutputStream outstr = new ByteArrayOutputStream();
- MyObject obj1 = new MyObject(10);
- hdlr.writeTo(obj1, obj1.getClass(), CLASS_OBJ, null, null, null, outstr);
-
- Object obj2 = hdlr.readFrom(CLASS_OBJ, CLASS_OBJ, null, null, null,
- new ByteArrayInputStream(outstr.toByteArray()));
- assertEquals(obj1.toString(), obj2.toString());
- }
-
- @Test
- void testWriteTo_DifferentTypes() throws Exception {
- ByteArrayOutputStream outstr = new ByteArrayOutputStream();
-
- // use a derived type, but specify the base type when writing
- MyObject obj1 = new MyObject(10) {};
- hdlr.writeTo(obj1, obj1.getClass(), CLASS_OBJ, null, null, null, outstr);
-
- Object obj2 = hdlr.readFrom(CLASS_OBJ, CLASS_OBJ, null, null, null,
- new ByteArrayInputStream(outstr.toByteArray()));
- assertEquals(obj1.toString(), obj2.toString());
- }
-
- @Test
- void testIsReadable() {
- // null media type
- assertTrue(hdlr.isReadable(null, null, null, null));
-
- // null subtype
- assertFalse(hdlr.isReadable(null, null, null, new MediaType(GEN_TYPE, null)));
-
- for (String subtype : subtypes) {
- assertTrue(hdlr.isReadable(null, null, null, new MediaType(GEN_TYPE, subtype)), "readable " + subtype);
-
- }
-
- // the remaining should be FALSE
-
- // null subtype
- assertFalse(hdlr.isReadable(null, null, null, new MediaType(GEN_TYPE, null)));
-
- // text subtype
- assertFalse(hdlr.isReadable(null, null, null, MediaType.TEXT_HTML_TYPE));
- }
-
- @Test
- void testReadFrom_DifferentTypes() throws Exception {
- ByteArrayOutputStream outstr = new ByteArrayOutputStream();
- MyObject obj1 = new MyObject(10);
- hdlr.writeTo(obj1, obj1.getClass(), CLASS_OBJ, null, null, null, outstr);
-
- // use a derived type, but specify the base type when reading
- @SuppressWarnings("rawtypes")
- Class clazz = MyObject.class;
-
- @SuppressWarnings("unchecked")
- Class<Object> objclazz = clazz;
-
- Object obj2 = hdlr.readFrom(objclazz, CLASS_OBJ, null, null, null,
- new ByteArrayInputStream(outstr.toByteArray()));
- assertEquals(obj1.toString(), obj2.toString());
- }
-
- @Test
- void testMapDouble() throws Exception {
- MyMap map = new MyMap();
- map.props = new HashMap<>();
- map.props.put("plainString", "def");
- map.props.put("negInt", -10);
- map.props.put("doubleVal", 12.5);
- map.props.put("posLong", 100000000000L);
-
- ByteArrayOutputStream outstr = new ByteArrayOutputStream();
- hdlr.writeTo(map, map.getClass(), map.getClass(), null, null, null, outstr);
-
- Object obj2 = hdlr.readFrom(Object.class, map.getClass(), null, null, null,
- new ByteArrayInputStream(outstr.toByteArray()));
- assertEquals(map.toString(), obj2.toString());
-
- map = (MyMap) obj2;
-
- assertEquals(-10, map.props.get("negInt"));
- assertEquals(100000000000L, map.props.get("posLong"));
- assertEquals(12.5, map.props.get("doubleVal"));
- }
-
- @Test
- void testInterestingFields() throws IOException {
- InterestingFields data = new InterestingFields();
- data.instant = Instant.ofEpochMilli(1583249713500L);
- data.uuid = UUID.fromString("a850cb9f-3c5e-417c-abfd-0679cdcd1ab0");
- data.localDate = LocalDateTime.of(2020, 2, 3, 4, 5, 6, 789000000);
- data.zonedDate = ZonedDateTime.of(2020, 2, 3, 4, 5, 6, 789000000, ZoneId.of("US/Eastern"));
-
- ByteArrayOutputStream outstr = new ByteArrayOutputStream();
- hdlr.writeTo(data, data.getClass(), data.getClass(), null, null, null, outstr);
-
- // ensure fields are encoded as expected
-
- // @formatter:off
- assertThat(outstr.toString(StandardCharsets.UTF_8))
- .contains("\"2020-03-03T15:35:13.500Z\"")
- .contains("\"2020-02-03T04:05:06.789\"")
- .contains("\"2020-02-03T04:05:06.789-05:00[US/Eastern]\"")
- .contains("a850cb9f-3c5e-417c-abfd-0679cdcd1ab0");
- // @formatter:on
-
- Object obj2 = hdlr.readFrom(Object.class, data.getClass(), null, null, null,
- new ByteArrayInputStream(outstr.toByteArray()));
- assertEquals(data.toString(), obj2.toString());
- }
-
-
- @ToString
- public static class MyObject {
- private int id;
-
- public MyObject() {
- super();
- }
-
- public MyObject(int id) {
- this.id = id;
- }
- }
-
- private static class MyMap {
- private Map<String, Object> props;
-
- @Override
- public String toString() {
- return props.toString();
- }
- }
-
- @ToString
- private static class InterestingFields {
- private LocalDateTime localDate;
- private Instant instant;
- private UUID uuid;
- private ZonedDateTime zonedDate;
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import java.time.Instant;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class InstantAsMillisTypeAdapterTest {
- private static Gson gson =
- new GsonBuilder().registerTypeAdapter(Instant.class, new InstantAsMillisTypeAdapter()).create();
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.instant = Instant.ofEpochMilli(1583249713500L);
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).doesNotContain("nanos").contains("1583249713500").doesNotContain("\"1583249713500\"")
- .doesNotContain("T");
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // null output
- data.instant = null;
- json = gson.toJson(data);
- data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // null input
- data2 = gson.fromJson("{\"instant\":null}", InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
- }
-
-
- @ToString
- private static class InterestingFields {
- private Instant instant;
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import java.time.Instant;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class InstantTypeAdapterTest {
- private static Gson gson =
- new GsonBuilder().registerTypeAdapter(Instant.class, new InstantTypeAdapter()).create();
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.instant = Instant.ofEpochMilli(1583249713500L);
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).doesNotContain("nanos").contains("\"2020-03-03T15:35:13.500Z\"")
- .doesNotContain("1583249713500");
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // try when the date-time string is invalid
- String json2 = json.replace("2020", "invalid-date");
- assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
- .hasMessageContaining("invalid date");
- }
-
-
- @ToString
- private static class InterestingFields {
- private Instant instant;
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modificaitons Copyright (C) 2023-2025 Nordix Foundation.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.FieldAttributes;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import java.io.Serial;
-import java.lang.reflect.GenericArrayType;
-import java.util.LinkedList;
-import java.util.TreeMap;
-import lombok.Getter;
-import lombok.Setter;
-import lombok.ToString;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-
-class JacksonExclusionStrategyTest {
-
- private static JacksonExclusionStrategy strategy;
- private static Gson gson;
-
- @BeforeAll
- static void setUpBeforeClass() {
- strategy = new JacksonExclusionStrategy();
- gson = new GsonBuilder().setExclusionStrategies(strategy).create();
- }
-
- @Test
- void testWithGson() {
- Derived data = new Derived();
- data.setId(10);
- data.setText("some text");
- data.setValue("some value");
-
- // no fields should be serialized
- String result = gson.toJson(data);
- assertEquals("{}", result);
-
- // no fields should be deserialized
- result = "{'id':20, 'text':'my text', 'value':'my value'}".replace('\'', '"');
- Derived data2 = gson.fromJson(result, Derived.class);
- assertEquals(new Derived().toString(), data2.toString());
- }
-
- @Test
- void testShouldSkipField() throws Exception {
- // should skip every field of Data
- assertTrue(strategy.shouldSkipField(new FieldAttributes(Data.class.getDeclaredField("id"))));
- assertTrue(strategy.shouldSkipField(new FieldAttributes(Data.class.getDeclaredField("text"))));
-
- // should not skip fields in Map
- assertFalse(strategy.shouldSkipField(new FieldAttributes(MyMap.class.getDeclaredField("mapId"))));
- }
-
- @Test
- void testShouldSkipClass() {
- assertFalse(strategy.shouldSkipClass(null));
- assertFalse(strategy.shouldSkipClass(Object.class));
- }
-
- @Test
- void testIsManaged() {
- // these classes SHOULD be managed
- Class<?>[] managed = {Data.class, Intfc.class, com.google.gson.TypeAdapter.class};
-
- for (Class<?> clazz : managed) {
- assertTrue(JacksonExclusionStrategy.isManaged(clazz), clazz.getName());
- }
-
- // generic classes should NOT be managed
- Class<?>[] unmanaged = {
- Data[].class, Enum.class, boolean.class, byte.class, short.class, int.class,
- long.class, float.class, double.class, char.class, Boolean.class, Byte.class, Short.class,
- Integer.class, Long.class, Float.class, Double.class, Character.class, String.class,
- MyMap.class, MyList.class, MyJson.class, GenericArrayType.class};
-
- for (Class<?> clazz : unmanaged) {
- assertFalse(JacksonExclusionStrategy.isManaged(clazz), clazz.getName());
- }
- }
-
- /**
- * Used to verify that no fields are exposed.
- */
- @Getter
- @Setter
- @ToString
- public static class Data {
- private int id;
- public String text;
-
- void setId(int id) {
- this.id = id;
- }
-
- void setText(String text) {
- this.text = text;
- }
- }
-
- @Getter
- @ToString(callSuper = true)
- public static class Derived extends Data {
- protected String value;
-
- void setValue(String value) {
- this.value = value;
- }
- }
-
- /**
- * Used to verify that enums are not managed.
- */
- public enum Enum {
- UP, DOWN,
- }
-
- /**
- * Used to verify that interfaces <i>are</i> managed.
- */
- public interface Intfc {
- int getId();
- }
-
- /**
- * Used to verify that Maps are not managed.
- */
- @Getter
- public static class MyMap extends TreeMap<String, Data> {
- @Serial
- private static final long serialVersionUID = 1L;
-
- private int mapId;
-
- }
-
- /**
- * Used to verify that Collections are not managed.
- */
- public static class MyList extends LinkedList<Data> {
- @Serial
- private static final long serialVersionUID = 1L;
- }
-
- /**
- * Used to verify that JsonElements are not managed.
- */
- @SuppressWarnings("deprecation")
- public static class MyJson extends JsonElement {
- @Override
- public JsonElement deepCopy() {
- return null;
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.reflect.TypeToken;
-import java.util.ArrayList;
-import java.util.List;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
-import org.onap.policy.common.gson.annotation.GsonJsonProperty;
-
-class JacksonFieldAdapterFactoryTest {
-
- private static JacksonFieldAdapterFactory factory = new JacksonFieldAdapterFactory();
-
- private static Gson gson = new GsonBuilder().setExclusionStrategies(new JacksonExclusionStrategy())
- .registerTypeAdapterFactory(factory).create();
-
- @Test
- void testCreate() {
- // unhandled types
- assertNull(factory.create(gson, TypeToken.get(JsonElement.class)));
- assertNull(factory.create(gson, TypeToken.get(NothingToSerialize.class)));
-
- assertNotNull(factory.create(gson, TypeToken.get(Data.class)));
- assertNotNull(factory.create(gson, TypeToken.get(Derived.class)));
-
- Data data = new Data();
-
- // deserialize using fields that aren't in the Data object
- Data data2 = gson.fromJson("{\"abc\":100}", Data.class);
- assertEquals(data.toString(), data2.toString());
-
- // now work with valid fields
- data.id = 10;
- data.text = "hello";
-
- String result = gson.toJson(data);
- data2 = gson.fromJson(result, Data.class);
- assertEquals(data.toString(), data2.toString());
-
- // should also work with derived types
- Derived der = new Derived();
- der.setId(20);
- der.text = "world";
- der.unserialized = "abc";
-
- result = gson.toJson(der);
-
- // should not contain the unserialized field
- assertFalse(result.contains("abc"));
-
- Derived der2 = gson.fromJson(result, Derived.class);
- der.unserialized = null;
- assertEquals(der.toString(), der2.toString());
- }
-
- @Test
- void testCreate_Lists() {
- DataList lst = new DataList();
- lst.theList = new ArrayList<>();
- lst.theList.add(new Data(200, "text 20"));
- lst.theList.add(new Data(210, "text 21"));
-
- String result = gson.toJson(lst);
- assertEquals("{'theList':[{'my-id':200,'text':'text 20'},{'my-id':210,'text':'text 21'}]}".replace('\'', '"'),
- result);
-
- DataList lst2 = gson.fromJson(result, DataList.class);
- assertEquals(stripIdent(lst.toString()), stripIdent(lst2.toString()));
- assertEquals(Data.class, lst2.theList.get(0).getClass());
- }
-
- @Test
- void testCreate_OnlyOutProps() {
- InFieldIgnored data = new InFieldIgnored();
- data.value = "out only";
-
- // field should be serialized
- String result = gson.toJson(data);
- assertEquals("{'value':'out only'}".replace('\'', '"'), result);
-
- // field should NOT be deserialized
- data = gson.fromJson(result, InFieldIgnored.class);
- assertNull(data.value);
- }
-
- @Test
- void testCreate_OnlyInProps() {
- OutFieldIgnored data = new OutFieldIgnored();
- data.value = "in only";
-
- // field should NOT be serialized
- String result = gson.toJson(data);
- assertEquals("{}", result);
-
- // field should NOT be deserialized
- data = gson.fromJson("{'value':'in only'}".replace('\'', '"'), OutFieldIgnored.class);
- assertEquals("in only", data.value);
- }
-
- /**
- * Object identifiers may change with each execution, so this method is used to strip
- * the identifier from the text string so that the strings will still match across
- * different runs.
- *
- * @param text text from which to strip the identifier
- * @return the text, without the identifier
- */
- private String stripIdent(String text) {
- return text.replaceFirst("@\\w+", "@");
- }
-
- @ToString
- private static class Data {
- @GsonJsonProperty("my-id")
- private int id;
-
- public String text;
-
- public Data() {
- super();
- }
-
- public Data(int id, String text) {
- this.id = id;
- this.text = text;
- }
-
- void setId(int id) {
- this.id = id;
- }
- }
-
- @ToString(callSuper = true)
- private static class Derived extends Data {
- // not serialized
- private String unserialized;
- }
-
- private static class DataList {
- @GsonJsonProperty
- private List<Data> theList;
- }
-
- protected static class NothingToSerialize {
- // not serialized
- protected String unserialized;
- }
-
- /**
- * This has a field that should show up in the "output" list, but not in the "input"
- * list, because the method will override it.
- */
- private static class InFieldIgnored {
- @GsonJsonProperty("value")
- private String value;
-
- @GsonJsonIgnore
- public void setValue(String value) {
- this.value = value;
- }
- }
-
- /**
- * This has a field that should show up in the "input" list, but not in the "output"
- * list, because the method will override it.
- */
- private static class OutFieldIgnored {
- @GsonJsonProperty("value")
- private String value;
-
- @GsonJsonIgnore
- public String getValue() {
- return value;
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonObject;
-import jakarta.ws.rs.core.MediaType;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.TreeMap;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
-import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
-
-class JacksonHandlerTest {
-
- @Test
- void test() throws Exception {
- JacksonHandler hdlr = new JacksonHandler();
-
- assertTrue(hdlr.isReadable(null, null, null, MediaType.APPLICATION_JSON_TYPE));
- assertFalse(hdlr.isReadable(null, null, null, MediaType.TEXT_PLAIN_TYPE));
-
- JsonObject expected = new JsonObject();
- expected.addProperty("myId", 100);
- expected.addProperty("value", "a value");
- expected.addProperty("abc", "def");
- expected.addProperty("hello", "world");
-
- Data data = new Data();
- data.id = 10;
- data.value = "a value";
- data.props = new HashMap<>();
- data.props.put("abc", "def");
- data.props.put("hello", "world");
-
- /*
- * Ensure everything serializes as expected.
- */
- ByteArrayOutputStream outstr = new ByteArrayOutputStream();
- hdlr.writeTo(data, Data.class, Data.class, null, null, null, outstr);
-
- StringReader rdr = new StringReader(outstr.toString("UTF-8"));
- JsonObject json = new Gson().fromJson(rdr, JsonObject.class);
-
- assertEquals(expected, json);
-
- /*
- * Ensure everything deserializes as expected.
- */
- Data data2 = (Data) hdlr.readFrom(Object.class, Data.class, null, null, null,
- new ByteArrayInputStream(outstr.toByteArray()));
-
- // id is not serialized, so we must copy it manually before comparing
- data2.id = data.id;
-
- assertEquals(data.toString(), data2.toString());
- }
-
- @Test
- void testMapDouble() throws Exception {
- MyMap map = new MyMap();
- map.props = new HashMap<>();
- map.props.put("plainString", "def");
- map.props.put("negInt", -10);
- map.props.put("doubleVal", 12.5);
- map.props.put("posLong", 100000000000L);
-
- JacksonHandler hdlr = new JacksonHandler();
- ByteArrayOutputStream outstr = new ByteArrayOutputStream();
- hdlr.writeTo(map, map.getClass(), map.getClass(), null, null, null, outstr);
-
- Object obj2 = hdlr.readFrom(Object.class, map.getClass(), null, null, null,
- new ByteArrayInputStream(outstr.toByteArray()));
- assertEquals(map.toString(), obj2.toString());
-
- map = (MyMap) obj2;
-
- assertEquals(-10, map.props.get("negInt"));
- assertEquals(100000000000L, map.props.get("posLong"));
- assertEquals(12.5, map.props.get("doubleVal"));
- }
-
- /**
- * This class includes all policy-specific gson annotations.
- */
- @ToString
- public static class Data {
- protected int id;
-
- protected String value;
-
- protected Map<String, String> props;
-
- public int getMyId() {
- return 100;
- }
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-
- @GsonJsonAnyGetter
- public Map<String, String> getProps() {
- return props;
- }
-
- /**
- * Sets a property.
- *
- * @param name property name
- * @param value new value
- */
- @GsonJsonAnySetter
- public void setProperty(String name, String value) {
- if (props == null) {
- props = new TreeMap<>();
- }
-
- props.put(name, value);
- }
- }
-
- private static class MyMap {
- private Map<String, Object> props;
-
- @Override
- public String toString() {
- return props.toString();
- }
-
- @SuppressWarnings("unused")
- public Map<String, Object> getProps() {
- return props;
- }
-
- @SuppressWarnings("unused")
- public void setProps(Map<String, Object> props) {
- this.props = props;
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.reflect.TypeToken;
-import java.util.Map;
-import java.util.TreeMap;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
-import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
-import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
-import org.onap.policy.common.gson.annotation.GsonJsonProperty;
-
-class JacksonMethodAdapterFactoryTest {
-
- private static JacksonMethodAdapterFactory factory = new JacksonMethodAdapterFactory();
-
- private static Gson gson = new GsonBuilder().setExclusionStrategies(new JacksonExclusionStrategy())
- .registerTypeAdapterFactory(factory).create();
-
- @Test
- void testCreate() {
- // unhandled types
- assertNull(factory.create(gson, TypeToken.get(JsonElement.class)));
- assertNull(factory.create(gson, TypeToken.get(NothingToSerialize.class)));
-
- assertNotNull(factory.create(gson, TypeToken.get(Data.class)));
- assertNotNull(factory.create(gson, TypeToken.get(Derived.class)));
- assertNotNull(factory.create(gson, TypeToken.get(OnlyGetters.class)));
- assertNotNull(factory.create(gson, TypeToken.get(OnlySetters.class)));
- assertNotNull(factory.create(gson, TypeToken.get(OnlyAnyGetter.class)));
- assertNotNull(factory.create(gson, TypeToken.get(OnlyAnySetter.class)));
-
- // unhandled type
-
- Data data = new Data();
- data.id = 10;
- data.text = "some text";
-
- String result = gson.toJson(data);
- Data data2 = gson.fromJson(result, Data.class);
- assertEquals(data.toString(), data2.toString());
-
- Derived der = new Derived();
- der.setId(20);
- der.setText("hello");
- der.text = "world";
- der.map = new TreeMap<>();
- der.map.put("mapA", "valA");
- der.map.put("mapB", "valB");
-
- result = gson.toJson(der);
-
- // should not contain the unserialized fields
- assertFalse(result.contains("hello"));
- assertFalse(result.contains("world"));
-
- // null out unserialized fields
- der.text = null;
-
- // null out overridden field
- der.setText(null);
-
- Derived der2 = gson.fromJson(result, Derived.class);
-
- assertEquals(der.toString(), der2.toString());
-
- // override of AnyGetter
- AnyGetterOverride dblget = new AnyGetterOverride();
- dblget.setMap(der.map);
- dblget.overMap = new TreeMap<>();
- dblget.overMap.put("getA", 100);
- dblget.overMap.put("getB", 110);
-
- String result2 = gson.toJson(dblget);
- dblget.overMap.keySet().forEach(key -> assertTrue(result2.contains(key), "over contains " + key));
- der.map.keySet().forEach(key -> assertFalse(result2.contains(key), "sub contains " + key));
-
- // override of AnySetter
- Map<String, Integer> map = new TreeMap<>();
- map.put("setA", 200);
- map.put("setB", 210);
- AnySetterOverride dblset = gson.fromJson(gson.toJson(map), AnySetterOverride.class);
- assertEquals(map.toString(), dblset.overMap.toString());
- assertNull(dblset.getTheMap());
-
- // non-static nested class - can serialize, but not de-serialize
- Container cont = new Container(500, "bye bye");
- result = gson.toJson(cont);
- assertEquals("{'id':500,'nested':{'value':'bye bye'}}".replace('\'', '"'), result);
- }
-
- @ToString
- protected static class Data {
- private int id;
- private String text;
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- // not public, but property provided
- @GsonJsonProperty("text")
- protected String getText() {
- return text;
- }
-
- public void setText(String text) {
- this.text = text;
- }
-
- public void unused(String text) {
- // do nothing
- }
- }
-
- @ToString(callSuper = true)
- protected static class Derived extends Data {
-
- // overrides private field from Data
- public String text;
-
- private Map<String, String> map;
-
- @GsonJsonAnyGetter
- public Map<String, String> getTheMap() {
- return map;
- }
-
- @GsonJsonIgnore
- public void setMap(Map<String, String> map) {
- this.map = map;
- }
-
- @GsonJsonAnySetter
- public void setMapValue(String key, String value) {
- if (map == null) {
- map = new TreeMap<>();
- }
-
- map.put(key, value);
- }
- }
-
- /**
- * Has {@link GsonJsonAnyGetter} method that overrides the super class' method.
- */
- private static class AnyGetterOverride extends Derived {
- private Map<String, Integer> overMap;
-
- @GsonJsonAnyGetter
- private Map<String, Integer> getOverride() {
- return overMap;
- }
- }
-
- /**
- * Has {@link GsonJsonAnySetter} method that overrides the super class' method.
- */
- private static class AnySetterOverride extends Derived {
- private Map<String, Integer> overMap;
-
- @GsonJsonAnySetter
- private void setOverride(String key, int value) {
- if (overMap == null) {
- overMap = new TreeMap<>();
- }
-
- overMap.put(key, value);
- }
- }
-
- /**
- * Has nothing to serialize.
- */
- protected static class NothingToSerialize {
- // not serialized
- protected String unserialized;
- }
-
- /**
- * Only has getters.
- */
- protected static class OnlyGetters {
- public int getId() {
- return 1010;
- }
- }
-
- /**
- * Only has setters.
- */
- protected static class OnlySetters {
- public void setId(int id) {
- // do nothing
- }
- }
-
- /**
- * Only has {@link GsonJsonAnyGetter}.
- */
- private static class OnlyAnyGetter {
- @GsonJsonAnyGetter
- public Map<String, Integer> getOverride() {
- return null;
- }
- }
-
- /**
- * Only has {@link GsonJsonAnySetter}.
- */
- private static class OnlyAnySetter {
- @GsonJsonAnySetter
- public void setOverride(String key, int value) {
- // do nothing
- }
- }
-
- /**
- * Used to test serialization of non-static nested classes.
- */
- @ToString
- protected static class Container {
- private int id;
- private Nested nested;
-
- public Container() {
- super();
- }
-
- public Container(int id, String value) {
- this.id = id;
- this.nested = new Nested(value);
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public Nested getNested() {
- return nested;
- }
-
-
- @ToString
- protected class Nested {
- private String value;
-
- public Nested(String val) {
- value = val;
- }
-
- public String getValue() {
- return value;
- }
- }
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import java.time.LocalDateTime;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class LocalDateTimeTypeAdapterTest {
- private static Gson gson =
- new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter()).create();
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.date = LocalDateTime.of(2020, 2, 3, 4, 5, 6, 789000000);
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).doesNotContain("year").contains("\"2020-02-03T04:05:06.789\"");
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // try when the date-time string is invalid
- String json2 = json.replace("2020", "invalid-date");
- assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
- .hasMessageContaining("invalid date");
-
- // null output
- data.date = null;
- json = gson.toJson(data);
- data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // null input
- data2 = gson.fromJson("{\"date\":null}", InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
- }
-
-
- @ToString
- private static class InterestingFields {
- private LocalDateTime date;
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import java.time.LocalDate;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class LocalDateTypeAdapterTest {
- private static Gson gson =
- new GsonBuilder().registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()).create();
- private static final String TEST_DATE = "2020-01-01";
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.date = LocalDate.parse(TEST_DATE);
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).doesNotContain("year").contains(TEST_DATE);
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // try when the date-time string is invalid
- String json2 = json.replace("2020", "invalid-date");
- assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
- .hasMessageContaining("invalid date");
-
- // null output
- data.date = null;
- json = gson.toJson(data);
- data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // null input
- data2 = gson.fromJson("{\"date\":null}", InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
- }
-
- @ToString
- private static class InterestingFields {
- private LocalDate date;
- }
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import org.junit.jupiter.api.Test;
-
-class MapDoubleAdapterFactoryTest {
- private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(new MapDoubleAdapterFactory()).create();
-
- @Test
- @SuppressWarnings("unchecked")
- void testMap() {
- MyMap map = new MyMap();
- map.data = new HashMap<>();
- map.data.put("plainString", "def");
- map.data.put("posInt", 10);
- map.data.put("negInt", -10);
- map.data.put("doubleVal", 12.5);
- map.data.put("posLong", 100000000000L);
- map.data.put("negLong", -100000000000L);
-
- Map<String, Object> nested = new LinkedHashMap<>();
- map.data.put("nestedMap", nested);
- nested.put("nestedString", "world");
- nested.put("nestedInt", 50);
-
- String json = gson.toJson(map);
-
- map.data.clear();
- map = gson.fromJson(json, MyMap.class);
-
- assertEquals(json, gson.toJson(map));
-
- assertEquals(10, map.data.get("posInt"));
- assertEquals(-10, map.data.get("negInt"));
- assertEquals(100000000000L, map.data.get("posLong"));
- assertEquals(-100000000000L, map.data.get("negLong"));
- assertEquals(12.5, map.data.get("doubleVal"));
- assertEquals(nested, map.data.get("nestedMap"));
-
- nested = (Map<String, Object>) map.data.get("nestedMap");
- assertEquals(50, nested.get("nestedInt"));
- }
-
- @Test
- void testList() {
- MyList list = new MyList();
- list.data = new ArrayList<>();
- list.data.add("ghi");
- list.data.add(100);
-
- List<Object> nested = new ArrayList<>();
- list.data.add(nested);
- nested.add("world2");
- nested.add(500);
-
- String json = gson.toJson(list);
-
- list.data.clear();
- list = gson.fromJson(json, MyList.class);
-
- assertEquals(json, gson.toJson(list));
-
- assertEquals("[ghi, 100, [world2, 500]]", list.data.toString());
- }
-
- @Test
- void test_ValueIsNotObject() {
- MyDoubleMap map = new MyDoubleMap();
- map.data = new LinkedHashMap<>();
- map.data.put("plainDouble", 13.5);
- map.data.put("doubleAsInt", 100.0);
-
- String json = gson.toJson(map);
-
- map.data.clear();
- map = gson.fromJson(json, MyDoubleMap.class);
-
- // everything should still be Double - check by simply accessing
- assertNotNull(map.data.get("plainDouble"));
- assertNotNull(map.data.get("doubleAsInt"));
- }
-
- @Test
- void test_KeyIsNotString() {
- MyObjectMap map = new MyObjectMap();
-
- map.data = new LinkedHashMap<>();
- map.data.put("plainDouble2", 14.5);
- map.data.put("doubleAsInt2", 200.0);
-
- String json = gson.toJson(map);
-
- map.data.clear();
- map = gson.fromJson(json, MyObjectMap.class);
-
- // everything should still be Double
- assertEquals(14.5, map.data.get("plainDouble2"));
- assertEquals(200.0, map.data.get("doubleAsInt2"));
- }
-
- @Test
- void test_ListValueIsNotObject() {
- MyDoubleList list = new MyDoubleList();
- list.data = new ArrayList<>();
- list.data.add(13.5);
- list.data.add(100.0);
-
- String json = gson.toJson(list);
-
- list.data.clear();
- list = gson.fromJson(json, MyDoubleList.class);
-
- // everything should still be Double - check by simply accessing
- assertEquals("[13.5, 100.0]", list.data.toString());
- }
-
- private static class MyMap {
- private Map<String, Object> data;
- }
-
- private static class MyDoubleMap {
- private Map<String, Double> data;
- }
-
- private static class MyObjectMap {
- private Map<Object, Object> data;
- }
-
- private static class MyList {
- private List<Object> data;
- }
-
- private static class MyDoubleList {
- private List<Double> data;
- }
-
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import java.time.OffsetDateTime;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class OffsetDateTimeAdapterTest {
- private static Gson gson =
- new GsonBuilder().registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter()).create();
- private static final String TEST_DATE = "2020-01-01T12:00:00.999+05:00";
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.date = OffsetDateTime.parse(TEST_DATE);
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).doesNotContain("year").contains(TEST_DATE);
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // try when the date-time string is invalid
- String json2 = json.replace("2020", "invalid-date");
- assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
- .hasMessageContaining("invalid date");
-
- // null output
- data.date = null;
- json = gson.toJson(data);
- data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // null input
- data2 = gson.fromJson("{\"date\":null}", InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
- }
-
- @ToString
- private static class InterestingFields {
- private OffsetDateTime date;
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import java.time.OffsetTime;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class OffsetTimeTypeAdapterTest {
- private static Gson gson =
- new GsonBuilder().registerTypeAdapter(OffsetTime.class, new OffsetTimeTypeAdapter()).create();
- private static final String TEST_TIME = "12:00:00.999+05:00";
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.time = OffsetTime.parse(TEST_TIME);
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).doesNotContain("foo").contains(TEST_TIME);
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // try when the date-time string is invalid
- String json2 = json.replace("12", "invalid-time");
- assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
- .hasMessageContaining("invalid time");
-
- // null output
- data.time = null;
- json = gson.toJson(data);
- data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // null input
- data2 = gson.fromJson("{\"time\":null}", InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
- }
-
- @ToString
- private static class InterestingFields {
- private OffsetTime time;
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class StringTypeAdapterTest {
- private static Gson gson = new GsonBuilder().registerTypeAdapter(MyData.class, new MyAdapter()).create();
- private static final int TEST_NUM1 = 10;
- private static final int TEST_NUM3 = 30;
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.data1 = new MyData(TEST_NUM1);
- data.data2 = null;
- data.data3 = new MyData(TEST_NUM3);
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).contains("10", "30");
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // try when the string is invalid
- String json2 = json.replace("30", "invalid-value");
- assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
- .hasMessageContaining("invalid data");
-
- // null output
- data = new InterestingFields();
- json = gson.toJson(data);
- data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // null input
- data2 = gson.fromJson("{\"data1\":null, \"data1\":null, \"data1\":null}", InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // empty input
- data2 = gson.fromJson("{}", InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
- }
-
- @Getter
- @ToString
- @AllArgsConstructor
- private static class MyData {
- private int num;
- }
-
- @ToString
- private static class InterestingFields {
- private MyData data1;
- private MyData data2;
- private MyData data3;
- }
-
- private static class MyAdapter extends StringTypeAdapter<MyData> {
- public MyAdapter() {
- super("data", string -> new MyData(Integer.parseInt(string)), data -> String.valueOf(data.num));
- }
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import java.time.ZoneOffset;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class ZoneOffsetTypeAdapterTest {
- private static final Gson gson =
- new GsonBuilder().registerTypeAdapter(ZoneOffset.class, new ZoneOffsetTypeAdapter()).create();
- private static final String TEST_ZONE = "+05:00";
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.zone = ZoneOffset.of(TEST_ZONE);
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).doesNotContain("foo").contains(TEST_ZONE);
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // try when the date-time string is invalid
- String json2 = json.replace("05", "invalid-zone");
- assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
- .hasMessageContaining("invalid zone");
-
- // null output
- data.zone = null;
- json = gson.toJson(data);
- data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // null input
- data2 = gson.fromJson("{\"zone\":null}", InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
- }
-
- @ToString
- private static class InterestingFields {
- private ZoneOffset zone;
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonParseException;
-import java.time.ZoneId;
-import java.time.ZonedDateTime;
-import lombok.ToString;
-import org.junit.jupiter.api.Test;
-
-class ZonedDateTimeTypeAdapterTest {
- private static Gson gson =
- new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeTypeAdapter()).create();
-
- @Test
- void test() {
- InterestingFields data = new InterestingFields();
- data.date = ZonedDateTime.of(2020, 2, 3, 4, 5, 6, 789000000, ZoneId.of("US/Eastern"));
-
- String json = gson.toJson(data);
-
- // instant should be encoded as a number, without quotes
- assertThat(json).doesNotContain("year").contains("\"2020-02-03T04:05:06.789-05:00[US/Eastern]\"");
-
- InterestingFields data2 = gson.fromJson(json, InterestingFields.class);
- assertEquals(data.toString(), data2.toString());
-
- // try when the date-time string is invalid
- String json2 = json.replace("2020", "invalid-date");
- assertThatThrownBy(() -> gson.fromJson(json2, InterestingFields.class)).isInstanceOf(JsonParseException.class)
- .hasMessageContaining("invalid date");
- }
-
-
- @ToString
- private static class InterestingFields {
- private ZonedDateTime date;
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023, 2024 Nordix Foundation.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonPrimitive;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.List;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.annotation.GsonJsonProperty;
-import org.onap.policy.common.gson.internal.Adapter.Factory;
-import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-import org.onap.policy.common.gson.internal.DataAdapterFactory.DerivedData;
-import org.springframework.test.util.ReflectionTestUtils;
-
-class AdapterTest {
- private static final String GET_INVALID_NAME = "get$InvalidName";
- private static final String SET_INVALID_NAME = "set$InvalidName";
- private static final String EMPTY_ALIAS = "emptyAlias";
- private static final String GET_VALUE = ".getValue";
- private static final String GET_VALUE_NAME = "getValue";
- private static final String SET_VALUE_NAME = "setValue";
- private static final String VALUE_NAME = "value";
- private static final String MY_NAME = AdapterTest.class.getName();
- private static final String FACTORY_FIELD = "factory";
-
- private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
-
- private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
-
- private static Factory saveFactory;
-
- /*
- * The remaining fields are just used within the tests.
- */
-
- private String value;
-
- // empty alias - should use field name
- @GsonJsonProperty("")
- protected String emptyAlias;
-
- @GsonJsonProperty("name-with-alias")
- protected String nameWithAlias;
-
- protected String unaliased;
-
- private List<Data> listField;
-
- private Data dataField;
-
- @BeforeAll
- static void setUpBeforeClass() {
- saveFactory = (Factory) ReflectionTestUtils.getField(Adapter.class, FACTORY_FIELD);
- }
-
- @AfterEach
- void tearDown() {
- ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, saveFactory);
- }
-
- @Test
- void testIsManagedField() {
- assertTrue(Adapter.isManaged(field(VALUE_NAME)));
-
- // return an invalid field name
- Factory factory = mock(Factory.class);
- when(factory.getName(any(Field.class))).thenReturn("$invalidFieldName");
- ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
- assertFalse(Adapter.isManaged(field(VALUE_NAME)));
- }
-
- @Test
- void testIsManagedMethod() {
- assertTrue(Adapter.isManaged(mget(GET_VALUE_NAME)));
-
- // return an invalid method name
- Factory factory = mock(Factory.class);
- ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
-
- when(factory.getName(any(Method.class))).thenReturn(GET_INVALID_NAME);
- assertFalse(Adapter.isManaged(mget(GET_VALUE_NAME)));
-
- when(factory.getName(any(Method.class))).thenReturn(SET_INVALID_NAME);
- assertFalse(Adapter.isManaged(mset(SET_VALUE_NAME)));
- }
-
- @Test
- void testAdapterField_Converter() {
- Adapter adapter = new Adapter(gson, field("dataField"));
-
- // first, write something of type Data
- dataAdapter.reset();
- dataField = new Data(300);
- JsonElement tree = adapter.toJsonTree(dataField);
- assertEquals("{'id':300}".replace('\'', '"'), tree.toString());
-
- // now try a subclass
- dataAdapter.reset();
- dataField = new DerivedData(300, "three");
- tree = adapter.toJsonTree(dataField);
- assertEquals("{'id':300,'text':'three'}".replace('\'', '"'), tree.toString());
- }
-
- @Test
- @SuppressWarnings("unchecked")
- void testAdapterField_Converter_List() {
- listField = DataAdapterFactory.makeList();
-
- Adapter adapter = new Adapter(gson, field("listField"));
-
- dataAdapter.reset();
- JsonElement tree = adapter.toJsonTree(listField);
- assertTrue(dataAdapter.isDataWritten());
- assertEquals(DataAdapterFactory.ENCODED_LIST, tree.toString());
-
- // encode it twice so it uses the cached converter
- dataAdapter.reset();
- tree = adapter.toJsonTree(listField);
- assertTrue(dataAdapter.isDataWritten());
- assertEquals(DataAdapterFactory.ENCODED_LIST, tree.toString());
-
- dataAdapter.reset();
- List<Data> lst2 = (List<Data>) adapter.fromJsonTree(tree);
- assertTrue(dataAdapter.isDataRead());
-
- assertEquals(listField.toString(), lst2.toString());
-
- // decode it twice so it uses the cached converter
- dataAdapter.reset();
- lst2 = (List<Data>) adapter.fromJsonTree(tree);
- assertTrue(dataAdapter.isDataRead());
-
- assertEquals(listField.toString(), lst2.toString());
- }
-
- @Test
- void testAdapterMethod_Converter() throws Exception {
- listField = DataAdapterFactory.makeList();
-
- Method getter = mget("getMyList");
-
- Adapter aget = new Adapter(gson, getter, getter.getReturnType());
-
- dataAdapter.reset();
- JsonElement tree = aget.toJsonTree(listField);
- assertTrue(dataAdapter.isDataWritten());
- assertEquals(DataAdapterFactory.ENCODED_LIST, tree.toString());
-
- Method setter = AdapterTest.class.getDeclaredMethod("setMyList", List.class);
- Adapter aset = new Adapter(gson, setter, setter.getGenericParameterTypes()[0]);
-
- dataAdapter.reset();
- @SuppressWarnings("unchecked")
- List<Data> lst2 = (List<Data>) aset.fromJsonTree(tree);
- assertTrue(dataAdapter.isDataRead());
-
- assertEquals(listField.toString(), lst2.toString());
- }
-
- @Test
- void testGetPropName_testGetFullName_testMakeError() {
- // test field
- Adapter adapter = new Adapter(gson, field(VALUE_NAME));
-
- assertEquals(VALUE_NAME, adapter.getPropName());
- assertEquals(MY_NAME + ".value", adapter.getFullName());
-
-
- // test getter
- adapter = new Adapter(gson, mget(GET_VALUE_NAME), String.class);
-
- assertEquals(VALUE_NAME, adapter.getPropName());
- assertEquals(MY_NAME + GET_VALUE, adapter.getFullName());
-
- assertEquals("hello: " + MY_NAME + GET_VALUE, adapter.makeError("hello: "));
-
-
- // test setter
- adapter = new Adapter(gson, mset(SET_VALUE_NAME), String.class);
-
- assertEquals(VALUE_NAME, adapter.getPropName());
- assertEquals(MY_NAME + ".setValue", adapter.getFullName());
- }
-
- @Test
- void testToJsonTree() {
- Adapter adapter = new Adapter(gson, field(VALUE_NAME));
-
- JsonElement tree = adapter.toJsonTree("hello");
- assertTrue(tree.isJsonPrimitive());
- assertEquals("hello", tree.getAsString());
- }
-
- @Test
- void testFromJsonTree() {
- Adapter adapter = new Adapter(gson, field(VALUE_NAME));
-
- assertEquals("world", adapter.fromJsonTree(new JsonPrimitive("world")));
- }
-
- @Test
- void testDetmPropName() {
- assertEquals(EMPTY_ALIAS, Adapter.detmPropName(field(EMPTY_ALIAS)));
- assertEquals("name-with-alias", Adapter.detmPropName(field("nameWithAlias")));
- assertEquals("unaliased", Adapter.detmPropName(field("unaliased")));
-
- // return an invalid field name
- Factory factory = mock(Factory.class);
- when(factory.getName(any(Field.class))).thenReturn("$invalidFieldName");
- ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
- assertEquals(null, Adapter.detmPropName(field(VALUE_NAME)));
- }
-
- @Test
- void testDetmGetterPropName() {
- assertEquals(EMPTY_ALIAS, Adapter.detmGetterPropName(mget("getEmptyAlias")));
- assertEquals("get-with-alias", Adapter.detmGetterPropName(mget("getWithAlias")));
- assertEquals("plain", Adapter.detmGetterPropName(mget("getPlain")));
- assertEquals("primBool", Adapter.detmGetterPropName(mget("isPrimBool")));
- assertEquals("boxedBool", Adapter.detmGetterPropName(mget("isBoxedBool")));
- assertEquals(null, Adapter.detmGetterPropName(mget("isString")));
- assertEquals(null, Adapter.detmGetterPropName(mget("noGet")));
- assertEquals(null, Adapter.detmGetterPropName(mget("get")));
-
- // return an invalid method name
- Factory factory = mock(Factory.class);
- ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
-
- when(factory.getName(any(Method.class))).thenReturn(GET_INVALID_NAME);
- assertEquals(null, Adapter.detmGetterPropName(mget(GET_VALUE_NAME)));
- }
-
- @Test
- void testDetmSetterPropName() {
- assertEquals(EMPTY_ALIAS, Adapter.detmSetterPropName(mset("setEmptyAlias")));
- assertEquals("set-with-alias", Adapter.detmSetterPropName(mset("setWithAlias")));
- assertEquals("plain", Adapter.detmSetterPropName(mset("setPlain")));
- assertEquals(null, Adapter.detmSetterPropName(mset("noSet")));
- assertEquals(null, Adapter.detmSetterPropName(mset("set")));
-
- // return an invalid method name
- Factory factory = mock(Factory.class);
- ReflectionTestUtils.setField(Adapter.class, FACTORY_FIELD, factory);
-
- when(factory.getName(any(Method.class))).thenReturn(SET_INVALID_NAME);
- assertEquals(null, Adapter.detmSetterPropName(mset(SET_VALUE_NAME)));
- }
-
- @Test
- void testGetQualifiedNameField() throws Exception {
- assertEquals(MY_NAME + ".value", Adapter.getQualifiedName(AdapterTest.class.getDeclaredField(VALUE_NAME)));
- }
-
- @Test
- void testGetQualifiedNameMethod() {
- assertEquals(MY_NAME + GET_VALUE, Adapter.getQualifiedName(mget(GET_VALUE_NAME)));
- }
-
- /**
- * Gets a field from this class, by name.
- *
- * @param name name of the field to get
- * @return the field
- */
- private Field field(String name) {
- try {
- return AdapterTest.class.getDeclaredField(name);
-
- } catch (SecurityException | NoSuchFieldException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Gets a "getter" method from this class, by name.
- *
- * @param name name of the method to get
- * @return the method
- */
- private Method mget(String name) {
- try {
- return AdapterTest.class.getDeclaredMethod(name);
-
- } catch (NoSuchMethodException | SecurityException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Gets a "setter" method from this class, by name.
- *
- * @param name name of the method to get
- * @return the method
- */
- private Method mset(String name) {
- try {
- return AdapterTest.class.getDeclaredMethod(name, String.class);
-
- } catch (NoSuchMethodException | SecurityException e) {
- throw new RuntimeException(e);
- }
- }
-
- /*
- * The remaining methods are just used within the tests.
- */
-
- protected String getValue() {
- return value;
- }
-
- // empty alias - should use method name
- @GsonJsonProperty("")
- protected String getEmptyAlias() {
- return "";
- }
-
- @GsonJsonProperty("get-with-alias")
- protected String getWithAlias() {
- return "";
- }
-
- // no alias, begins with "get"
- protected String getPlain() {
- return "";
- }
-
- // begins with "is", returns primitive boolean
- protected boolean isPrimBool() {
- return true;
- }
-
- // begins with "is", returns boxed Boolean
- protected Boolean isBoxedBool() {
- return true;
- }
-
- // begins with "is", but doesn't return a boolean
- protected String isString() {
- return "";
- }
-
- // doesn't begin with "get"
- protected String noGet() {
- return "";
- }
-
- // nothing after "get"
- protected String get() {
- return "";
- }
-
-
- protected void setValue(String text) {
- // do nothing
- }
-
- // empty alias - should use method name
- @GsonJsonProperty("")
- protected void setEmptyAlias(String text) {
- // do nothing
- }
-
- @GsonJsonProperty("set-with-alias")
- protected void setWithAlias(String text) {
- // do nothing
- }
-
- // no alias, begins with "set"
- protected void setPlain(String text) {
- // do nothing
- }
-
- // doesn't begin with "set"
- protected void noSet(String text) {
- // do nothing
- }
-
- // nothing after "get"
- protected void set(String text) {
- // do nothing
- }
-
- // returns a list
- protected List<Data> getMyList() {
- return listField;
- }
-
- // accepts a list
- protected void setMyList(List<Data> newList) {
- listField = newList;
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-
-class AnyGetterSerializerTest {
-
- private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
-
- private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
-
- private Set<String> set;
- private AnyGetterSerializer ser;
-
- /**
- * Set up.
- *
- * @throws Exception if an error occurs
- */
- @BeforeEach
- void setUp() throws Exception {
- set = new HashSet<>(Arrays.asList("id", "value"));
- ser = new AnyGetterSerializer(gson, set, MapData.class.getDeclaredMethod("getTheMap"));
- }
-
- @Test
- void testAddToTree_testCopyLiftedItems() {
- JsonObject tree = new JsonObject();
- tree.addProperty("hello", "world");
-
- MapData data = new MapData();
-
- data.map = DataAdapterFactory.makeMap();
-
- // this should not be copied because it is in the "set"
- data.map.put("value", Arrays.asList(new Data(1000)));
-
- dataAdapter.reset();
- JsonObject tree2 = tree.deepCopy();
- ser.addToTree(data, tree2);
-
- assertTrue(dataAdapter.isDataWritten());
-
- DataAdapterFactory.addToObject(tree);
-
- assertEquals(tree.toString(), tree2.toString());
- }
-
- @Test
- void testAddToTree_NullMap() {
- JsonObject tree = new JsonObject();
- tree.addProperty("hello", "world");
-
- MapData data = new MapData();
-
- // leave "map" unset
-
- JsonObject tree2 = tree.deepCopy();
- ser.addToTree(data, tree2);
-
- assertEquals(tree.toString(), tree2.toString());
- }
-
- @Test
- void testAddToTree_NotAnObject() throws Exception {
- ser = new AnyGetterSerializer(gson, set, NotAnObject.class.getDeclaredMethod("getNonMap"));
-
- JsonObject tree = new JsonObject();
-
- NotAnObject data = new NotAnObject();
- data.text = "bye bye";
-
- assertThatThrownBy(() -> ser.addToTree(data, tree)).isInstanceOf(JsonParseException.class)
- .hasMessage(AnyGetterSerializer.NOT_AN_OBJECT_ERR + NotAnObject.class.getName() + ".getNonMap");
- }
-
- public static class MapData {
- protected int id;
- protected String value;
- protected Map<String, List<Data>> map;
-
- protected Map<String, List<Data>> getTheMap() {
- return map;
- }
- }
-
- /**
- * The "lifted" property is not a JsonObject so it should throw an exception.
- */
- public static class NotAnObject {
- protected String text;
-
- public String getNonMap() {
- return text;
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonObject;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-
-class AnySetterDeserializerTest {
-
- private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
-
- private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
-
- private Set<String> set;
- private AnySetterDeserializer deser;
-
- /**
- * Set up.
- *
- * @throws Exception if an error occurs
- */
- @BeforeEach
- void setUp() throws Exception {
- set = new HashSet<>(Arrays.asList("id", "value"));
- deser = new AnySetterDeserializer(gson, set,
- MapData.class.getDeclaredMethod("setItem", String.class, List.class));
- }
-
- @Test
- void testAnySetterDeserializer() {
- JsonObject json = new JsonObject();
-
- // these should not be copied
- json.addProperty("id", 10);
- json.addProperty("value", "the-value");
-
- // these should be copied
- DataAdapterFactory.addToObject(json);
-
- MapData data = new MapData();
- data.map = new TreeMap<>();
-
- dataAdapter.reset();
- deser.getFromTree(json, data);
-
- assertTrue(dataAdapter.isDataRead());
- assertNotNull(data.map);
- assertEquals(DataAdapterFactory.makeMap().toString(), data.map.toString());
- }
-
- public static class MapData {
- protected Map<String, List<Data>> map;
-
- protected void setItem(String key, List<Data> value) {
- map.put(key, value);
- }
- }
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import com.google.gson.JsonParseException;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-import java.util.TreeSet;
-import lombok.Getter;
-import lombok.Setter;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter;
-import org.onap.policy.common.gson.annotation.GsonJsonAnySetter;
-import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
-import org.onap.policy.common.gson.annotation.GsonJsonProperty;
-
-class ClassWalkerTest {
-
- private static final String SET_OVERRIDE = ".setOverride";
- private static final String INVALID_FIELD_NAME = "invalidFieldName";
-
- private MyWalker walker;
-
- /**
- * Set up.
- */
- @BeforeEach
- void setUp() {
- walker = new MyWalker();
- }
-
- @Test
- void testExamineClassOfQ_testExamineField_testExamineInField_testExamineOutField() {
- walker.walkClassHierarchy(DerivedFromBottom.class);
-
- assertEquals("[InterfaceOne, InterfaceTwo, InterfaceOne, InterfaceThree, Bottom, DerivedFromBottom]",
- walker.classes.toString());
-
- List<String> inFields = walker.getInProps(Field.class).stream().map(Field::getName).sorted().toList();
- assertEquals("[exposedField, overriddenValue, transField]", inFields.toString());
-
- List<String> outFields = walker.getInProps(Field.class).stream().map(Field::getName).sorted().toList();
- assertEquals("[exposedField, overriddenValue, transField]", outFields.toString());
-
- // should work with interfaces without throwing an NPE
- walker.walkClassHierarchy(InterfaceOne.class);
- }
-
- @Test
- void testHasAnyGetter() {
- walker.walkClassHierarchy(Object.class);
- assertNull(walker.getAnyGetter());
- assertNull(walker.getAnySetter());
-
- walker.walkClassHierarchy(AnyGetterIgnored.class);
- assertNull(walker.getAnyGetter());
- assertNull(walker.getAnySetter());
-
- walker.walkClassHierarchy(AnyGetterOnly.class);
- assertNotNull(walker.getAnyGetter());
- assertNull(walker.getAnySetter());
- }
-
- @Test
- void testHasAnySetter() {
- walker.walkClassHierarchy(Object.class);
- assertNull(walker.getAnySetter());
- assertNull(walker.getAnyGetter());
-
- walker.walkClassHierarchy(AnySetterIgnored.class);
- assertNull(walker.getAnySetter());
- assertNull(walker.getAnyGetter());
-
- walker.walkClassHierarchy(AnySetterOnly.class);
- assertNotNull(walker.getAnySetter());
- assertNull(walker.getAnyGetter());
- }
-
- @Test
- void testExamineMethod() {
- walker.walkClassHierarchy(DerivedFromData.class);
-
- assertEquals("[Data, DerivedFromData]", walker.classes.toString());
-
- // ensure all methods were examined
- Collections.sort(walker.methods);
- List<String> lst = Arrays.asList("getId", "getValue", "getOnlyOut", "getStatic", "getText", "getTheMap",
- "getUnserialized", "getValue", "getWithParams", "setExtraParams", "setId", "setMap",
- "setMapValue", "setMissingParams", "setNonPublic", "setOnlyIn", "setText", "setUnserialized",
- "setValue", "setValue", "wrongGetPrefix", "wrongSetPrefix");
- Collections.sort(lst);
- assertEquals(lst.toString(), walker.methods.toString());
-
- assertNotNull(walker.getAnyGetter());
- assertEquals("getTheMap", walker.getAnyGetter().getName());
-
- List<String> getters = walker.getOutProps(Method.class).stream().map(Method::getName).sorted().toList();
- assertEquals("[getId, getOnlyOut, getValue]", getters.toString());
-
- assertNotNull(walker.getAnySetter());
- assertEquals("setMapValue", walker.getAnySetter().getName());
-
- List<String> setters = walker.getInProps(Method.class).stream().map(Method::getName).sorted().toList();
- assertEquals("[setId, setOnlyIn, setValue]", setters.toString());
-
- // getter with invalid parameter count
- assertThatThrownBy(() -> walker.walkClassHierarchy(AnyGetterMismatchParams.class))
- .isInstanceOf(JsonParseException.class).hasMessage(ClassWalker.ANY_GETTER_MISMATCH_ERR
- + AnyGetterMismatchParams.class.getName() + ".getTheMap");
-
- // setter with too few parameters
- assertThatThrownBy(() -> walker.walkClassHierarchy(AnySetterTooFewParams.class))
- .isInstanceOf(JsonParseException.class).hasMessage(ClassWalker.ANY_SETTER_MISMATCH_ERR
- + AnySetterTooFewParams.class.getName() + SET_OVERRIDE);
-
- // setter with too many parameters
- assertThatThrownBy(() -> walker.walkClassHierarchy(AnySetterTooManyParams.class))
- .isInstanceOf(JsonParseException.class).hasMessage(ClassWalker.ANY_SETTER_MISMATCH_ERR
- + AnySetterTooManyParams.class.getName() + SET_OVERRIDE);
-
- // setter with invalid parameter type
- assertThatThrownBy(() -> walker.walkClassHierarchy(AnySetterInvalidParam.class))
- .isInstanceOf(JsonParseException.class).hasMessage(ClassWalker.ANY_SETTER_TYPE_ERR
- + AnySetterInvalidParam.class.getName() + SET_OVERRIDE);
- }
-
- @Test
- void testExamineMethod_AnyGetter() {
- walker.walkClassHierarchy(AnyGetterOverride.class);
-
- assertNotNull(walker.getAnyGetter());
- assertEquals("getOverride", walker.getAnyGetter().getName());
- }
-
- @Test
- void testExamineMethod_AnySetter() {
- walker.walkClassHierarchy(AnySetterOverride.class);
-
- assertNotNull(walker.getAnySetter());
- assertEquals("setOverride", walker.getAnySetter().getName());
- }
-
- @Test
- void testGetInNotIgnored_testGetOutNotIgnored() {
- walker.walkClassHierarchy(DerivedFromData.class);
-
- assertEquals("[id, onlyIn, text, value]", new TreeSet<>(walker.getInNotIgnored()).toString());
- assertEquals("[id, onlyOut, text, value]", new TreeSet<>(walker.getOutNotIgnored()).toString());
- }
-
- /**
- * Walker subclass that records items that are examined.
- */
- private static class MyWalker extends ClassWalker {
- private final List<String> classes = new ArrayList<>();
- private final List<String> methods = new ArrayList<>();
-
- @Override
- protected void examine(Class<?> clazz) {
- classes.add(clazz.getSimpleName());
-
- super.examine(clazz);
- }
-
- @Override
- protected void examine(Method method) {
- if (Adapter.isManaged(method)) {
- methods.add(method.getName());
- }
-
- super.examine(method);
- }
-
- @Override
- protected String detmPropName(Field field) {
- if (INVALID_FIELD_NAME.equals(field.getName())) {
- return null;
- }
-
- return super.detmPropName(field);
- }
- }
-
- protected interface InterfaceOne {
- int id = 1000; // NOSONAR I think this is meant to be accessible as fields, not constants
- }
-
- protected interface InterfaceTwo {
- String text = "intfc2-text"; // NOSONAR I think this is meant to be accessible as fields, not constants
- }
-
- private interface InterfaceThree {
-
- }
-
- protected static class Bottom implements InterfaceOne, InterfaceThree {
- private int id;
- public String value;
-
- // this is not actually invalid, but will be treated as if it were
- public String invalidFieldName;
-
- @GsonJsonProperty("exposed")
- private String exposedField;
-
- @GsonJsonIgnore
- public int ignored;
-
- public transient int ignoredTransField;
-
- @GsonJsonProperty("trans")
- public transient int transField;
-
- @GsonJsonIgnore
- public int getId() {
- return id;
- }
-
- @GsonJsonIgnore
- public void setId(int id) {
- this.id = id;
- }
- }
-
- protected static class DerivedFromBottom extends Bottom implements InterfaceOne, InterfaceTwo {
- private String text;
- protected String anotherValue;
-
- @GsonJsonProperty("value")
- public String overriddenValue;
-
- @GsonJsonIgnore
- public String getText() {
- return text;
- }
-
- @GsonJsonIgnore
- public void setText(String text) {
- this.text = text;
- }
- }
-
- @Setter
- protected static class Data {
- @Getter
- private int id;
- // this will be ignored, because there's already a field by this name
- private String text;
-
- // not public, but property provided
- @GsonJsonProperty("text")
- protected String getText() {
- return text;
- }
-
- // should only show up in the output list
- public int getOnlyOut() {
- return 1100;
- }
-
- // will be overridden by subclass
- @GsonJsonProperty("super-value-getter")
- public String getValue() {
- return null;
- }
-
- // will be overridden by subclass
- @GsonJsonProperty("super-value-setter")
- public void setValue(String value) {
- // do nothing
- }
- }
-
- protected static class DerivedFromData extends Data {
- // not serialized
- private String unserialized;
-
- // overrides private field and public method from Data
- public String text;
-
- private Map<String, String> map;
-
- private String value;
-
- @Override
- public String getValue() {
- return value;
- }
-
- @Override
- public void setValue(String value) {
- this.value = value;
- }
-
- @GsonJsonAnyGetter
- public Map<String, String> getTheMap() {
- return map;
- }
-
- @GsonJsonIgnore
- public void setMap(Map<String, String> map) {
- this.map = map;
- }
-
- @GsonJsonAnySetter
- public void setMapValue(String key, String value) {
- if (map == null) {
- map = new TreeMap<>();
- }
-
- map.put(key, value);
- }
-
- @GsonJsonIgnore
- public String getUnserialized() {
- return unserialized;
- }
-
- @GsonJsonIgnore
- public void setUnserialized(String unserialized) {
- this.unserialized = unserialized;
- }
-
- // should only show up in the input list
- public void setOnlyIn(int value) {
- // do nothing
- }
-
- // has a param - shouldn't be serialized
- @SuppressWarnings("unused")
- public int getWithParams(String text) {
- return 1000;
- }
-
- // too few params - shouldn't be serialized
- public void setMissingParams() {
- // do nothing
- }
-
- // too many params - shouldn't be serialized
- public void setExtraParams(String text, String moreText) {
- // do nothing
- }
-
- // not public - shouldn't be serialized
- protected void setNonPublic(String text) {
- // do nothing
- }
-
- // doesn't start with "get"
- public String wrongGetPrefix() {
- return null;
- }
-
- // doesn't start with "set"
- public void wrongSetPrefix(String text) {
- // do nothing
- }
-
- // static
- public static String getStatic() {
- return null;
- }
- }
-
- /**
- * The "get" method has an incorrect argument count.
- */
- private static class AnyGetterMismatchParams {
- @GsonJsonAnyGetter
- public Map<String, String> getTheMap(String arg) {
- return new TreeMap<>();
- }
- }
-
- /**
- * Has {@link GsonJsonAnyGetter} method.
- */
- private static class AnyGetterOnly {
- @GsonJsonAnyGetter
- private Map<String, Integer> getOverride() {
- return null;
- }
- }
-
- /**
- * Has {@link GsonJsonAnyGetter} method, but it's ignored.
- */
- private static class AnyGetterIgnored {
- @GsonJsonAnyGetter
- @GsonJsonIgnore
- private Map<String, Integer> getOverride() {
- return null;
- }
- }
-
- /**
- * Has {@link GsonJsonAnySetter} method.
- */
- private static class AnySetterOnly {
- @GsonJsonAnySetter
- private void setOverride(String key, int value) {
- // do nothing
- }
- }
-
- /**
- * Has {@link GsonJsonAnySetter} method, but it's ignored.
- */
- private static class AnySetterIgnored {
- @GsonJsonAnySetter
- @GsonJsonIgnore
- private void setOverride(String key, int value) {
- // do nothing
- }
- }
-
- /**
- * Has {@link GsonJsonAnyGetter} method that overrides the super class' method.
- */
- private static class AnyGetterOverride extends DerivedFromData {
- private Map<String, Integer> overMap;
-
- @GsonJsonAnyGetter
- private Map<String, Integer> getOverride() {
- return overMap;
- }
- }
-
- /**
- * Has {@link GsonJsonAnySetter} method that overrides the super class' method.
- */
- private static class AnySetterOverride extends DerivedFromData {
- private Map<String, Integer> overMap;
-
- @GsonJsonAnySetter
- private void setOverride(String key, int value) {
- if (overMap == null) {
- overMap = new TreeMap<>();
- }
-
- overMap.put(key, value);
- }
- }
-
- /**
- * Has {@link GsonJsonAnySetter} method with too few parameters.
- */
- private static class AnySetterTooFewParams extends DerivedFromData {
- @GsonJsonAnySetter
- public void setOverride(String key) {
- // do nothing
- }
- }
-
- /**
- * Has {@link GsonJsonAnySetter} method with too few parameters.
- */
- private static class AnySetterTooManyParams extends DerivedFromData {
- @GsonJsonAnySetter
- public void setOverride(String key, int value, String anotherValue) {
- // do nothing
- }
- }
-
- /**
- * Has {@link GsonJsonAnySetter} method whose first argument type is incorrect.
- */
- private static class AnySetterInvalidParam extends DerivedFromData {
- @GsonJsonAnySetter
- public void setOverride(Integer key, String value) {
- // do nothing
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.TypeAdapter;
-import com.google.gson.TypeAdapterFactory;
-import com.google.gson.reflect.TypeToken;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-import lombok.ToString;
-
-/**
- * Factory used with test Data.
- */
-public class DataAdapterFactory implements TypeAdapterFactory {
-
- /**
- * Output of {@link #makeList()}, encoded as json.
- */
- public static final String ENCODED_LIST = "[{'id':100},{'id':101}]".replace('\'', '"');
-
- /**
- * Output of {@link #makeMap()}, encoded as json.
- */
- public static final String ENCODED_MAP = "'data-100':{'id':100},'data-101':{'id':101}".replace('\'', '"');
-
- /**
- * Object handled by this factory.
- */
- @ToString
- public static class Data {
- private int id;
-
- public Data() {
- super();
- }
-
- public Data(int id) {
- this.id = id;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
- }
-
- /**
- * Object derived from Data.
- */
- @ToString(callSuper = true)
- public static class DerivedData extends Data {
- private String text;
-
- public DerivedData() {
- super();
- }
-
- public DerivedData(int id, String text) {
- super(id);
- this.text = text;
- }
-
- public String getText() {
- return text;
- }
-
- public void setText(String text) {
- this.text = text;
- }
- }
-
- /**
- * Set to {@code true} when {@link #write(JsonWriter, Data)} has been invoked.
- */
- private boolean dataWritten = false;
-
- /**
- * Set to {@code true} when {@link #read(JsonReader)} has been invoked.
- */
- private boolean dataRead = false;
-
- /**
- * Clears the flags that indicate that "read" or "write" has been invoked.
- */
- public void reset() {
- dataWritten = true;
- dataRead = true;
- }
-
- public boolean isDataWritten() {
- return dataWritten;
- }
-
- public boolean isDataRead() {
- return dataRead;
- }
-
- /**
- * Makes a list of Data.
- *
- * @return a new list of Data
- */
- public static List<Data> makeList() {
- List<Data> listField = new ArrayList<>();
-
- listField.add(new Data(100));
- listField.add(new Data(101));
-
- return listField;
- }
-
- /**
- * Makes an array of Data.
- *
- * @return a new array of Data
- */
- public static JsonArray makeArray() {
- JsonArray arr = new JsonArray();
-
- for (Data data : makeList()) {
- JsonObject json = new JsonObject();
- json.addProperty("id", data.getId());
- arr.add(json);
- }
-
- return arr;
- }
-
- /**
- * Makes a map of Data.
- *
- * @return a new map of Data
- */
- public static Map<String, List<Data>> makeMap() {
- Map<String, List<Data>> map = new TreeMap<>();
-
- for (Data data : makeList()) {
- map.put("data-" + data.getId(), Arrays.asList(data));
- }
-
- return map;
- }
-
- /**
- * Adds Data objects to a tree, mirroring {@link #makeMap()}.
- *
- * @param tree tree into which objects are to be added
- */
- public static void addToObject(JsonObject tree) {
- for (JsonElement ent : makeArray()) {
- JsonObject obj = ent.getAsJsonObject();
- JsonArray arr = new JsonArray();
- arr.add(obj);
- tree.add("data-" + obj.get("id").getAsString(), arr);
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
- if (type.getRawType() == Data.class) {
- return (TypeAdapter<T>) new DataTypeAdapter(gson.getDelegateAdapter(this, TypeToken.get(Data.class)),
- gson.getAdapter(JsonElement.class));
- }
-
- if (type.getRawType() == DerivedData.class) {
- return (TypeAdapter<T>) new DerivedDataTypeAdapter(
- gson.getDelegateAdapter(this, TypeToken.get(DerivedData.class)),
- gson.getAdapter(JsonElement.class));
- }
-
- return null;
- }
-
- /**
- * Adapter for "Data".
- */
- private class DataTypeAdapter extends TypeAdapter<Data> {
- private TypeAdapter<Data> delegate;
- private TypeAdapter<JsonElement> elementAdapter;
-
- /**
- * Constructs the object.
- *
- * @param delegate delegate adapter
- * @param elementAdapter element adapter
- */
- public DataTypeAdapter(TypeAdapter<Data> delegate, TypeAdapter<JsonElement> elementAdapter) {
- this.delegate = delegate;
- this.elementAdapter = elementAdapter;
- }
-
- @Override
- public void write(JsonWriter out, Data data) throws IOException {
- dataWritten = true;
-
- JsonElement tree = delegate.toJsonTree(data);
-
- if (tree.isJsonObject()) {
- JsonObject jsonObj = tree.getAsJsonObject();
- jsonObj.addProperty("id", data.getId());
- }
-
- elementAdapter.write(out, tree);
- }
-
- @Override
- public Data read(JsonReader in) throws IOException {
- dataRead = true;
-
- JsonElement tree = elementAdapter.read(in);
- Data data = delegate.fromJsonTree(tree);
-
- if (tree.isJsonObject()) {
- JsonObject jsonObj = tree.getAsJsonObject();
- data.setId(jsonObj.get("id").getAsInt());
- }
-
- return data;
- }
- }
-
- /**
- * Adapter for "DerivedData".
- */
- private class DerivedDataTypeAdapter extends TypeAdapter<DerivedData> {
- private TypeAdapter<DerivedData> delegate;
- private TypeAdapter<JsonElement> elementAdapter;
-
- /**
- * Constructs the object.
- *
- * @param delegate delegate adapter
- * @param elementAdapter element adapter
- */
- public DerivedDataTypeAdapter(TypeAdapter<DerivedData> delegate, TypeAdapter<JsonElement> elementAdapter) {
- this.delegate = delegate;
- this.elementAdapter = elementAdapter;
- }
-
- @Override
- public void write(JsonWriter out, DerivedData data) throws IOException {
- dataWritten = true;
-
- JsonElement tree = delegate.toJsonTree(data);
-
- if (tree.isJsonObject()) {
- JsonObject jsonObj = tree.getAsJsonObject();
- jsonObj.addProperty("id", data.getId());
- jsonObj.addProperty("text", data.getText());
- }
-
- elementAdapter.write(out, tree);
- }
-
- @Override
- public DerivedData read(JsonReader in) throws IOException {
- dataRead = true;
-
- JsonElement tree = elementAdapter.read(in);
- DerivedData data = delegate.fromJsonTree(tree);
-
- if (tree.isJsonObject()) {
- JsonObject jsonObj = tree.getAsJsonObject();
- data.setId(jsonObj.get("id").getAsInt());
- data.setText(jsonObj.get("text").getAsString());
- }
-
- return data;
- }
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonNull;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import java.util.List;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-
-class FieldDeserializerTest {
- private static final String TEXT_FIELD_NAME = "text";
- private static final String LIST_FIELD_NAME = "listField";
- private static final String INITIAL_VALUE = "initial value";
- private static final String NEW_VALUE = "new value";
-
- private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
-
- private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
-
- private FieldDeserializer deser;
-
- private String text;
-
- private List<Data> listField;
-
- @Test
- void testGetFromTree() throws Exception {
- deser = new FieldDeserializer(gson, FieldDeserializerTest.class.getDeclaredField(TEXT_FIELD_NAME));
-
- JsonObject json = new JsonObject();
-
- // no value in tree - text remains unchanged
- text = INITIAL_VALUE;
- deser.getFromTree(json, this);
- assertEquals(INITIAL_VALUE, text);
-
- // null value in tree - text remains unchanged
- json.add(TEXT_FIELD_NAME, JsonNull.INSTANCE);
- deser.getFromTree(json, this);
- assertEquals(INITIAL_VALUE, text);
-
- // now assign a value - text should be changed now
- json.addProperty(TEXT_FIELD_NAME, NEW_VALUE);
-
- deser.getFromTree(json, this);
- assertEquals(NEW_VALUE, text);
-
- /*
- * check list field
- */
- deser = new FieldDeserializer(gson, FieldDeserializerTest.class.getDeclaredField(LIST_FIELD_NAME));
-
- json.add(LIST_FIELD_NAME, DataAdapterFactory.makeArray());
-
- dataAdapter.reset();
- listField = null;
- deser.getFromTree(json, this);
-
- assertTrue(dataAdapter.isDataRead());
- assertEquals(DataAdapterFactory.makeList().toString(), listField.toString());
- }
-
- @Test
- void testGetFromTree_SetEx() throws Exception {
- deser = new FieldDeserializer(gson, FieldDeserializerTest.class.getDeclaredField(TEXT_FIELD_NAME)) {
- @Override
- public Object fromJsonTree(JsonElement tree) {
- // return an int, which won't fit in a String - cause an exception
- return 10;
- }
- };
-
- JsonObject json = new JsonObject();
- json.addProperty(TEXT_FIELD_NAME, NEW_VALUE);
-
- assertThatThrownBy(() -> deser.getFromTree(json, this)).isInstanceOf(JsonParseException.class)
- .hasMessage(FieldDeserializer.SET_ERR + FieldDeserializerTest.class.getName() + ".text");
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import java.util.List;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-
-class FieldSerializerTest {
- private static final String TEXT_FIELD_NAME = "text";
- private static final String LIST_FIELD_NAME = "listField";
-
- private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
-
- private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
-
- private FieldSerializer ser;
-
- protected String text;
-
- private List<Data> listField;
-
- @Test
- void testAddToTree() throws Exception {
- ser = new FieldSerializer(gson, FieldSerializerTest.class.getDeclaredField(TEXT_FIELD_NAME));
-
- // serialize null value first
- text = null;
-
- JsonObject json = new JsonObject();
- ser.addToTree(this, json);
- assertTrue(json.get(TEXT_FIELD_NAME).isJsonNull());
-
- // serialize an actual value
- text = "hello";
- ser.addToTree(this, json);
- assertEquals("hello", json.get(TEXT_FIELD_NAME).getAsString());
-
- /*
- * check list field
- */
- listField = DataAdapterFactory.makeList();
-
- ser = new FieldSerializer(gson, FieldSerializerTest.class.getDeclaredField(LIST_FIELD_NAME));
-
- dataAdapter.reset();
- JsonElement tree = ser.toJsonTree(listField);
- assertTrue(dataAdapter.isDataWritten());
- assertEquals(DataAdapterFactory.ENCODED_LIST, tree.toString());
- }
-
- @Test
- void testAddToTree_GetEx() throws Exception {
- ser = new FieldSerializer(gson, FieldSerializerTest.class.getDeclaredField(TEXT_FIELD_NAME)) {
- @Override
- protected Object getFromObject(Object source) throws IllegalAccessException {
- throw new IllegalAccessException("expected exception");
- }
- };
-
- text = "world";
-
- JsonObject obj = new JsonObject();
-
- assertThatThrownBy(() -> ser.addToTree(this, obj)).isInstanceOf(JsonParseException.class)
- .hasMessage(FieldSerializer.GET_ERR + FieldSerializerTest.class.getName() + ".text");
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START==============================================================
- * ONAP
- * =======================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024-2025 OpenInfra Foundation Europe. All rights reserved.
- * =======================================================================================
- * 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END================================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonObject;
-import com.google.gson.TypeAdapter;
-import com.google.gson.TypeAdapterFactory;
-import com.google.gson.reflect.TypeToken;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-import lombok.ToString;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-class JacksonTypeAdapterTest {
- private static final String HELLO = "hello";
- private static final String WORLD = "world";
-
- /**
- * Gson object that excludes fields, as we're going to process the fields ourselves.
- */
- private static final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
-
- private JacksonTypeAdapter<Data> adapter;
- private List<Serializer> sers;
- private List<Deserializer> desers;
-
- /**
- * Initializes the previously defined fields.
- */
- @BeforeEach
- void setUp() {
- // create list of serializers, one for "id" and one for "value"
- sers = new ArrayList<>(2);
- sers.add(new NamedSer(HELLO) {
- @Override
- protected String getValue(Data data) {
- return data.id;
- }
- });
- sers.add(new NamedSer(WORLD) {
- @Override
- protected String getValue(Data data) {
- return data.value;
- }
- });
-
- // create list of deserializers, one for "id" and one for "value"
- desers = new ArrayList<>(2);
- desers.add(new NamedDeser(HELLO) {
- @Override
- protected void setValue(Data data, String value) {
- data.id = value;
- }
- });
- desers.add(new NamedDeser(WORLD) {
- @Override
- protected void setValue(Data data, String value) {
- data.value = value;
- }
- });
-
- TypeAdapterFactory factory = new TypeAdapterFactory() {
- @Override
- public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
- return null;
- }
- };
-
- TypeAdapter<Data> delegate = gson.getDelegateAdapter(factory, TypeToken.get(Data.class));
-
- adapter = new JacksonTypeAdapter<>(gson, delegate, sers, desers);
- }
-
- @Test
- void testWriteJsonWriterT() throws Exception {
- Data data = new Data("abc", "def");
-
- StringWriter wtr = new StringWriter();
- adapter.write(new JsonWriter(wtr), data);
-
- assertEquals("{'hello':'abc','world':'def'}".replace('\'', '"'), wtr.toString());
- }
-
- /**
- * Tests the case where the delegate does not return a JsonObject.
- *
- * @throws Exception if an error occurs
- */
- @Test
- void testWriteJsonWriterT_NotAnObject() throws Exception {
- TypeAdapter<String> delegate = gson.getAdapter(String.class);
- JacksonTypeAdapter<String> stringAdapter = new JacksonTypeAdapter<>(gson, delegate, sers, desers);
-
- StringWriter wtr = new StringWriter();
- stringAdapter.write(new JsonWriter(wtr), "write text");
-
- assertEquals("'write text'".replace('\'', '"'), wtr.toString());
- }
-
- @Test
- void testReadJsonReader() throws Exception {
- Data data = adapter
- .read(new JsonReader(new StringReader("{'hello':'four','world':'score'}".replace('\'', '"'))));
-
- assertEquals(new Data("four", "score").toString(), data.toString());
- }
-
- /**
- * Tests the case where the delegate does not use a JsonObject.
- *
- * @throws Exception if an error occurs
- */
- @Test
- void testReadJsonReader_NotAnObject() throws Exception {
- TypeAdapter<String> delegate = gson.getAdapter(String.class);
- JacksonTypeAdapter<String> stringAdapter = new JacksonTypeAdapter<>(gson, delegate, sers, desers);
-
- String data = stringAdapter.read(new JsonReader(new StringReader("'read text'".replace('\'', '"'))));
-
- assertEquals("read text", data);
- }
-
- @ToString
- private static class Data {
- private String id;
- private String value;
-
- /*
- * This is invoked by gson via reflection, thus no direct invocation. Hence it has
- * to be labeled "unused".
- */
- @SuppressWarnings("unused")
- public Data() {
- super();
- }
-
- public Data(String id, String value) {
- this.id = id;
- this.value = value;
- }
- }
-
- private abstract static class NamedSer implements Serializer {
- private final String name;
-
- /**
- * Constructs the object.
- *
- * @param name the name of the field, when stored in a JsonObject
- */
- public NamedSer(String name) {
- this.name = name;
- }
-
- @Override
- public void addToTree(Object source, JsonObject target) {
- Data data = (Data) source;
- target.addProperty(name, getValue(data));
- }
-
- protected abstract String getValue(Data data);
- }
-
- private abstract static class NamedDeser implements Deserializer {
- private final String name;
-
- /**
- * Constructs the object.
- *
- * @param name the name of the field, when stored in a JsonObject
- */
- public NamedDeser(String name) {
- this.name = name;
- }
-
- @Override
- public void getFromTree(JsonObject source, Object target) {
- Data data = (Data) target;
- setValue(data, source.get(name).getAsString());
- }
-
- protected abstract void setValue(Data data, String value);
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-import org.junit.jupiter.api.Test;
-
-class LifterTest {
-
- private static Gson gson = new Gson();
-
- @Test
- void testLifter_testShouldLift() throws Exception {
- Set<String> set = new HashSet<>(Arrays.asList("abc", "def"));
- Lifter lifter = new Lifter(gson, set, LifterTest.class.getDeclaredMethod("getValue"), String.class);
-
- // should not lift these
- assertFalse(lifter.shouldLift("abc"));
- assertFalse(lifter.shouldLift("def"));
-
- // should lift anything else
- assertTrue(lifter.shouldLift("hello"));
- assertTrue(lifter.shouldLift("world"));
- }
-
- public String getValue() {
- return "";
- }
-
-}
+++ /dev/null
-/*--
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonParseException;
-import org.junit.jupiter.api.Test;
-
-class MethodAdapterTest {
- private static final Gson gson = new Gson();
-
- private String saved;
-
- @Test
- void testMethodAdapter_testInvoke() throws Exception {
- MethodAdapter adapter =
- new MethodAdapter(gson, MethodAdapterTest.class.getDeclaredMethod("getValue"), String.class);
- assertEquals("hello", adapter.invoke(this));
-
- MethodAdapter adapter2 = new MethodAdapter(gson,
- MethodAdapterTest.class.getDeclaredMethod("setValue", String.class), String.class);
- adapter2.invoke(this, "world");
- assertEquals("world", saved);
-
- assertThatThrownBy(() -> adapter2.invoke(this, 100)).isInstanceOf(JsonParseException.class)
- .hasMessage(MethodAdapter.INVOKE_ERR + MethodAdapterTest.class.getName() + ".setValue");
- }
-
- public String getValue() {
- return "hello";
- }
-
- void setValue(String val) {
- saved = val;
- }
-}
+++ /dev/null
-/*--
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonNull;
-import com.google.gson.JsonObject;
-import java.util.List;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-
-class MethodDeserializerTest {
- private static final String PROP_NAME = "text";
- private static final String METHOD_NAME = "setText";
- private static final String INITIAL_VALUE = "initial value";
- private static final String NEW_VALUE = "new value";
-
- private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
-
- private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
-
- private MethodDeserializer deser;
-
- private String text;
-
- private List<Data> listField;
-
- @Test
- void testGetFromTree() throws Exception {
- deser = new MethodDeserializer(gson, MethodDeserializerTest.class.getDeclaredMethod(METHOD_NAME, String.class));
-
- // non-existent value - should not overwrite
- text = INITIAL_VALUE;
- JsonObject json = new JsonObject();
- deser.getFromTree(json, this);
- assertEquals(INITIAL_VALUE, text);
-
- // null value - should not overwrite
- text = INITIAL_VALUE;
- json.add(PROP_NAME, JsonNull.INSTANCE);
- deser.getFromTree(json, this);
- assertEquals(INITIAL_VALUE, text);
-
- // has a value - should store it
- text = INITIAL_VALUE;
- json.addProperty(PROP_NAME, NEW_VALUE);
- deser.getFromTree(json, this);
- assertEquals(NEW_VALUE, text);
-
- /*
- * check list field
- */
- deser = new MethodDeserializer(gson, MethodDeserializerTest.class.getDeclaredMethod("setTheList", List.class));
-
- json = new JsonObject();
- json.add("theList", DataAdapterFactory.makeArray());
-
- dataAdapter.reset();
- listField = null;
- deser.getFromTree(json, this);
-
- assertTrue(dataAdapter.isDataRead());
- assertNotNull(listField);
- assertEquals(DataAdapterFactory.makeList().toString(), listField.toString());
- }
-
- protected void setText(String text) {
- this.text = text;
- }
-
- protected void setTheList(List<Data> lst) {
- listField = lst;
- }
-}
+++ /dev/null
-/*--
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.gson.internal;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import java.util.List;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.gson.JacksonExclusionStrategy;
-import org.onap.policy.common.gson.internal.DataAdapterFactory.Data;
-
-class MethodSerializerTest {
- private static final String PROP_NAME = "text";
- private static final String METHOD_NAME = "getText";
-
- private static DataAdapterFactory dataAdapter = new DataAdapterFactory();
-
- private static Gson gson = new GsonBuilder().registerTypeAdapterFactory(dataAdapter)
- .setExclusionStrategies(new JacksonExclusionStrategy()).create();
-
- private MethodSerializer ser;
-
- private String text;
-
- private List<Data> listField;
-
- @Test
- void testAddToTree() throws Exception {
- ser = new MethodSerializer(gson, MethodSerializerTest.class.getDeclaredMethod(METHOD_NAME));
-
- // serialize null value first
- text = null;
-
- JsonObject json = new JsonObject();
- ser.addToTree(this, json);
- assertTrue(json.get(PROP_NAME).isJsonNull());
-
- // serialize an actual value
- text = "hello";
- ser.addToTree(this, json);
- assertEquals("hello", json.get(PROP_NAME).getAsString());
-
- /*
- * check list field
- */
- listField = DataAdapterFactory.makeList();
-
- ser = new MethodSerializer(gson, MethodSerializerTest.class.getDeclaredMethod("getTheList"));
-
- dataAdapter.reset();
- JsonElement tree = ser.toJsonTree(listField);
-
- assertTrue(dataAdapter.isDataWritten());
- assertEquals(DataAdapterFactory.ENCODED_LIST, tree.toString());
- }
-
- protected String getText() {
- return text;
- }
-
- protected List<Data> getTheList() {
- return listField;
- }
-}
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.common.message.bus.properties.MessageBusProperties;
import org.onap.policy.common.parameters.topic.TopicParameterGroup;
import org.onap.policy.common.parameters.topic.TopicParameters;
-import org.onap.policy.common.utils.gson.GsonTestUtils;
+import org.onap.policy.common.utils.jackson.JacksonTestUtils;
class TopicEndpointProxyTest {
manager.addTopicSources(configuration);
manager.addTopicSinks(configuration);
- assertThatCode(() -> new GsonTestUtils().compareGson(manager, TopicEndpointProxyTest.class))
+ assertThatCode(() -> new JacksonTestUtils().compareJson(manager, TopicEndpointProxyTest.class))
.doesNotThrowAnyException();
}
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.onap.policy.common.parameters.topic.BusTopicParams;
-import org.onap.policy.common.utils.gson.GsonTestUtils;
+import org.onap.policy.common.utils.jackson.JacksonTestUtils;
class BusTopicBaseTest extends TopicTestBase {
@Test
void testSerialize() {
- assertThatCode(() -> new GsonTestUtils().compareGson(base, BusTopicBaseTest.class)).doesNotThrowAnyException();
+ assertThatCode(() -> new JacksonTestUtils().compareJson(base, BusTopicBaseTest.class))
+ .doesNotThrowAnyException();
}
@Test
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.common.message.bus.event.Topic.CommInfrastructure;
import org.onap.policy.common.message.bus.event.TopicListener;
import org.onap.policy.common.parameters.topic.BusTopicParams;
-import org.onap.policy.common.utils.gson.GsonTestUtils;
+import org.onap.policy.common.utils.jackson.JacksonTestUtils;
class InlineBusTopicSinkTest extends TopicTestBase {
@Test
void testSerialize() {
- assertThatCode(() -> new GsonTestUtils().compareGson(sink, InlineBusTopicSinkTest.class))
+ assertThatCode(() -> new JacksonTestUtils().compareJson(sink, InlineBusTopicSinkTest.class))
.doesNotThrowAnyException();
}
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.policy.common.message.bus.event.Topic.CommInfrastructure;
import org.onap.policy.common.message.bus.event.TopicListener;
import org.onap.policy.common.parameters.topic.BusTopicParams;
-import org.onap.policy.common.utils.gson.GsonTestUtils;
+import org.onap.policy.common.utils.jackson.JacksonTestUtils;
import org.onap.policy.common.utils.network.NetworkUtil;
class SingleThreadedBusTopicSourceTest extends TopicTestBase {
@Test
void testSerialize() {
- assertThatCode(() -> new GsonTestUtils().compareGson(source, SingleThreadedBusTopicSourceTest.class))
- .doesNotThrowAnyException();
+ assertThatCode(() -> new JacksonTestUtils()
+ .compareJson(source, SingleThreadedBusTopicSourceTest.class))
+ .doesNotThrowAnyException();
}
@Test
* ONAP
* ================================================================================
* Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.junit.jupiter.api.Test;
import org.onap.policy.common.message.bus.event.Topic.CommInfrastructure;
import org.onap.policy.common.message.bus.event.TopicListener;
-import org.onap.policy.common.utils.gson.GsonTestUtils;
+import org.onap.policy.common.utils.jackson.JacksonTestUtils;
class TopicBaseTest extends TopicTestBase {
@Test
void testSerialize() {
- assertThatCode(() -> new GsonTestUtils().compareGson(base, TopicBaseTest.class)).doesNotThrowAnyException();
+ assertThatCode(() -> new JacksonTestUtils().compareJson(base, TopicBaseTest.class))
+ .doesNotThrowAnyException();
}
@Test
-/*
+/*-
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024-2025 Nordix Foundation
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
- * ============LICENSE_END=========================================================
+ *
*/
package org.onap.policy.common.utils.coder;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class StandardCoderObjectTest {
- private static final Gson gson = new Gson();
+
+ private static final ObjectMapper mapper = new ObjectMapper();
private static final String PROP1 = "abc";
private static final String PROP2 = "ghi";
private static final String PROP_2_B = "jkl";
private static final String VAL1 = "def";
private static final String VAL2 = "mno";
- private static final String JSON = "{'abc':'def','ghi':[{},{'jkl':'mno'}]}".replace('\'', '"');
+ private static final String JSON =
+ "{'abc':'def','ghi':[{},{'jkl':'mno'}]}".replace('\'', '"');
private StandardCoderObject sco;
/**
* Creates a standard object, populated with some data.
- *
- * @throws Exception if an error occurs
*/
@BeforeEach
void setUp() throws Exception {
- sco = new StandardCoderObject(gson.fromJson(JSON, JsonElement.class));
+ sco = new StandardCoderObject(mapper.readTree(JSON));
}
@Test
}
@Test
- void testStandardCoderObjectJsonElement() {
+ void testStandardCoderObjectJsonElement() throws JsonProcessingException {
assertNotNull(sco.getData());
- assertEquals(JSON, gson.toJson(sco.getData()));
+ assertEquals(JSON, mapper.writeValueAsString(sco.getData()));
}
@Test
assertNull(new StandardCoderObject().getString());
assertNull(new StandardCoderObject().getString(PROP1));
- JsonElement obj = gson.fromJson("{'abc':[]}".replace('\'', '"'), JsonElement.class);
+ JsonNode obj = mapper.readTree("{'abc':[]}".replace('\'', '"'));
sco = new StandardCoderObject(obj);
// not a primitive
}
@Test
- void testGetFieldFromObject() {
+ void testGetFieldFromObject() throws JsonProcessingException {
// not an object
assertNull(sco.getFieldFromObject(fromJson("[]"), PROP1));
assertNull(sco.getFieldFromObject(fromJson("{}"), "non-existent"));
// field exists
- assertEquals(4, sco.getFieldFromObject(fromJson("{\"world\":4}"), "world").getAsInt());
+ assertEquals(4,
+ sco.getFieldFromObject(fromJson("{\"world\":4}"), "world").asInt());
}
@Test
- void testGetItemFromArray() {
+ void testGetItemFromArray() throws JsonProcessingException {
// not an array
assertNull(sco.getItemFromArray(fromJson("{}"), 0));
// negative index
- assertThatIllegalArgumentException().isThrownBy(() -> sco.getItemFromArray(fromJson("[]"), -1));
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> sco.getItemFromArray(fromJson("[]"), -1));
// index out of bounds
assertNull(sco.getItemFromArray(fromJson("[5]"), 1));
assertNull(sco.getItemFromArray(fromJson("[5]"), 2));
// index exists
- assertEquals(6, sco.getItemFromArray(fromJson("[5,6,7]"), 1).getAsInt());
+ assertEquals(6,
+ sco.getItemFromArray(fromJson("[5,6,7]"), 1).asInt());
// edge case: first and last item
- assertEquals(50, sco.getItemFromArray(fromJson("[50,60,70]"), 0).getAsInt());
- assertEquals(700, sco.getItemFromArray(fromJson("[500,600,700]"), 2).getAsInt());
+ assertEquals(50,
+ sco.getItemFromArray(fromJson("[50,60,70]"), 0).asInt());
+ assertEquals(700,
+ sco.getItemFromArray(fromJson("[500,600,700]"), 2).asInt());
}
- private JsonElement fromJson(String json) {
- return gson.fromJson(json, JsonElement.class);
+ private JsonNode fromJson(String json) throws JsonProcessingException {
+ return mapper.readTree(json);
}
}
-/*
+/*-
* ============LICENSE_START=======================================================
- * ONAP PAP
+ * ONAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
- * ============LICENSE_END=========================================================
+ *
*/
package org.onap.policy.common.utils.coder;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParseException;
-import com.google.gson.JsonSyntaxException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
-import java.io.FileReader;
import java.io.IOException;
-import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import java.util.TreeMap;
import lombok.ToString;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class StandardCoderTest {
+
private static final String EXPECTED_EXCEPTION = "expected exception";
- private static final JsonParseException jpe = new JsonParseException(EXPECTED_EXCEPTION);
+ private static final JsonProcessingException jpe =
+ new JsonProcessingException(EXPECTED_EXCEPTION) {};
+
private static final IOException ioe = new IOException(EXPECTED_EXCEPTION);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
private StandardCoder coder;
@BeforeEach
}
@Test
- void testConvert() throws CoderException {
+ void testConvert() throws Exception {
// null source
assertNull(coder.convert(null, StandardCoderObject.class));
// source is a string
assertEquals(Integer.valueOf(10), coder.convert("10", Integer.class));
-
- // target is a string
assertEquals("10", coder.convert(10, String.class));
// source and target are different types, neither is a string
sco = coder.convert(Map.of("hello", "world"), StandardCoderObject.class);
assertEquals("world", sco.getString("hello"));
- // throw an exeception
+ // throw an exception
coder = new StandardCoder() {
@Override
- protected <T> T fromJson(JsonElement json, Class<T> clazz) {
- throw jpe;
+ protected <T> T fromJson(JsonNode json, Class<T> clazz) throws CoderException {
+ throw new CoderException(jpe);
}
};
- assertThatThrownBy(() -> coder.convert(10, Long.class)).isInstanceOf(CoderException.class).hasCause(jpe);
+ assertThatThrownBy(() -> coder.convert(10, Long.class))
+ .isInstanceOf(CoderException.class)
+ .hasRootCause(jpe);
}
@Test
// test exception case
coder = spy(new StandardCoder());
when(coder.toJson(arr)).thenThrow(jpe);
- assertThatThrownBy(() -> coder.encode(arr)).isInstanceOf(CoderException.class).hasCause(jpe);
+
+ assertThatThrownBy(() -> coder.encode(arr))
+ .isInstanceOf(CoderException.class)
+ .hasCause(jpe);
}
@Test
void testEncodeObjectBoolean() throws Exception {
final List<Integer> arr = Arrays.asList(1100, 1110);
- /*
- * As plain json.
- */
assertEquals("[1100,1110]", coder.encode(arr, false));
// test exception case
coder = spy(new StandardCoder());
when(coder.toJson(arr)).thenThrow(jpe);
- assertThatThrownBy(() -> coder.encode(arr, false)).isInstanceOf(CoderException.class).hasCause(jpe);
+ assertThatThrownBy(() -> coder.encode(arr, false))
+ .isInstanceOf(CoderException.class)
+ .hasCause(jpe);
- /*
- * As pretty json.
- */
- assertEquals("[\n 1100,\n 1110\n]", coder.encode(arr, true));
+ assertEquals("[ 1100, 1110 ]", coder.encode(arr, true));
// test exception case
coder = spy(new StandardCoder());
when(coder.toPrettyJson(arr)).thenThrow(jpe);
- assertThatThrownBy(() -> coder.encode(arr, true)).isInstanceOf(CoderException.class).hasCause(jpe);
+
+ assertThatThrownBy(() -> coder.encode(arr, true))
+ .isInstanceOf(CoderException.class)
+ .hasCause(jpe);
}
@Test
void testEncodeWriterObject() throws Exception {
List<Integer> arr = Arrays.asList(1200, 1210);
StringWriter wtr = new StringWriter();
+
coder.encode(wtr, arr);
assertEquals("[1200,1210]", wtr.toString());
// test json exception
coder = spy(new StandardCoder());
doThrow(jpe).when(coder).toJson(wtr, arr);
- assertThatThrownBy(() -> coder.encode(wtr, arr)).isInstanceOf(CoderException.class).hasCause(jpe);
+ assertThatThrownBy(() -> coder.encode(wtr, arr))
+ .isInstanceOf(CoderException.class)
+ .hasCause(jpe);
}
+
@Test
void testEncodeOutputStreamObject() throws Exception {
List<Integer> arr = Arrays.asList(1300, 1310);
when(coder.makeWriter(stream)).thenReturn(wtr);
doThrow(jpe).when(coder).toJson(wtr, arr);
assertThatThrownBy(() -> coder.encode(stream, arr)).isInstanceOf(CoderException.class).hasCause(jpe);
-
- // test exception when flushed
- wtr = spy(new OutputStreamWriter(stream));
- doThrow(ioe).when(wtr).flush();
- coder = spy(new StandardCoder());
- when(coder.makeWriter(stream)).thenReturn(wtr);
- assertThatThrownBy(() -> coder.encode(stream, arr)).isInstanceOf(CoderException.class).hasCause(ioe);
}
@Test
assertThatThrownBy(() -> coder.encode(file, arr)).isInstanceOf(CoderException.class).hasCause(jpe);
// test exception when closed
- coder = spy(new StandardCoder());
wtr = spy(new StringWriter());
+ StringWriter finalWtr1 = wtr;
+ coder = spy(new StandardCoder() {
+ @Override
+ protected Writer makeWriter(File f) {
+ return finalWtr1;
+ }
+ });
doThrow(ioe).when(wtr).close();
- coder = spy(new StandardCoder());
- when(coder.makeWriter(file)).thenReturn(wtr);
- assertThatThrownBy(() -> coder.encode(file, arr)).isInstanceOf(CoderException.class).hasCause(ioe);
+
+ assertThatThrownBy(() -> coder.encode(file, arr))
+ .isInstanceOf(CoderException.class)
+ .hasRootCause(ioe);
}
@Test
void testDecodeStringClass() throws Exception {
String text = "[2200,2210]";
- assertEquals(text, coder.decode(text, JsonElement.class).toString());
+ assertEquals(text, coder.decode(text, JsonNode.class).toString());
- // test json exception
coder = spy(new StandardCoder());
- when(coder.fromJson(text, JsonElement.class)).thenThrow(jpe);
- assertThatThrownBy(() -> coder.decode(text, JsonElement.class)).isInstanceOf(CoderException.class)
- .hasCause(jpe);
+ when(coder.fromJson(text, JsonNode.class)).thenThrow(jpe);
+
+ assertThatThrownBy(() -> coder.decode(text, JsonNode.class))
+ .isInstanceOf(CoderException.class)
+ .hasCause(jpe);
}
@Test
void testDecodeReaderClass() throws Exception {
String text = "[2300,2310]";
- assertEquals(text, coder.decode(new StringReader(text), JsonElement.class).toString());
+ assertEquals(text, coder.decode(new StringReader(text), JsonNode.class).toString());
// test json exception
coder = spy(new StandardCoder());
StringReader rdr = new StringReader(text);
- when(coder.fromJson(rdr, JsonElement.class)).thenThrow(jpe);
- assertThatThrownBy(() -> coder.decode(rdr, JsonElement.class)).isInstanceOf(CoderException.class).hasCause(jpe);
+ when(coder.fromJson(rdr, JsonNode.class)).thenThrow(jpe);
+ assertThatThrownBy(() -> coder.decode(rdr, JsonNode.class)).isInstanceOf(CoderException.class).hasCause(jpe);
}
@Test
void testDecodeInputStreamClass() throws Exception {
String text = "[2400,2410]";
assertEquals(text,
- coder.decode(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), JsonElement.class)
- .toString());
+ coder.decode(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), JsonNode.class)
+ .toString());
// test json exception
coder = spy(new StandardCoder());
ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
- StringReader rdr = new StringReader(text);
+ var rdr = new StringReader(text);
when(coder.makeReader(stream)).thenReturn(rdr);
- when(coder.fromJson(rdr, JsonElement.class)).thenThrow(jpe);
- assertThatThrownBy(() -> coder.decode(stream, JsonElement.class)).isInstanceOf(CoderException.class)
- .hasCause(jpe);
+ when(coder.fromJson(rdr, JsonNode.class)).thenThrow(jpe);
+ assertThatThrownBy(() -> coder.decode(stream, JsonNode.class)).isInstanceOf(CoderException.class)
+ .hasCause(jpe);
}
@Test
void testDecodeFileClass() throws Exception {
File file = new File(getClass().getResource(StandardCoder.class.getSimpleName() + ".json").getFile());
- String text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
- assertEquals(text, coder.decode(file, JsonElement.class).toString());
+ var text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
+ assertEquals(text, coder.decode(file, JsonNode.class).toString());
// test FileNotFoundException case
- assertThatThrownBy(() -> coder.decode(new File("unknown-file"), JsonElement.class))
- .isInstanceOf(CoderException.class).hasCauseInstanceOf(FileNotFoundException.class);
+ assertThatThrownBy(() -> coder.decode(new File("unknown-file"), JsonNode.class))
+ .isInstanceOf(CoderException.class).hasCauseInstanceOf(FileNotFoundException.class);
// test json exception
Reader rdr = new StringReader(text);
coder = spy(new StandardCoder());
when(coder.makeReader(file)).thenReturn(rdr);
- when(coder.fromJson(rdr, JsonElement.class)).thenThrow(jpe);
- assertThatThrownBy(() -> coder.decode(file, JsonElement.class)).isInstanceOf(CoderException.class)
- .hasCause(jpe);
-
- // test IOException case
- rdr = spy(new FileReader(file));
- doThrow(ioe).when(rdr).close();
- coder = spy(new StandardCoder());
- when(coder.makeReader(file)).thenReturn(rdr);
- assertThatThrownBy(() -> coder.decode(file, JsonElement.class)).isInstanceOf(CoderException.class)
- .hasCause(ioe);
+ when(coder.fromJson(rdr, JsonNode.class)).thenThrow(jpe);
+ assertThatThrownBy(() -> coder.decode(file, JsonNode.class)).isInstanceOf(CoderException.class)
+ .hasCause(jpe);
}
@Test
- void testToJsonTree_testFromJsonJsonElementClassT() {
+ void testToJsonTree_testFromJsonJsonElementClassT() throws CoderException {
MyMap map = new MyMap();
map.props = new LinkedHashMap<>();
map.props.put("jel keyA", "jel valueA");
map.props.put("jel keyB", "jel valueB");
- JsonElement json = coder.toJsonTree(map);
+ JsonNode json = MAPPER.valueToTree(map);
assertEquals("{'props':{'jel keyA':'jel valueA','jel keyB':'jel valueB'}}".replace('\'', '"'), json.toString());
Object result = coder.fromJson(json, MyMap.class);
@Test
void testConvertFromDouble() throws Exception {
- String text = "[listA, {keyA=100}, 200]";
- assertEquals(text, coder.decode(text, Object.class).toString());
+ String text = "[\"listA\", {\"keyA\":100}, 200]";
+ assertEquals("[listA, {keyA=100}, 200]", coder.decode(text, Object.class).toString());
- text = "{keyB=200}";
- assertEquals(text, coder.decode(text, Object.class).toString());
+ text = "{\"keyB\":200}";
+ assertEquals("{keyB=200}", coder.decode(text, Object.class).toString());
}
+
@Test
void testToStandard() throws Exception {
MyObject obj = new MyObject();
obj.abc = "xyz";
+
StandardCoderObject sco = coder.toStandard(obj);
assertNotNull(sco.getData());
- assertEquals("{'abc':'xyz'}".replace('\'', '"'), sco.getData().toString());
+ assertEquals("{\"abc\":\"xyz\"}", sco.getData().toString());
// class instead of object -> exception
- assertThatThrownBy(() -> coder.toStandard(String.class)).isInstanceOf(CoderException.class);
+ assertThatThrownBy(() -> coder.toStandard(String.class))
+ .isInstanceOf(CoderException.class);
}
@Test
void testFromStandard() throws Exception {
MyObject obj = new MyObject();
obj.abc = "pdq";
- StandardCoderObject sco = coder.toStandard(obj);
+ StandardCoderObject sco = coder.toStandard(obj);
MyObject obj2 = coder.fromStandard(sco, MyObject.class);
+
assertEquals(obj.toString(), obj2.toString());
// null class -> exception
- assertThatThrownBy(() -> coder.fromStandard(sco, null)).isInstanceOf(CoderException.class);
- }
-
- @Test
- void testStandardTypeAdapter() {
- String json = "{'abc':'def'}".replace('\'', '"');
- StandardCoderObject sco = coder.fromJson(json, StandardCoderObject.class);
- assertNotNull(sco.getData());
- assertEquals(json, sco.getData().toString());
- assertEquals(json, coder.toJson(sco));
-
- // invalid json -> exception
- StringReader rdr = new StringReader("[");
- assertThatThrownBy(() -> coder.fromJson(rdr, StandardCoderObject.class))
- .isInstanceOf(JsonSyntaxException.class);
+ assertThatThrownBy(() -> coder.fromStandard(sco, null))
+ .isInstanceOf(CoderException.class);
}
@Test
map.props.put("posLong", 100000000000L);
String json = coder.encode(map);
-
map.props.clear();
map = coder.decode(json, MyMap.class);
assertEquals(-10, map.props.get("negInt"));
assertEquals(100000000000L, map.props.get("posLong"));
assertEquals(12.5, map.props.get("doubleVal"));
-
- // test when decoding into a map
- @SuppressWarnings("unchecked")
- Map<String, Object> map2 = coder.decode("{'intValue':10, 'dblVal':20.1}", TreeMap.class);
- assertEquals("{dblVal=20.1, intValue=10}", map2.toString());
}
@Test
assertEquals("[10, 20.1, 30]", list.toString());
}
-
@ToString
- private static class MyObject {
- private String abc;
+ public static class MyObject {
+ public String abc;
}
public static class MyMap {
- private Map<String, Object> props;
+ public Map<String, Object> props;
@Override
public String toString() {
* ONAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
+ * Modifications Copyright (C) 2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
assertNotNull(container.map.get("itemB"));
assertEquals("stringB", container.map.get("itemB").stringVal);
- double dbl = 123456789012345678901234567890.0;
- assertEquals(dbl, container.map.get("itemB").doubleVal, 1000.0);
+ double dbl = 123456.789;
+ assertEquals(dbl, container.map.get("itemB").doubleVal, 0.001);
assertNotNull(container.map.get("itemC"));
assertTrue(container.map.get("itemC").boolVal);
@EqualsAndHashCode
public static class Container {
- protected Item item;
- protected List<Item> list;
- protected Map<String, Item> map;
+ public Item item;
+ public List<Item> list;
+ public Map<String, Item> map;
+
+ public Container() {
+ // Default constructor for Jackson
+ }
}
@EqualsAndHashCode
public static class Item {
- protected boolean boolVal;
- protected int intVal;
- protected long longVal;
- protected double doubleVal;
- protected float floatVal;
- protected String stringVal;
- protected Object nullVal;
- protected Item another;
+ public boolean boolVal;
+ public int intVal;
+ public long longVal;
+ public double doubleVal;
+ public float floatVal;
+ public String stringVal;
+ public Object nullVal;
+ public Item another;
+
+ public Item() {
+ // Default constructor for Jackson
+ }
}
}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.utils.gson;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import java.io.StringReader;
-import org.junit.jupiter.api.Test;
-
-class GsonSerializerTest {
-
- @Test
- void testReadJsonReader() {
- JsonReader rdr = new JsonReader(new StringReader("10"));
-
- GsonSerializer<Object> ser = new GsonSerializer<Object>() {
- @Override
- public void write(JsonWriter out, Object value) throws IOException {
- // do nothing
- }
- };
-
- assertThatThrownBy(() -> ser.read(rdr)).isInstanceOf(UnsupportedOperationException.class)
- .hasMessage("read from pseudo TypeAdapter");
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.utils.gson;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import com.google.gson.Gson;
-import com.google.gson.TypeAdapter;
-import com.google.gson.TypeAdapterFactory;
-import com.google.gson.reflect.TypeToken;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-class GsonTestUtilsBuilderTest {
-
- private GsonTestUtils utils;
-
- @BeforeEach
- void setUp() {
- utils = new MyBuilder().build();
- }
-
- @Test
- void testBuilderAddMock() {
- PreMock pre = mock(PreMock.class);
- when(pre.getId()).thenReturn(2000);
-
- assertEquals("{\"name\":2000}", utils.gsonEncode(pre));
- }
-
- /**
- * Builder that provides an adapter for mock(PreMock.class).
- */
- private static class MyBuilder extends GsonTestUtilsBuilder {
- public MyBuilder() {
- TypeAdapterFactory sgson = new TypeAdapterFactory() {
- @Override
- public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
- Class<? super T> clazz = type.getRawType();
-
- if (PreMock.class.isAssignableFrom(clazz)) {
- return new GsonSerializer<T>() {
- @Override
- public void write(JsonWriter out, T value) throws IOException {
- PreMock obj = (PreMock) value;
- out.beginObject().name("name").value(obj.getId()).endObject();
- }
- };
- }
-
- return null;
- }
- };
-
- addMock(PreMock.class, sgson);
- }
- }
-
- /**
- * Class that will be mocked.
- */
- public static class PreMock {
- protected int id = 1000;
-
- public int getId() {
- return id;
- }
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.utils.gson;
-
-import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonNull;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import lombok.Getter;
-import lombok.Setter;
-import lombok.ToString;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-class GsonTestUtilsTest {
- private static final String HELLO = "hello";
-
- private GsonTestUtils utils;
-
- @BeforeEach
- void setUp() {
- utils = new GsonTestUtils();
- }
-
- @Test
- void testGetGson() {
- assertNotNull(utils.getGson());
- }
-
- @Test
- void testGsonRoundTrip() {
- Data data = new Data();
- data.setId(500);
-
- // try with null text
- data.setText(null);
- assertEquals(data.toString(), utils.gsonRoundTrip(data, Data.class).toString());
-
- // try with non-null text
- data.setText(HELLO);
- assertEquals(data.toString(), utils.gsonRoundTrip(data, Data.class).toString());
- }
-
- @Test
- void testCompareGsonObjectClass_testCompareGsonObjectFile() {
- Data data = new Data();
- data.setId(500);
- data.setText(HELLO);
-
- utils.compareGson(data, GsonTestUtilsTest.class);
-
- // file not found
- File file = new File(GsonTestUtilsTest.class.getSimpleName() + "-NotFound.json");
-
- assertThatThrownBy(() -> utils.compareGson(data, file))
- .isInstanceOf(JsonParseException.class)
- .hasCauseInstanceOf(FileNotFoundException.class);
-
- // force I/O error while reading file
- GsonTestUtils utils2 = new GsonTestUtils() {
- @Override
- protected String readFile(File file) throws IOException {
- throw new IOException("expected exception");
- }
- };
- assertThatThrownBy(() -> utils2.compareGson(data, GsonTestUtilsTest.class))
- .isInstanceOf(JsonParseException.class).hasCauseInstanceOf(IOException.class)
- .hasMessage("error reading: GsonTestUtilsTest.json");
- }
-
- @Test
- void testCompareGsonObjectString() {
- Data data = new Data();
- data.setId(600);
- data.setText(HELLO);
-
- assertThatCode(() -> utils.compareGson(data, "{'id': ${obj.id}, 'text': '${obj.text}'}".replace('\'', '"')))
- .doesNotThrowAnyException();
- }
-
- @Test
- void testCompareGsonObjectJsonElement() {
- Data data = new Data();
- data.setId(650);
- data.setText(HELLO);
-
- JsonObject json = new JsonObject();
- json.addProperty("id", data.getId());
- json.addProperty("text", data.getText());
-
- utils.compareGson(data, json);
-
- // mismatch
- data.setText("world");
- assertThatThrownBy(() -> utils.compareGson(data, json)).isInstanceOf(AssertionError.class);
- }
-
- @Test
- void testApplyScripts() {
- Data data = new Data();
- data.setId(700);
- data.setText(HELLO);
-
- String result = utils.applyScripts("no interpolation", data);
- assertEquals("no interpolation", result);
-
- result = utils.applyScripts("${obj.id} at start, ${obj.text} in middle, and end ${obj.id}", data);
- assertEquals("700 at start, hello in middle, and end 700", result);
-
- // try null value
- data.setText(null);
- result = utils.applyScripts("use ${obj.text} this", data);
- assertEquals("use null this", result);
- assertEquals("use null this", utils.applyScripts("use ${obj.text} this", null));
- }
-
- @Test
- void testReorderJsonObject() {
- // insert properties in a non-alphabetical order
- JsonObject inner = new JsonObject();
- inner.addProperty("objBint", 100);
- inner.add("objBNull", JsonNull.INSTANCE);
- inner.addProperty("objB", true);
-
- JsonArray arr = new JsonArray();
- arr.add(110);
- arr.add(inner);
- arr.add(false);
-
- JsonObject outer = new JsonObject();
- outer.add("objANull", JsonNull.INSTANCE);
- outer.addProperty("objA", true);
- outer.addProperty("objAStr", "obj-a-string");
- outer.add("nested-array", arr);
-
- outer = utils.reorder(outer);
- assertEquals("{'nested-array':[110,{'objB':true,'objBint':100},false],'objA':true,'objAStr':'obj-a-string'}"
- .replace('\'', '"'), outer.toString());
- }
-
- @Test
- void testReorderJsonArray() {
- // insert properties in a non-alphabetical order
- JsonObject inner = new JsonObject();
- inner.add("objCNull", JsonNull.INSTANCE);
- inner.addProperty("objCStr", "obj-c-string");
- inner.addProperty("objC", true);
-
- JsonArray arr = new JsonArray();
- arr.add(200);
- arr.add(inner);
- arr.add(false);
-
- arr = utils.reorder(arr);
- assertEquals("[200,{'objC':true,'objCStr':'obj-c-string'},false]".replace('\'', '"'), arr.toString());
- }
-
- @Test
- void testReorderJsonElement() {
- // null element
- JsonElement jsonEl = null;
- assertNull(utils.reorder(jsonEl));
-
- // object element
- JsonObject obj = new JsonObject();
- obj.add("objDNull", JsonNull.INSTANCE);
- obj.addProperty("objDStr", "obj-d-string");
- obj.addProperty("objD", true);
- jsonEl = obj;
- jsonEl = utils.reorder(jsonEl);
- assertEquals("{'objD':true,'objDStr':'obj-d-string'}".replace('\'', '"'), jsonEl.toString());
-
- // boolean
- jsonEl = obj.get("objD");
- jsonEl = utils.reorder(jsonEl);
- assertEquals("true", jsonEl.toString());
-
- // JsonNull
- jsonEl = JsonNull.INSTANCE;
- jsonEl = utils.reorder(jsonEl);
- assertEquals("null", jsonEl.toString());
-
- // array element
- JsonObject inner = new JsonObject();
- inner.add("objENull", JsonNull.INSTANCE);
- inner.addProperty("objEStr", "obj-e-string");
- inner.addProperty("objE", true);
-
- JsonArray arr = new JsonArray();
- arr.add(300);
- arr.add(inner);
- arr.add(false);
- jsonEl = arr;
- jsonEl = utils.reorder(jsonEl);
- assertEquals("[300,{'objE':true,'objEStr':'obj-e-string'},false]".replace('\'', '"'), jsonEl.toString());
- }
-
- @Setter
- @Getter
- @ToString
- public static class Data {
- private int id;
- private String text;
-
- }
-}
--- /dev/null
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2026 OpenInfra Foundation Europe. All rights reserved
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.common.utils.jackson;
+
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.NullNode;
+import java.io.File;
+import java.io.IOException;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class JacksonTestUtilsTest {
+ private static final String HELLO = "hello";
+ private JacksonTestUtils utils;
+
+ @BeforeEach
+ void setUp() {
+ utils = new JacksonTestUtils();
+ }
+
+ @Test
+ void testCompareJsonObjectClass_testCompareJsonObjectFile() {
+ var data = new Data();
+ data.setId(500);
+ data.setText(HELLO);
+ // file not found
+ var file = new File(JacksonTestUtilsTest.class.getSimpleName() + "-NotFound.json");
+ assertThatThrownBy(() -> utils.compareJson(data, file))
+ .isInstanceOf(JsonParseException.class);
+ // force I/O error while reading file
+ JacksonTestUtils utils2 = new JacksonTestUtils() {
+ @Override
+ protected String readFile(File file) throws IOException {
+ throw new IOException("expected exception");
+ }
+ };
+ var file2 = new File(JacksonTestUtilsTest.class.getSimpleName() + ".json");
+ assertThatThrownBy(() -> utils2.compareJson(data, file2)).isInstanceOf(JsonParseException.class)
+ .hasMessage("error reading: expected exception");
+ }
+
+ @Test
+ void testCompareJsonObjectString() {
+ var data = new Data();
+ data.setId(600);
+ data.setText(HELLO);
+ assertThatCode(() -> utils.compareJson(data, "{\"id\":600,\"text\":\"hello\"}"))
+ .doesNotThrowAnyException();
+ assertThrows(JsonParseException.class, () -> utils.compareJson(data, "invalid string"));
+ }
+
+ @Test
+ void testCompareJsonObjectJsonElement() throws JsonParseException {
+ var data = new Data();
+ data.setId(650);
+ data.setText(HELLO);
+ var json = new ObjectMapper().createObjectNode();
+ json.putPOJO("id", data.getId());
+ json.putPOJO("text", data.getText());
+ assertDoesNotThrow(() -> utils.compareJson(data, json));
+ // mismatch
+ data.setText("world");
+ assertThatThrownBy(() -> utils.compareJson(data, json)).isInstanceOf(AssertionError.class);
+ assertThrows(JsonParseException.class, () -> utils.compareJson(new Object(), json));
+ }
+
+ @Test
+ void testReorderJsonObject() {
+ // insert properties in a non-alphabetical order
+ var mapper = new ObjectMapper();
+ var inner = mapper.createObjectNode();
+ inner.put("objBint", 100);
+ inner.put("objB", true);
+ var arr = mapper.createArrayNode();
+ arr.add(110);
+ arr.add(inner);
+ arr.add(false);
+ var outer = mapper.createObjectNode();
+ outer.putPOJO("objA", true);
+ outer.putPOJO("objAStr", "obj-a-string");
+ outer.putPOJO("nested-array", arr);
+ outer = utils.reorder(outer);
+ assertEquals("{'nested-array':[110,{'objBint':100,'objB':true},false],'objA':true,'objAStr':'obj-a-string'}"
+ .replace('\'', '"'), outer.toString());
+ }
+
+ @Test
+ void testReorderJsonArray() {
+ // insert properties in a non-alphabetical order
+ var mapper = new ObjectMapper();
+ var inner = mapper.createObjectNode();
+ inner.put("objCStr", "obj-c-string");
+ inner.put("objC", true);
+ var arr = mapper.createArrayNode();
+ arr.add(200);
+ arr.add(inner);
+ arr.add(false);
+ arr = utils.reorder(arr);
+ assertEquals("[200,{'objC':true,'objCStr':'obj-c-string'},false]".replace('\'', '"'), arr.toString());
+ }
+
+ @Test
+ void testReorderJsonElement() {
+ // null element
+ JsonNode jsonNode = null;
+ assertTrue(utils.reorder(jsonNode).isNull());
+ var mapper = new ObjectMapper();
+ // object element
+ var obj = mapper.createObjectNode();
+ obj.set("objDNull", NullNode.instance);
+ obj.put("objDStr", "obj-d-string");
+ obj.put("objD", true);
+ jsonNode = obj;
+ jsonNode = utils.reorder(jsonNode);
+ assertEquals("{'objD':true,'objDStr':'obj-d-string'}".replace('\'', '"'), jsonNode.toString());
+ // boolean
+ jsonNode = obj.get("objD");
+ jsonNode = utils.reorder(jsonNode);
+ assertEquals("true", jsonNode.toString());
+ // JsonNull
+ jsonNode = NullNode.instance;
+ jsonNode = utils.reorder(jsonNode);
+ assertEquals("null", jsonNode.toString());
+ // array element
+ var inner = mapper.createObjectNode();
+ inner.put("objEStr", "obj-e-string");
+ inner.put("objE", true);
+ var arr = mapper.createArrayNode();
+ arr.add(300);
+ arr.add(inner);
+ arr.add(false);
+ jsonNode = arr;
+ jsonNode = utils.reorder(jsonNode);
+ assertEquals("[300,{'objE':true,'objEStr':'obj-e-string'},false]".replace('\'', '"'), jsonNode.toString());
+ }
+
+ @Setter
+ @Getter
+ @ToString
+ public static class Data {
+ private int id;
+ private String text;
+ }
+}
+
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020-2021, 2023-2024 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2021, 2023-2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
normalizePath(resultD2.iterator().next()));
Set<String> resultJ0 = ResourceUtils.getDirectoryContents("com");
- assertTrue(resultJ0.contains("com/google/"));
- assertEquals("com/google/", normalizePath(resultJ0.iterator().next()));
+ assertTrue(resultJ0.contains("com/fasterxml/"));
+ assertEquals("com/fasterxml/", normalizePath(resultJ0.iterator().next()));
- Set<String> resultJ1 = ResourceUtils.getDirectoryContents("com/google/gson");
+ Set<String> resultJ1 = ResourceUtils.getDirectoryContents("com/fasterxml/jackson/core");
assertTrue(resultJ1.size() > 1);
- assertTrue(resultJ1.contains("com/google/gson/JsonElement.class"));
+ assertTrue(resultJ1.contains("com/fasterxml/jackson/core/Base64Variants.class"));
URL dummyUrl = new URL("http://even/worse");
assertTrue(ResourceUtils.getDirectoryContentsJar(dummyUrl, "nonexistantdirectory").isEmpty());
stringVal: stringA
itemB:
stringVal: stringB
- doubleVal: 123456789012345678901234567890
+ doubleVal: 123456.789
itemC: *top
{
- "id": ${obj.id},
+ "id": "${obj.id}",
"text": "${obj.text}"
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
============LICENSE_START=======================================================
- Copyright (C) 2025 OpenInfra Foundation Europe. All rights reserved.
+ Copyright (C) 2025-2026 OpenInfra Foundation Europe. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
<artifactId>policy-common</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
<dependency>
<groupId>com.google.re2j</groupId>
<artifactId>re2j</artifactId>
/*
* ============LICENSE_START=======================================================
- * ONAP Policy Decision Models
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.errors.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.ws.rs.core.Response;
import java.io.Serial;
import java.io.Serializable;
@Serial
private static final long serialVersionUID = 6760066094588944729L;
- @SerializedName("code")
+ @JsonProperty("code")
private Response.Status responseCode;
- @SerializedName("error")
+ @JsonProperty("error")
private String errorMessage;
- @SerializedName("details")
+ @JsonProperty("details")
private List<String> errorDetails;
- @SerializedName("warnings")
+ @JsonProperty("warnings")
private List<String> warningDetails;
}
* ONAP Policy Model
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Data;
*/
@Data
public class ToscaConstraint {
- @SerializedName("valid_values")
+ @JsonProperty("valid_values")
private List<String> validValues;
private String equal;
- @SerializedName("greater_than")
+ @JsonProperty("greater_than")
private String greaterThan;
- @SerializedName("greater_or_equal")
+ @JsonProperty("greater_or_equal")
private String greaterOrEqual;
- @SerializedName("less_than")
+ @JsonProperty("less_than")
private String lessThan;
- @SerializedName("less_or_equal")
+ @JsonProperty("less_or_equal")
private String lessOrEqual;
- @SerializedName("in_range")
+ @JsonProperty("in_range")
private List<String> rangeValues;
}
* ONAP Policy Model
* ================================================================================
* Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ToscaDataType extends ToscaWithToscaProperties {
private List<ToscaConstraint> constraints;
}
* ============LICENSE_START=======================================================
* ONAP Policy Model
* ================================================================================
- * Copyright (C) 2019-2023 Nordix Foundation.
+ * Copyright (C) 2019-2023,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.ws.rs.core.Response;
import java.util.LinkedHashMap;
import java.util.List;
*/
@Data
@NoArgsConstructor
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ToscaEntity implements PfNameVersion {
private String name = PfKey.NULL_KEY_NAME;
private String version = PfKey.NULL_KEY_VERSION;
- @SerializedName("derived_from")
+ @JsonProperty("derived_from")
private String derivedFrom;
private Map<String, Object> metadata;
*
* @return a ToscaEntityKey for this entry
*/
+ @JsonIgnore
public ToscaEntityKey getKey() {
return new ToscaEntityKey(name, version);
}
* ============LICENSE_START=======================================================
* ONAP Policy Model
* ================================================================================
- * Copyright (C) 2020 Nordix Foundation.
+ * Copyright (C) 2020,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
private String name;
private String type;
- @SerializedName("type_version")
-
+ @JsonProperty("type_version")
private String typeVersion;
+
private Object value;
}
* ONAP Policy Model
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019-2020 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
import lombok.Data;
private String name;
private String type;
- @SerializedName("type_version")
+ @JsonProperty("type_version")
private String typeVersion;
private String description;
- @SerializedName("default")
+ @JsonProperty("default")
private Object defaultValue;
private boolean required = false;
private Status status;
private List<ToscaConstraint> constraints;
- @SerializedName("key_schema")
+ @JsonProperty("key_schema")
private ToscaSchemaDefinition keySchema;
- @SerializedName("entry_schema")
+ @JsonProperty("entry_schema")
private ToscaSchemaDefinition entrySchema;
private Map<String, String> metadata;
* ONAP Policy Model
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Data;
private String name;
private String type;
- @SerializedName("type_version")
+ @JsonProperty("type_version")
private String typeVersion;
private String description;
* ONAP Policy Model
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Data;
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ToscaServiceTemplate extends ToscaEntity {
- @SerializedName("tosca_definitions_version")
+ @JsonProperty("tosca_definitions_version")
private String toscaDefinitionsVersion;
- @SerializedName("data_types")
+ @JsonProperty("data_types")
private Map<String, ToscaDataType> dataTypes;
- @SerializedName("capability_types")
+ @JsonProperty("capability_types")
private Map<String, ToscaCapabilityType> capabilityTypes;
- @SerializedName("node_types")
+ @JsonProperty("node_types")
private Map<String, ToscaNodeType> nodeTypes;
- @SerializedName("relationship_types")
+ @JsonProperty("relationship_types")
private Map<String, ToscaRelationshipType> relationshipTypes;
- @SerializedName("policy_types")
+ @JsonProperty("policy_types")
private Map<String, ToscaPolicyType> policyTypes;
- @SerializedName("topology_template")
+ @JsonProperty("topology_template")
private ToscaTopologyTemplate toscaTopologyTemplate;
+ @JsonIgnore
public Map<ToscaEntityKey, ToscaDataType> getDataTypesAsMap() {
return ToscaEntity.getEntityMapAsMap(dataTypes);
}
+ @JsonIgnore
public Map<ToscaEntityKey, ToscaPolicyType> getPolicyTypesAsMap() {
return ToscaEntity.getEntityMapAsMap(policyTypes);
}
* ============LICENSE_START=======================================================
* ONAP Policy Model
* ================================================================================
- * Copyright (C) 2020 Nordix Foundation.
+ * Copyright (C) 2020,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
*/
@Data
@EqualsAndHashCode
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ToscaServiceTemplates {
- @SerializedName("service_templates")
+ @JsonProperty("service_templates")
private List<ToscaServiceTemplate> serviceTemplates;
}
* ONAP Policy Model
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2020-2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
private Map<String, ToscaParameter> inputs;
- @SerializedName("node_templates")
+ @JsonProperty("node_templates")
private Map<String, ToscaNodeTemplate> nodeTemplates;
private List<Map<String, ToscaPolicy>> policies;
+ @JsonIgnore
public Map<ToscaEntityKey, ToscaPolicy> getPoliciesAsMap() {
return ToscaEntity.getEntityListMapAsMap(policies);
}
/**
* Copy constructor.
*
- * @param copyObject the obejct to copy from.
+ * @param copyObject the object to copy from.
*/
public ToscaTopologyTemplate(@NonNull ToscaTopologyTemplate copyObject) {
this.description = copyObject.description;
* ONAP Policy Model
* ================================================================================
* Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
+ * Modification Copyright (C) 2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Data;
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ToscaWithToscaProperties extends ToscaEntity {
private Map<String, ToscaProperty> properties;
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.models.tosca.authorative.concepts;
-import com.google.gson.annotations.SerializedName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Data;
public class ToscaWithTypeAndObjectProperties extends ToscaEntity {
private String type;
- @SerializedName("type_version")
+ @JsonProperty("type_version")
private String typeVersion;
private Map<String, Object> properties;
*
* @return this policy's identifier
*/
+ @JsonIgnore
public ToscaConceptIdentifier getIdentifier() {
return new ToscaConceptIdentifier(getName(), getVersion());
}
/**
* Gets the type identifier for this policy.
*
- * @return this policy's type identifier
+ * @return this policy's type identifier, or null if type is null
*/
+ @JsonIgnore
public ToscaConceptIdentifier getTypeIdentifier() {
+ if (getType() == null) {
+ return null;
+ }
return new ToscaConceptIdentifier(getType(), getTypeVersion());
}
}
import lombok.Getter;
import org.junit.jupiter.api.Test;
import org.onap.policy.common.parameters.BeanValidator;
-import org.onap.policy.common.utils.coder.CoderException;
-import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfKey;
}
@Test
- void testVerifyKey() throws CoderException {
+ void testVerifyKey() {
FullKeyAnnot data = new FullKeyAnnot();
// null key - Jakarta validation will include all constraint violations
.contains(KEY_FIELD, IS_A_NULL_KEY);
// invalid version - should invoke cascade validation
- data.key = new StandardCoder().decode("{'name':'abc', 'version':'xyzzy'}".replace('\'', '"'),
- PfConceptKey.class);
+
+ // Create object with invalid version using reflection to bypass setter validation
+ data.key = new PfConceptKey("abc", "1.0.0"); // Create with valid version first
+ try {
+ var versionField = PfConceptKey.class.getDeclaredField("version");
+ versionField.setAccessible(true);
+ versionField.set(data.key, "xyzzy"); // Set invalid version directly
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to set invalid version for test", e);
+ }
assertThat(BeanValidator.validate("", data).getResult())
.contains(KEY_FIELD, "version", "xyzzy", "must match");
assertThat(BeanValidator.validate("", data).getResult()).contains(KEY_FIELD, "version", IS_NULL);
// null name, invalid version - should get two messages
- data.key = new StandardCoder().decode("{'name':'NULL', 'version':'xyzzy'}".replace('\'', '"'),
- PfConceptKey.class);
+ // Create object with invalid version using reflection to bypass setter validation
+ data.key = new PfConceptKey("NULL", "1.0.0"); // Create with valid version first
+ try {
+ var versionField = PfConceptKey.class.getDeclaredField("version");
+ versionField.setAccessible(true);
+ versionField.set(data.key, "xyzzy"); // Set invalid version directly
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to set invalid version for test", e);
+ }
assertThat(BeanValidator.validate("", data).getResult())
.contains(KEY_FIELD, "name", IS_NULL, "version", "xyzzy", "must match");
}
* ONAP
* ================================================================================
* Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
+ * Modifications Copyright (C) 2021,2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Map;
import org.junit.jupiter.api.Test;
@Test
void testCopyConstructor() {
ToscaWithTypeAndObjectProperties tosca = new ToscaWithTypeAndObjectProperties();
+ assertNull(tosca.getTypeIdentifier());
assertEquals(tosca, new ToscaWithTypeAndObjectProperties(tosca));
tosca.setProperties(Map.of("abc", 10, "def", "world"));
+ var typeVersion = "1.0.0";
+ var type = "onap.test.element";
+ tosca.setType(type);
+ tosca.setTypeVersion(typeVersion);
assertEquals(tosca, new ToscaWithTypeAndObjectProperties(tosca));
assertNotEquals(tosca, new ToscaWithTypeAndObjectProperties());
assertThatThrownBy(() -> new ToscaWithTypeAndObjectProperties(null)).hasMessageContaining("copyObject")
.hasMessageContaining("is null");
+
+ assertEquals(typeVersion, tosca.getTypeIdentifier().getVersion());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
============LICENSE_START=======================================================
- Copyright (C) 2021-2025 OpenInfra Foundation Europe. All rights reserved.
+ Copyright (C) 2021-2026 OpenInfra Foundation Europe. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
<artifactId>policy-clamp-models</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- </dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
<artifactId>jersey-client</artifactId>
<scope>runtime</scope>
</dependency>
+ <dependency>
+ <groupId>org.glassfish.jersey.media</groupId>
+ <artifactId>jersey-media-json-jackson</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022, 2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2022, 2025-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.clamp.acm.runtime.main.rest.stub;
-import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.onap.policy.common.utils.coder.CoderException;
+import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.coder.StandardYamlCoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final HttpServletRequest request;
private static final StandardYamlCoder YAML_TRANSLATOR = new StandardYamlCoder();
- private static final Gson JSON_TRANSLATOR = new Gson();
+ private static final StandardCoder JSON_TRANSLATOR = new StandardCoder();
private static final String YAML = "application/yaml";
private static final String ACCEPT = "Accept";
return new ResponseEntity<>(targetObject, HttpStatus.OK);
} else {
final var string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
- var targetObject = JSON_TRANSLATOR.fromJson(string, clazz);
+ var targetObject = JSON_TRANSLATOR.decode(string, clazz);
return new ResponseEntity<>(targetObject, HttpStatus.OK);
}
} catch (IOException | CoderException exception) {
final var resource = new ClassPathResource(path);
try (var inputStream = resource.getInputStream()) {
final var string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
- var targetObject = JSON_TRANSLATOR.fromJson(string, ArrayList.class);
+ var targetObject = JSON_TRANSLATOR.decode(string, ArrayList.class);
return new ResponseEntity<>(targetObject, HttpStatus.OK);
- } catch (IOException exception) {
+ } catch (IOException | CoderException exception) {
log.error("Error reading the file.", exception);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2021-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
message.setParticipantIdList(participantIds);
message.setTimestamp(Instant.now());
message.setRevisionIdComposition(revisionId);
- // DeCommission the automation composition but deleting participantdefinitions on participants
- message.setParticipantDefinitionUpdates(null);
LOGGER.debug("Participant Update sent {}", message.getMessageId());
super.send(message);
user:
name: ${RUNTIME_USER}
password: ${RUNTIME_PASSWORD}
- http:
- converters:
- preferred-json-mapper: gson
datasource:
url: jdbc:postgresql://${SQL_HOST:localhost}:${SQL_PORT:5432}/clampacm
driverClassName: org.postgresql.Driver
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2021-2026 OpenInfra Foundation Europe. All rights reserved.
* Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
x.setVersion("1.0.wrong");
serviceTemplateCreate.getToscaTopologyTemplate().getNodeTemplates().put(x.getName(), x);
+
var commissioningResponse = createServiceTemplate(serviceTemplateCreate, Response.Status.INTERNAL_SERVER_ERROR);
assertThat(commissioningResponse.getErrorDetails())
.isEqualTo("java.lang.IllegalArgumentException parameter "
var invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "?name=noResultWithThisName");
try (var rawresp = invocationBuilder.buildGet().invoke()) {
assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus());
- var entityList = rawresp.readEntity(ToscaServiceTemplate.class);
- assertThat(entityList.getNodeTypes()).isNull();
+ var entityList = rawresp.readEntity(ToscaServiceTemplates.class);
+ assertThat(entityList.getServiceTemplates()).isEmpty();
}
}
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2024 Nordix Foundation.
+ * Copyright (C) 2021-2024,2026 OpenInfra Foundation Europe. All rights reserved.
* Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
verify(publisherFirst, times(1)).active(any());
verify(publisherSecond, times(1)).active(any());
- var sco = CODER.decode("{messageType:" + TOPIC_FIRST + "}", StandardCoderObject.class);
+ var sco = CODER.decode("{\"messageType\":\"" + TOPIC_FIRST + "\"}", StandardCoderObject.class);
activator.getMsgDispatcher().onTopicEvent(null, "msg", sco);
verify(listenerFirst, times(1)).onTopicEvent(any(), any(), any());
- sco = CODER.decode("{messageType:" + TOPIC_SECOND + "}", StandardCoderObject.class);
+ sco = CODER.decode("{\"messageType\":\"" + TOPIC_SECOND + "\"}", StandardCoderObject.class);
activator.getMsgDispatcher().onTopicEvent(null, "msg", sco);
verify(listenerSecond, times(1)).onTopicEvent(any(), any(), any());
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2022-2023, 2025 OpenInfra Foundation Europe. All rights reserved.
+ * Copyright (C) 2022-2023, 2025-2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.Response;
+import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@Test
void testPost() {
+ var ac = new AutomationComposition();
+ ac.setCompositionId(UUID.randomUUID());
var invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT
+ "/" + COMPOSITION_ID
+ "/" + INSTANTIATION_ENDPOINT);
- var respPost = invocationBuilder.post(Entity.json(new AutomationComposition()));
- assertThat(Response.Status.OK.getStatusCode()).isEqualTo(respPost.getStatus());
+ var respPost = invocationBuilder.post(Entity.json(ac));
+ assertThat(respPost.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
respPost.close();
}
class ActuatorControllerTest {
public static final String HEALTH = "/actuator/health";
- public static final String STATUS_CODE = "$.status.code";
+ public static final String STATUS_CODE = "$.status";
@Autowired
private WebTestClient webClient;
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2024 Nordix Foundation.
+ * Copyright (C) 2021-2024,2026 OpenInfra Foundation Europe. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import jakarta.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
-import org.onap.policy.common.gson.GsonMessageBodyHandler;
+import org.glassfish.jersey.jackson.JacksonFeature;
import org.onap.policy.common.utils.network.NetworkUtil;
/**
client = ClientBuilder.newBuilder().build();
client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
- client.register(GsonMessageBodyHandler.class);
+ client.register(JacksonFeature.class);
if (includeAuth) {
client.register(HttpAuthenticationFeature.basic("runtimeUser", "zb!XztG34"));