Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind;
  
  import java.util.*;
  
Checked exception used to signal fatal problems with mapping of content.

One additional feature is the ability to denote relevant path of references (during serialization/deserialization) to help in troubleshooting.

 
 public class JsonMappingException
     extends JsonProcessingException
 {
     private static final long serialVersionUID = 1L;

    
Let's limit length of reference chain, to limit damage in cases of infinite recursion.
 
     final static int MAX_REFS_TO_LIST = 1000;
 
     /*
     /**********************************************************
     /* Helper classes
     /**********************************************************
      */

    
Simple bean class used to contain references. References can be added to indicate execution/reference path that lead to the problem that caused this exception to be thrown.
 
     public static class Reference implements Serializable
     {
         private static final long serialVersionUID = 1L;

        
Object through which reference was resolved. Can be either actual instance (usually the case for serialization), or Class (usually the case for deserialization).
 
         protected Object _from;

        
Name of field (for beans) or key (for Maps) that is part of the reference. May be null for Collection types (which generally have _index defined), or when resolving Map classes without (yet) having an instance to operate on.
 
         protected String _fieldName;

        
Index within a java.util.Collection instance that contained the reference; used if index is relevant and available. If either not applicable, or not available, -1 is used to denote "not known".
 
         protected int _index = -1;

        
Default constructor for deserialization/sub-classing purposes
 
         protected Reference() { }
 
         public Reference(Object from) {  = from; }
 
         public Reference(Object fromString fieldName) {
              = from;
             if (fieldName == null) {
                 throw new NullPointerException("Can not pass null fieldName");
             }
              = fieldName;
         }
 
         public Reference(Object fromint index) {
              = from;
              = index;
         }
 
         public void setFrom(Object o) {  = o; }
         public void setFieldName(String n) {  = n; }
         public void setIndex(int ix) {  = ix; }
 
         public Object getFrom() { return ; }
         public String getFieldName() { return ; }
         public int getIndex() { return ; }
 
         @Override public String toString() {
             StringBuilder sb = new StringBuilder();
             Class<?> cls = ( instanceof Class<?>) ?
                 ((Class<?>)) : .getClass();
             /* Hmmh. Although Class.getName() is mostly ok, it does look
             * butt-ugly for arrays. So let's use getSimpleName() instead;
             * but have to prepend package name too.
             */
            Package pkg = cls.getPackage();
            if (pkg != null) {
                sb.append(pkg.getName());
                sb.append('.');
            }
            sb.append(cls.getSimpleName());
            sb.append('[');
            if ( != null) {
                sb.append('"');
                sb.append();
                sb.append('"');
            } else if ( >= 0) {
                sb.append();
            } else {
                sb.append('?');
            }
            sb.append(']');
            return sb.toString();
        }
    }
    /*
    /**********************************************************
    /* State/configuration
    /**********************************************************
     */

    
Path through which problem that triggering throwing of this exception was reached.
    protected LinkedList<Reference_path;
    /*
    /**********************************************************
    /* Life-cycle
    /**********************************************************
     */
    public JsonMappingException(String msg)
    {
        super(msg);
    }
    public JsonMappingException(String msgThrowable rootCause)
    {
        super(msgrootCause);
    }
    public JsonMappingException(String msgJsonLocation loc)
    {
        super(msgloc);
    }
    public JsonMappingException(String msgJsonLocation locThrowable rootCause)
    {
        super(msglocrootCause);
    }
    public static JsonMappingException from(JsonParser jpString msg)
    {
        return new JsonMappingException(msg, ((jp == null) ? null : jp.getTokenLocation()));
    }
    public static JsonMappingException from(JsonParser jpString msg,
            Throwable problem)
    {
        return new JsonMappingException(msg, ((jp == null) ? null : jp.getTokenLocation()), problem);
    }
    
    
Factory method used when "upgrading" an java.io.IOException into JsonMappingException: usually only needed to comply with a signature.

Since:
2.1
    {
        return new JsonMappingException("Unexpected IOException (of type "
                +src.getClass().getName()+"): "+src.getMessage(), (JsonLocation)nullsrc);
    }
    
    
Method that can be called to either create a new JsonMappingException (if underlying exception is not a JsonMappingException), or augment given exception with given path/reference information. This version of method is called when the reference is through a non-indexed object, such as a Map or POJO/bean.
    public static JsonMappingException wrapWithPath(Throwable srcObject refFrom,
                                                    String refFieldName)
    {
        return wrapWithPath(srcnew Reference(refFromrefFieldName));
    }

    
Method that can be called to either create a new JsonMappingException (if underlying exception is not a JsonMappingException), or augment given exception with given path/reference information. This version of method is called when the reference is through an index, which happens with arrays and Collections.
    public static JsonMappingException wrapWithPath(Throwable srcObject refFrom,
                                                    int index)
    {
        return wrapWithPath(srcnew Reference(refFromindex));
    }

    
Method that can be called to either create a new JsonMappingException (if underlying exception is not a JsonMappingException), or augment given exception with given path/reference information.
    public static JsonMappingException wrapWithPath(Throwable srcReference ref)
    {
        JsonMappingException jme;
        if (src instanceof JsonMappingException) {
            jme = (JsonMappingExceptionsrc;
        } else {
            String msg = src.getMessage();
            /* Related to [JACKSON-62], let's use a more meaningful placeholder
             * if all we have is null
             */
            if (msg == null || msg.length() == 0) {
                msg = "(was "+src.getClass().getName()+")";
            }
            jme = new JsonMappingException(msgnullsrc);
        }
        jme.prependPath(ref);
        return jme;
    }
    
    /*
    /**********************************************************
    /* Accessors/mutators
    /**********************************************************
     */

    
Method for accessing full structural path within type hierarchy down to problematic property.
    public List<ReferencegetPath()
    {
        if ( == null) {
            return Collections.emptyList();
        }
        return Collections.unmodifiableList();
    }

    
Method for accesing description of path that lead to the problem that triggered this exception
    public String getPathReference()
    {
        return getPathReference(new StringBuilder()).toString();
    }
    {
        _appendPathDesc(sb);
        return sb;
    }
    
    
Method called to prepend a reference information in front of current path
    public void prependPath(Object referrerString fieldName)
    {
        Reference ref = new Reference(referrerfieldName);
        prependPath(ref);
    }
    
Method called to prepend a reference information in front of current path
    public void prependPath(Object referrerint index)
    {
        Reference ref = new Reference(referrerindex);
        prependPath(ref);
    }
    public void prependPath(Reference r)
    {
        if ( == null) {
             = new LinkedList<Reference>();
        }
        /* Also: let's not increase without bounds. Could choose either
         * head or tail; tail is easier (no need to ever remove), as
         * well as potentially more useful so let's use it:
         */
        if (.size() < ) {
            .addFirst(r);
        }
    }
    
    /*
    /**********************************************************
    /* Overridden methods
    /**********************************************************
     */
    @Override
    public String getLocalizedMessage() {
        return _buildMessage();
    }
    
    
Method is overridden so that we can properly inject description of problem path, if such is defined.
    @Override
    public String getMessage() {
        return _buildMessage();
    }
    protected String _buildMessage()
    {
        /* First: if we have no path info, let's just use parent's
         * definition as is
         */
        String msg = super.getMessage();
        if ( == null) {
            return msg;
        }
        StringBuilder sb = (msg == null) ? new StringBuilder() : new StringBuilder(msg);
        /* 18-Feb-2009, tatu: initially there was a linefeed between
         *    message and path reference; but unfortunately many systems
         *   (loggers, junit) seem to assume linefeeds are only added to
         *   separate stack trace.
         */
        sb.append(" (through reference chain: ");
        sb = getPathReference(sb);
        sb.append(')');
        return sb.toString();
    }
    @Override
    public String toString()
    {
        return getClass().getName()+": "+getMessage();
    }
    /*
    /**********************************************************
    /* Internal methods
    /**********************************************************
     */
    protected void _appendPathDesc(StringBuilder sb)
    {
        if ( == null) {
            return;
        }
        Iterator<Referenceit = .iterator();
        while (it.hasNext()) {
            sb.append(it.next().toString());
            if (it.hasNext()) {
                sb.append("->");
            }
        }
    }
New to GrepCode? Check out our FAQ X