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

net.anwiba.commons.json.AbstractJsonUnmarshaller Maven / Gradle / Ivy

/*
 * #%L anwiba commons advanced %% Copyright (C) 2007 - 2016 Andreas Bartels %% This program is free
 * software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation, either version 2.1 of the License,
 * or (at your option) any later version. This program is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Lesser Public License for more details. You should
 * have received a copy of the GNU General Lesser Public License along with this program. If not,
 * see . #L%
 */
package net.anwiba.commons.json;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.anwiba.commons.lang.io.NoneClosingInputStream;

public abstract class AbstractJsonUnmarshaller {

  private final ObjectMapper mapper = new ObjectMapper();
  private final Class errorResponseClass;
  private final Class clazz;
  private final Map injectionValues = new HashMap<>();

  public AbstractJsonUnmarshaller(
      final Class clazz,
      final Class errorResponseClass,
      final Map injectionValues) {
    this.clazz = clazz;
    this.errorResponseClass = errorResponseClass;
    this.injectionValues.putAll(injectionValues);
    this.mapper.getFactory().configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
  }

  public final O unmarshal(final String body) throws IOException, E {
    return unmarshal(new ByteArrayInputStream(body.getBytes(Charset.forName("UTF-8")))); //$NON-NLS-1$
  }

  @SuppressWarnings("resource")
  public final O unmarshal(final InputStream inputStream) throws IOException, E {
    return _unmarshal(
        new NoneClosingInputStream(
            inputStream instanceof BufferedInputStream
                ? (BufferedInputStream) inputStream
                : new BufferedInputStream(inputStream)));
  }

  protected abstract O _unmarshal(final InputStream inputStream) throws IOException, E;

  private String toString(final InputStream inputStream, final String contentEncoding) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final byte[] buffer = new byte[4096];
    int numChars;
    while ((numChars = inputStream.read(buffer)) > 0) {
      out.write(buffer, 0, numChars);
    }
    final String string = out.toString(contentEncoding);
    return string.length() > 8200 ? string.substring(0, 8200) + "..." : string; //$NON-NLS-1$
  }

  private  X check(final InputStream stream, final Class type)
      throws IOException,
      JsonParseException,
      JsonMappingException,
      JsonProcessingException {
    final InjectableValues.Std injectableValues = new InjectableValues.Std();
    for (final String key : this.injectionValues.keySet()) {
      injectableValues.addValue(key, this.injectionValues.get(key));
    }
    return this.mapper.readerFor(type).with(injectableValues).readValue(stream);
  }

  @SuppressWarnings("unchecked")
  protected T validate(final InputStream stream) throws IOException, E {
    if (Void.class.equals(this.errorResponseClass)) {
      return null;
    }
    try {
      final R response = check(stream, this.errorResponseClass);
      if (this.clazz.isInstance(response)) {
        return (T) response;
      }
      throw createException(response);
    } catch (final JsonParseException e) {
      return null;
    } catch (final JsonMappingException e) {
      return null;
    }
  }

  protected abstract E createException(R response);

  protected IOException createIOException(final InputStream content, final Exception exception) {
    try {
      return new IOException(
          MessageFormat.format(
              "Error during mapping json resource, coudn''t map the content:\n {0}", //$NON-NLS-1$
              toString(content, "UTF-8")), //$NON-NLS-1$
          exception);
    } catch (final IOException exception1) {
      return new IOException(
          "Error during mapping json resource, coudn''t map the content", //$NON-NLS-1$
          exception);
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy