Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind.deser;
  
  
 
Alternative to com.fasterxml.jackson.core.format.DataFormatDetector that needs to be used when using data-binding.

Since:
2.1
 
 public class DataFormatReaders
 {
    
By default we will look ahead at most 64 bytes; in most cases, much less (4 bytes or so) is needed, but we will allow bit more leniency to support data formats that need more complex heuristics.
 
     public final static int DEFAULT_MAX_INPUT_LOOKAHEAD = 64;
    
    
Ordered list of readers which both represent data formats to detect (in precedence order, starting with highest) and contain factories used for actual detection.
 
     protected final ObjectReader[] _readers;

    
Strength of match we consider to be good enough to be used without checking any other formats. Default value is com.fasterxml.jackson.core.format.MatchStrength.SOLID_MATCH,
 
     protected final MatchStrength _optimalMatch;

    
Strength of minimal match we accept as the answer, unless better matches are found. Default value is com.fasterxml.jackson.core.format.MatchStrength.WEAK_MATCH,
 
     protected final MatchStrength _minimalMatch;

    
Maximum number of leading bytes of the input that we can read to determine data format.

Default value is DEFAULT_MAX_INPUT_LOOKAHEAD.

 
     protected final int _maxInputLookahead;
     
     /*
     /**********************************************************
     /* Construction
     /**********************************************************
      */
     
     public DataFormatReaders(ObjectReader... detectors) {
         this(detectors..,
             );
     }
 
     public DataFormatReaders(Collection<ObjectReaderdetectors) {
         this(detectors.toArray(new ObjectReader[detectors.size()]));
     }
 
     private DataFormatReaders(ObjectReader[] detectors,
             MatchStrength optMatchMatchStrength minMatch,
             int maxInputLookahead)
     {
          = detectors;
          = optMatch;
          = minMatch;
          = maxInputLookahead;
     }
     
     /*
     /**********************************************************
     /* Fluent factories for changing match settings
     /**********************************************************
      */
     
     public DataFormatReaders withOptimalMatch(MatchStrength optMatch) {
         if (optMatch == ) {
             return this;
         }
         return new DataFormatReaders(optMatch);
     }
 
     public DataFormatReaders withMinimalMatch(MatchStrength minMatch) {
         if (minMatch == ) {
             return this;
         }
        return new DataFormatReaders(minMatch);
    }
    public DataFormatReaders with(ObjectReader[] readers) {
        return new DataFormatReaders(readers);
    }
    
    public DataFormatReaders withMaxInputLookahead(int lookaheadBytes)
    {
        if (lookaheadBytes == ) {
            return this;
        }
        return new DataFormatReaders(lookaheadBytes);
    }
    /*
    /**********************************************************
    /* Fluent factories for changing underlying readers
    /**********************************************************
     */
    {
        final int len = .;
        ObjectReader[] r = new ObjectReader[len];
        for (int i = 0; i < len; ++i) {
            r[i] = [i].with(config);
        }
    }
    public DataFormatReaders withType(JavaType type)
    {
        final int len = .;
        ObjectReader[] r = new ObjectReader[len];
        for (int i = 0; i < len; ++i) {
            r[i] = [i].withType(type);
        }
    }
    
    /*
    /**********************************************************
    /* Public API
    /**********************************************************
     */

    
Method to call to find format that content (accessible via given java.io.InputStream) given has, as per configuration of this detector instance.

Returns:
Matcher object which contains result; never null, even in cases where no match (with specified minimal match strength) is found.
    public Match findFormat(InputStream inthrows IOException
    {
        return _findFormat(new AccessorForReader(innew byte[]));
    }

    
Method to call to find format that given content (full document) has, as per configuration of this detector instance.

Returns:
Matcher object which contains result; never null, even in cases where no match (with specified minimal match strength) is found.
    public Match findFormat(byte[] fullInputDatathrows IOException
    {
        return _findFormat(new AccessorForReader(fullInputData));
    }

    
Method to call to find format that given content (full document) has, as per configuration of this detector instance.

Returns:
Matcher object which contains result; never null, even in cases where no match (with specified minimal match strength) is found.
Since:
2.1
    public Match findFormat(byte[] fullInputDataint offsetint lenthrows IOException
    {
        return _findFormat(new AccessorForReader(fullInputDataoffsetlen));
    }
    
    /*
    /**********************************************************
    /* Overrides
    /**********************************************************
     */
    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        final int len = .;
        if (len > 0) {
            sb.append([0].getFactory().getFormatName());
            for (int i = 1; i < len; ++i) {
                sb.append(", ");
                sb.append([i].getFactory().getFormatName());
            }
        }
        sb.append(']');
        return sb.toString();
    }
    
    /*
    /**********************************************************
    /* Internal methods
    /**********************************************************
     */
    private Match _findFormat(AccessorForReader accthrows IOException
    {
        ObjectReader bestMatch = null;
        MatchStrength bestMatchStrength = null;
        for (ObjectReader f : ) {
            acc.reset();
            MatchStrength strength = f.getFactory().hasFormat(acc);
            // if not better than what we have so far (including minimal level limit), skip
            if (strength == null || strength.ordinal() < .ordinal()) {
                continue;
            }
            // also, needs to better match than before
            if (bestMatch != null) {
                if (bestMatchStrength.ordinal() >= strength.ordinal()) {
                    continue;
                }
            }
            // finally: if it's good enough match, we are done
            bestMatch = f;
            bestMatchStrength = strength;
            if (strength.ordinal() >= .ordinal()) {
                break;
            }
        }
        return acc.createMatcher(bestMatchbestMatchStrength);
    }
    /*
    /**********************************************************
    /* Helper classes
    /**********************************************************
     */

    
We need sub-class here as well, to be able to access efficiently.
    protected class AccessorForReader extends InputAccessor.Std
    {
        public AccessorForReader(InputStream inbyte[] buffer) {
            super(inbuffer);
        }
        public AccessorForReader(byte[] inputDocument) {
            super(inputDocument);
        }
        public AccessorForReader(byte[] inputDocumentint startint len) {
            super(inputDocumentstartlen);
        }
        public Match createMatcher(ObjectReader matchMatchStrength matchStrength)
        {
            return new Match(, ( - ),
                    matchmatchStrength);
        }
    }
    
    
    public static class Match
    {
        protected final InputStream _originalStream;

        
Content read during format matching process
        protected final byte[] _bufferedData;

        
Pointer to the first byte in buffer available for reading
        protected final int _bufferedStart;
        
        
Number of bytes available in buffer.
        protected final int _bufferedLength;

        
Factory that produced sufficient match (if any)
        protected final ObjectReader _match;

        
Strength of match with _match
        protected final MatchStrength _matchStrength;
        
        protected Match(InputStream inbyte[] buffered,
                int bufferedStartint bufferedLength,
                ObjectReader matchMatchStrength strength)
        {
             = in;
             = buffered;
             = bufferedStart;
             = bufferedLength;
             = match;
             = strength;
        }
        /*
        /**********************************************************
        /* Public API, simple accessors
        /**********************************************************
         */

        
Accessor to use to see if any formats matched well enough with the input data.
        public boolean hasMatch() { return  != null; }

        
Method for accessing strength of the match, if any; if no match, will return com.fasterxml.jackson.core.format.MatchStrength.INCONCLUSIVE.
        public MatchStrength getMatchStrength() {
            return ( == null) ? . : ;
        }

        
Accessor for com.fasterxml.jackson.core.JsonFactory that represents format that data matched.
        public ObjectReader getReader() { return ; }

        
Accessor for getting brief textual name of matched format if any (null if none). Equivalent to:
   return hasMatch() ? getMatch().getFormatName() : null;
        public String getMatchedFormatName() {
            return .getFactory().getFormatName();
        }
        
        /*
        /**********************************************************
        /* Public API, factory methods
        /**********************************************************
         */
        
        
Convenience method for trying to construct a com.fasterxml.jackson.core.JsonParser for parsing content which is assumed to be in detected data format. If no match was found, returns null.
        public JsonParser createParserWithMatch() throws IOException
        {
            if ( == null) {
                return null;
            }
            JsonFactory jf = .getFactory();
            if ( == null) {
                return jf.createParser();
            }
            return jf.createParser(getDataStream());
        }
        
        
Method to use for accessing input for which format detection has been done. This must be used instead of using stream passed to detector unless given stream itself can do buffering. Stream will return all content that was read during matching process, as well as remaining contents of the underlying stream.
        public InputStream getDataStream() {
            if ( == null) {
                return new ByteArrayInputStream();
            }
            return new MergedStream(null);
        }        
    }
    
New to GrepCode? Check out our FAQ X