
de.dentrassi.asyncapi.gson.GsonPayloadFormat Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of asyncapi-gson Show documentation
Show all versions of asyncapi-gson Show documentation
AsyncAPI GSON payload support
The newest version!
/*
* Copyright (C) 2017 Jens Reimann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.dentrassi.asyncapi.gson;
import java.io.Serializable;
import java.util.Objects;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import de.dentrassi.asyncapi.Message;
import de.dentrassi.asyncapi.format.TextPayloadFormat;
import de.dentrassi.asyncapi.gson.time.DateTimeAdapterFactory;
import de.dentrassi.asyncapi.gson.time.DateTimeStrategy;
public class GsonPayloadFormat implements TextPayloadFormat {
private static final Logger logger = LoggerFactory.getLogger(GsonPayloadFormat.class);
private final Gson gson;
public GsonPayloadFormat() {
this((Consumer) null);
}
public GsonPayloadFormat(final Consumer customizer) {
this(DateTimeStrategy.ISO_8601_UTC, customizer);
}
public GsonPayloadFormat(final DateTimeStrategy dateTimeStrategy) {
this(dateTimeStrategy, null);
}
public GsonPayloadFormat(final DateTimeStrategy dateTimeStrategy, final Consumer customizer) {
Objects.requireNonNull(dateTimeStrategy);
final GsonBuilder builder = new GsonBuilder();
switch (dateTimeStrategy) {
case ISO_8601_UTC:
DateTimeAdapterFactory.iso8601().accept(builder);
break;
case ISO_8601_ZONED:
DateTimeAdapterFactory.iso8601WithTimezone().accept(builder);
break;
default:
throw new IllegalArgumentException("Unknown date time strategy: " + dateTimeStrategy);
}
if (customizer != null) {
customizer.accept(builder);
}
this.gson = builder.create();
}
public GsonPayloadFormat(final GsonBuilder builder) {
this.gson = builder.create();
}
@Override
public String encode(final Message> message) throws Exception {
return this.gson.toJson(message.getPayload());
}
@Override
public , P extends Serializable> M decode(final Class clazz, final Class payloadClazz, final String message) throws Exception {
logger.debug("Decoding JSON: {}", message);
final M m = clazz.newInstance();
m.setPayload(this.gson.fromJson(message, payloadClazz));
return m;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy