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

io.camunda.connector.slack.utils.SlackRequestDeserializer Maven / Gradle / Ivy

There is a newer version: 8.7.0-alpha2.1
Show newest version
/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. Licensed under a proprietary license.
 * See the License.txt file for more information. You may not use this file
 * except in compliance with the proprietary license.
 */
package io.camunda.connector.slack.utils;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import io.camunda.connector.slack.SlackRequest;
import io.camunda.connector.slack.SlackRequestData;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class SlackRequestDeserializer
    implements JsonDeserializer> {

  private String typeElementName;
  private Gson gson;
  private Map> typeRegistry;

  public SlackRequestDeserializer(String typeElementName) {
    this.typeElementName = typeElementName;
    this.gson = new Gson();
    this.typeRegistry = new HashMap<>();
  }

  public SlackRequestDeserializer registerType(
      String typeName, Class requestType) {
    typeRegistry.put(typeName, requestType);
    return this;
  }

  @Override
  public SlackRequest deserialize(
      JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
      throws JsonParseException {
    return getTypeElementValue(jsonElement)
        .map(typeRegistry::get)
        .map(SlackRequestDeserializer::getTypeToken)
        .map(typeToken -> getSlackRequest(jsonElement, typeToken))
        .orElse(null);
  }

  private Optional getTypeElementValue(JsonElement jsonElement) {
    JsonObject asJsonObject = jsonElement.getAsJsonObject();
    JsonElement element = asJsonObject.get(typeElementName);
    return Optional.ofNullable(element).map(JsonElement::getAsString);
  }

  private static TypeToken> getTypeToken(
      Class requestDataClass) {
    return (TypeToken>)
        TypeToken.getParameterized(SlackRequest.class, requestDataClass);
  }

  private SlackRequest getSlackRequest(
      JsonElement jsonElement, TypeToken> typeToken) {
    return gson.fromJson(jsonElement, typeToken.getType());
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy