idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
123,600
public static String encodeQ ( byte [ ] bytes , Usage usage ) { BitSet qChars = usage == Usage . TEXT_TOKEN ? Q_REGULAR_CHARS : Q_RESTRICTED_CHARS ; StringBuilder sb = new StringBuilder ( ) ; final int end = bytes . length ; for ( int idx = 0 ; idx < end ; idx ++ ) { int v = bytes [ idx ] & 0xff ; if ( v == 32 ) { sb ....
Encodes the specified byte array using the Q encoding defined in RFC 2047 .
123,601
public static boolean isToken ( String str ) { final int length = str . length ( ) ; if ( length == 0 ) return false ; for ( int idx = 0 ; idx < length ; idx ++ ) { char ch = str . charAt ( idx ) ; if ( ! TOKEN_CHARS . get ( ch ) ) return false ; } return true ; }
Tests whether the specified string is a token as defined in RFC 2045 section 5 . 1 .
123,602
private static boolean isDotAtomText ( String str ) { char prev = '.' ; final int length = str . length ( ) ; if ( length == 0 ) return false ; for ( int idx = 0 ; idx < length ; idx ++ ) { char ch = str . charAt ( idx ) ; if ( ch == '.' ) { if ( prev == '.' || idx == length - 1 ) return false ; } else { if ( ! ATEXT_C...
RFC 5322 section 3 . 2 . 3
123,603
public Resty setOptions ( Option ... someOptions ) { options = ( someOptions == null ) ? new Option [ 0 ] : someOptions ; for ( Option o : options ) { o . init ( this ) ; } return this ; }
Set options if you missed your opportunity in the c tor or if you want to change the options .
123,604
public void authenticate ( URI aSite , String aLogin , char [ ] aPwd ) { rath . addSite ( aSite , aLogin , aPwd ) ; }
Register this root URI for authentication . Whenever a URL is requested that starts with this root the credentials given are used for HTTP AUTH . Note that currently authentication information is shared across all Resty instances . This is due to the shortcomings of the java . net authentication mechanism . This might ...
123,605
public void authenticateForRealm ( String realm , String aLogin , char [ ] charArray ) { rath . addRealm ( realm , aLogin , charArray ) ; }
Register a login password for the realm returned by the authorization challenge . Use this method instead of authenticate in case the URL is not made available to the java . net . Authenticator class
123,606
public JSONResource json ( URI anUri , AbstractContent requestContent ) throws IOException { return doPOSTOrPUT ( anUri , requestContent , createJSONResource ( ) ) ; }
POST to a URI and parse the result as JSON
123,607
public XMLResource xml ( URI anUri , AbstractContent requestContent ) throws IOException { return doPOSTOrPUT ( anUri , requestContent , createXMLResource ( ) ) ; }
POST to a URI and parse the result as XML
123,608
protected void addAdditionalHeaders ( URLConnection con ) { for ( Map . Entry < String , String > header : getAdditionalHeaders ( ) . entrySet ( ) ) { con . addRequestProperty ( header . getKey ( ) , header . getValue ( ) ) ; } }
Add all headers that have been set with the alwaysSend call .
123,609
protected < T extends AbstractResource > T fillResourceFromURL ( URLConnection con , T resource ) throws IOException { resource . fill ( con ) ; resource . getAdditionalHeaders ( ) . putAll ( getAdditionalHeaders ( ) ) ; return resource ; }
Get the content from the URLConnection create a Resource representing the content and carry over some metadata like HTTP Result and location header .
123,610
public static Content content ( JSONObject someJson ) { Content c = null ; try { c = new Content ( "application/json; charset=UTF-8" , someJson . toString ( ) . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { } return c ; }
Create a content object from a JSON object . Use this to POST the content to a URL .
123,611
public static Content content ( String somePlainText ) { Content c = null ; try { c = new Content ( "text/plain; charset=UTF-8" , somePlainText . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { } return c ; }
Create a content object from plain text . Use this to POST the content to a URL .
123,612
public static String enc ( String unencodedString ) { try { return URLEncoder . encode ( unencodedString , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { } return null ; }
Shortcut to URLEncoder . encode with UTF - 8 .
123,613
public Document doc ( ) throws IOException { InputSource is ; if ( document == null ) { if ( text == null ) { is = new InputSource ( inputStream ) ; is . setEncoding ( getCharSet ( ) . name ( ) ) ; } else { is = new InputSource ( new StringReader ( text ) ) ; } try { document = DocumentBuilderFactory . newInstance ( ) ...
Return the DOM of the XML resource .
123,614
public JSONResource json ( XPathQuery path ) throws Exception { String uri = path . eval ( this , String . class ) ; return json ( uri ) ; }
Execute the given path query on the XML GET the returned URI expecting JSON as content
123,615
public XMLResource xml ( XPathQuery path , Content aContent ) throws Exception { String uri = path . eval ( this , String . class ) ; return xml ( uri , aContent ) ; }
Execute the given path query on the XML POST the returned URI expecting XML
123,616
public NodeList get ( String xPath ) throws Exception { XPathQuery xp = new XPathQuery ( xPath ) ; return xp . eval ( this ) ; }
Access the XML evaluating an XPath on it returning the resulting NodeList .
123,617
public < T > T get ( String xPath , Class < T > returnType ) throws Exception { XPathQuery xp = new XPathQuery ( xPath ) ; return xp . eval ( this , returnType ) ; }
Access the XML evaluating an XPath on it returning the resulting Object of the desired type Supported types are NodeList String Boolean Double Node .
123,618
public void addSite ( URI aRootUrl , String login , char [ ] pwd ) { String rootUri = aRootUrl . normalize ( ) . toString ( ) ; boolean replaced = false ; for ( Site site : sites ) { if ( site . root . equals ( rootUri ) ) { site . login = login ; site . pwd = pwd ; replaced = true ; break ; } } if ( ! replaced ) { Sit...
Add or replace an authentication for a root URL aka site .
123,619
public boolean status ( int responseCode ) { if ( urlConnection instanceof HttpURLConnection ) { HttpURLConnection http = ( HttpURLConnection ) urlConnection ; try { return http . getResponseCode ( ) == responseCode ; } catch ( IOException e ) { e . printStackTrace ( ) ; return false ; } } else return false ; }
Check if the URLConnection has returned the specified responseCode
123,620
public URI location ( ) { String loc = http ( ) . getHeaderField ( "Location" ) ; if ( loc != null ) { return URI . create ( loc ) ; } return null ; }
Get the location header as URI . Returns null if there is no location header .
123,621
public String printResponseHeaders ( ) { StringBuilder sb = new StringBuilder ( ) ; HttpURLConnection http = http ( ) ; if ( http != null ) { Map < String , List < String > > header = http . getHeaderFields ( ) ; for ( String key : header . keySet ( ) ) { for ( String val : header . get ( key ) ) { sb . append ( key ) ...
Print out the response headers for this resource .
123,622
public File save ( File aFileName ) throws IOException { BufferedOutputStream bos = new BufferedOutputStream ( new FileOutputStream ( aFileName ) , 1024 ) ; byte [ ] buffer = new byte [ 1024 ] ; int len = - 1 ; while ( ( len = inputStream . read ( buffer ) ) != - 1 ) { bos . write ( buffer , 0 , len ) ; } bos . close (...
Save the contents of the resource to a file . This reads the data from the stream and stores it into the given file . Depending on the resource the data might or might not be available afterwards .
123,623
protected Charset getCharSet ( ) { String contentType = urlConnection . getContentType ( ) ; Charset charset = Charset . forName ( "iso-8859-1" ) ; if ( contentType != null ) { Matcher m = charsetPattern . matcher ( contentType ) ; if ( m . find ( ) ) { String charsetString = m . group ( 1 ) ; try { charset = Charset ....
Get charset for this content type . Parses charset = attribute of content type or falls back to a default
123,624
private final String getOperationText ( final BinaryOperation exp ) { final String text ; if ( exp instanceof AdditionOperation ) { text = " + " ; } else if ( exp instanceof SubtractionOperation ) { text = " - " ; } else if ( exp instanceof MultiplicationOperation ) { text = " * " ; } else if ( exp instanceof DivisionO...
Returns the text value of the received operation .
123,625
private final V process ( final Iterable < DiceNotationExpression > nodes ) { accumulator . reset ( ) ; for ( final DiceNotationExpression current : nodes ) { if ( current instanceof BinaryOperation ) { accumulator . binaryOperation ( ( BinaryOperation ) current ) ; } else if ( current instanceof ConstantOperand ) { ac...
Returns the result from applying the accumulator in all the nodes .
123,626
private final IntegerOperand getIntegerOperand ( final String expression ) { final Integer value ; value = Integer . parseInt ( expression ) ; return new IntegerOperand ( value ) ; }
Creates an integer operand from the parsed expression .
123,627
private final DiceNotationExpression unwrap ( final DiceNotationExpression expression ) { final DiceNotationExpression result ; if ( expression instanceof ExpressionWrapper ) { result = ( ( ExpressionWrapper ) expression ) . getWrappedExpression ( ) ; } else { result = expression ; } return result ; }
Removes the expression wrappers used to temporally prune the nodes .
123,628
public synchronized void setPollingInterval ( final long pollingInterval ) { if ( pollingInterval <= 0 ) { throw new IllegalArgumentException ( "'pollingInterval' must be greater than 0" ) ; } currentPollingInterval = pollingInterval ; if ( listeners . size ( ) > 0 ) { stop ( ) ; start ( ) ; } }
Sets the polling interval
123,629
private void updateConnectedDevices ( final List < USBStorageDevice > currentConnectedDevices ) { final List < USBStorageDevice > removedDevices = new ArrayList < > ( ) ; synchronized ( this ) { final Iterator < USBStorageDevice > itConnectedDevices = connectedDevices . iterator ( ) ; while ( itConnectedDevices . hasNe...
Updates the internal state of this manager and sends
123,630
public boolean isMisspelled ( final String word ) { String wordToCheck = word ; if ( ! dictionaryMetadata . getInputConversionPairs ( ) . isEmpty ( ) ) { wordToCheck = DictionaryLookup . applyReplacements ( word , dictionaryMetadata . getInputConversionPairs ( ) ) ; } boolean isAlphabetic = wordToCheck . length ( ) != ...
Checks whether the word is misspelled by performing a series of checks according to properties of the dictionary .
123,631
public boolean isInDictionary ( final CharSequence word ) { try { byteBuffer = charSequenceToBytes ( word ) ; } catch ( UnmappableInputException e ) { return false ; } final MatchResult match = matcher . match ( matchResult , byteBuffer . array ( ) , 0 , byteBuffer . remaining ( ) , rootNode ) ; if ( containsSeparators...
Test whether the word is found in the dictionary .
123,632
public int getFrequency ( final CharSequence word ) { if ( ! dictionaryMetadata . isFrequencyIncluded ( ) ) { return 0 ; } final byte separator = dictionaryMetadata . getSeparator ( ) ; try { byteBuffer = charSequenceToBytes ( word ) ; } catch ( UnmappableInputException e ) { return 0 ; } final MatchResult match = matc...
Get the frequency value for a word form . It is taken from the first entry with this word form .
123,633
public List < String > replaceRunOnWords ( final String original ) { final List < String > candidates = new ArrayList < String > ( ) ; String wordToCheck = original ; if ( ! dictionaryMetadata . getInputConversionPairs ( ) . isEmpty ( ) ) { wordToCheck = DictionaryLookup . applyReplacements ( original , dictionaryMetad...
Propose suggestions for misspelled run - on words . This algorithm is inspired by spell . cc in s_fsa package by Jan Daciuk .
123,634
public ArrayList < String > findReplacements ( String word ) { final List < CandidateData > result = findReplacementCandidates ( word ) ; final ArrayList < String > resultSuggestions = new ArrayList < String > ( result . size ( ) ) ; for ( CandidateData cd : result ) { resultSuggestions . add ( cd . getWord ( ) ) ; } r...
Find suggestions by using K . Oflazer s algorithm . See Jan Daciuk s s_fsa package spell . cc for further explanation .
123,635
public int ed ( final int i , final int j , final int wordIndex , final int candIndex ) { int result ; int a , b , c ; if ( areEqual ( wordProcessed [ wordIndex ] , candidate [ candIndex ] ) ) { result = hMatrix . get ( i , j ) ; } else if ( wordIndex > 0 && candIndex > 0 && wordProcessed [ wordIndex ] == candidate [ c...
Calculates edit distance .
123,636
private boolean areEqual ( final char x , final char y ) { if ( x == y ) { return true ; } if ( dictionaryMetadata . getEquivalentChars ( ) != null ) { List < Character > chars = dictionaryMetadata . getEquivalentChars ( ) . get ( x ) ; if ( chars != null && chars . contains ( y ) ) { return true ; } } if ( dictionaryM...
by Jaume Ortola
123,637
public int cuted ( final int depth , final int wordIndex , final int candIndex ) { final int l = Math . max ( 0 , depth - effectEditDistance ) ; final int u = Math . min ( wordLen - 1 - ( wordIndex - depth ) , depth + effectEditDistance ) ; int minEd = effectEditDistance + 1 ; int wi = wordIndex + l - depth ; int d ; f...
Calculates cut - off edit distance .
123,638
private int matchAnyToOne ( final int wordIndex , final int candIndex ) { if ( replacementsAnyToOne . containsKey ( candidate [ candIndex ] ) ) { for ( final char [ ] rep : replacementsAnyToOne . get ( candidate [ candIndex ] ) ) { int i = 0 ; while ( i < rep . length && ( wordIndex + i ) < wordLen && rep [ i ] == word...
Match the last letter of the candidate against two or more letters of the word .
123,639
static boolean containsNoDigit ( final String s ) { for ( int k = 0 ; k < s . length ( ) ; k ++ ) { if ( Character . isDigit ( s . charAt ( k ) ) ) { return false ; } } return true ; }
Checks whether a string contains a digit . Used for ignoring words with numbers
123,640
void setWordAndCandidate ( final String word , final String candidate ) { wordProcessed = word . toCharArray ( ) ; wordLen = wordProcessed . length ; this . candidate = candidate . toCharArray ( ) ; candLen = this . candidate . length ; effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance ; }
Sets up the word and candidate . Used only to test the edit distance in JUnit tests .
123,641
static int sharedPrefixLength ( ByteBuffer a , int aStart , ByteBuffer b , int bStart ) { int i = 0 ; final int max = Math . min ( a . remaining ( ) - aStart , b . remaining ( ) - bStart ) ; aStart += a . position ( ) ; bStart += b . position ( ) ; while ( i < max && a . get ( aStart ++ ) == b . get ( bStart ++ ) ) { i...
Compute the length of the shared prefix between two byte sequences .
123,642
public static ByteBuffer charsToBytes ( CharsetEncoder encoder , CharBuffer chars , ByteBuffer bytes ) throws UnmappableInputException { assert encoder . malformedInputAction ( ) == CodingErrorAction . REPORT ; bytes = clearAndEnsureCapacity ( bytes , ( int ) ( chars . remaining ( ) * encoder . maxBytesPerChar ( ) ) ) ...
Convert chars into bytes .
123,643
public void add ( byte [ ] sequence , int start , int len ) { assert serialized != null : "Automaton already built." ; assert previous == null || len == 0 || compare ( previous , 0 , previousLength , sequence , start , len ) <= 0 : "Input must be sorted: " + Arrays . toString ( Arrays . copyOf ( previous , previousLeng...
Add a single sequence of bytes to the FSA . The input must be lexicographically greater than any previously added sequence .
123,644
public static FSA build ( byte [ ] [ ] input ) { final FSABuilder builder = new FSABuilder ( ) ; for ( byte [ ] chs : input ) { builder . add ( chs , 0 , chs . length ) ; } return builder . complete ( ) ; }
Build a minimal deterministic automaton from a sorted list of byte sequences .
123,645
private int getArcTarget ( int arc ) { arc += ADDRESS_OFFSET ; return ( serialized [ arc ] ) << 24 | ( serialized [ arc + 1 ] & 0xff ) << 16 | ( serialized [ arc + 2 ] & 0xff ) << 8 | ( serialized [ arc + 3 ] & 0xff ) ; }
Returns the address of an arc .
123,646
private void expandAndRehash ( ) { final int [ ] newHashSet = new int [ hashSet . length * 2 ] ; final int bucketMask = ( newHashSet . length - 1 ) ; for ( int j = 0 ; j < hashSet . length ; j ++ ) { final int state = hashSet [ j ] ; if ( state > 0 ) { int slot = hash ( state , stateLength ( state ) ) & bucketMask ; fo...
Reallocate and rehash the hash set .
123,647
private int serialize ( final int activePathIndex ) { expandBuffers ( ) ; final int newState = size ; final int start = activePath [ activePathIndex ] ; final int len = nextArcOffset [ activePathIndex ] - start ; System . arraycopy ( serialized , start , serialized , newState , len ) ; size += len ; return newState ; }
Serialize a given state on the active path .
123,648
private void expandActivePath ( int size ) { if ( activePath . length < size ) { final int p = activePath . length ; activePath = java . util . Arrays . copyOf ( activePath , size ) ; nextArcOffset = java . util . Arrays . copyOf ( nextArcOffset , size ) ; for ( int i = p ; i < size ; i ++ ) { nextArcOffset [ i ] = act...
Append a new mutable state to the active path .
123,649
private void expandBuffers ( ) { if ( this . serialized . length < size + ARC_SIZE * MAX_LABELS ) { serialized = java . util . Arrays . copyOf ( serialized , serialized . length + bufferGrowthSize ) ; serializationBufferReallocations ++ ; } }
Expand internal buffers for the next state .
123,650
public static String applyReplacements ( CharSequence word , LinkedHashMap < String , String > replacements ) { StringBuilder sb = new StringBuilder ( word ) ; for ( final Map . Entry < String , String > e : replacements . entrySet ( ) ) { String key = e . getKey ( ) ; int index = sb . indexOf ( e . getKey ( ) ) ; whil...
Apply partial string replacements from a given map .
123,651
private void computeLabelsIndex ( final FSA fsa ) { final int [ ] countByValue = new int [ 256 ] ; fsa . visitAllStates ( new StateVisitor ( ) { public boolean accept ( int state ) { for ( int arc = fsa . getFirstArc ( state ) ; arc != 0 ; arc = fsa . getNextArc ( arc ) ) countByValue [ fsa . getArcLabel ( arc ) & 0xff...
Compute a set of labels to be integrated with the flags field .
123,652
private void linearizeState ( final FSA fsa , IntStack nodes , IntArrayList linearized , BitSet visited , int node ) { linearized . add ( node ) ; visited . set ( node ) ; for ( int arc = fsa . getFirstArc ( node ) ; arc != 0 ; arc = fsa . getNextArc ( arc ) ) { if ( ! fsa . isArcTerminal ( arc ) ) { final int target =...
Add a state to linearized list .
123,653
private int [ ] computeFirstStates ( IntIntHashMap inlinkCount , int maxStates , int minInlinkCount ) { Comparator < IntIntHolder > comparator = new Comparator < FSAUtils . IntIntHolder > ( ) { public int compare ( IntIntHolder o1 , IntIntHolder o2 ) { int v = o1 . a - o2 . a ; return v == 0 ? ( o1 . b - o2 . b ) : v ;...
Compute the set of states that should be linearized first to minimize other states goto length .
123,654
private IntIntHashMap computeInlinkCount ( final FSA fsa ) { IntIntHashMap inlinkCount = new IntIntHashMap ( ) ; BitSet visited = new BitSet ( ) ; IntStack nodes = new IntStack ( ) ; nodes . push ( fsa . getRootNode ( ) ) ; while ( ! nodes . isEmpty ( ) ) { final int node = nodes . pop ( ) ; if ( visited . get ( node )...
Compute in - link count for each state .
123,655
private int emitNodeArcs ( FSA fsa , OutputStream os , final int state , final int nextState ) throws IOException { int offset = 0 ; for ( int arc = fsa . getFirstArc ( state ) ; arc != 0 ; arc = fsa . getNextArc ( arc ) ) { int targetOffset ; final int target ; if ( fsa . isArcTerminal ( arc ) ) { target = 0 ; targetO...
Emit all arcs of a single node .
123,656
static int writeVInt ( byte [ ] array , int offset , int value ) { assert value >= 0 : "Can't v-code negative ints." ; while ( value > 0x7F ) { array [ offset ++ ] = ( byte ) ( 0x80 | ( value & 0x7F ) ) ; value >>= 7 ; } array [ offset ++ ] = ( byte ) value ; return offset ; }
Write a v - int to a byte array .
123,657
public static IntIntHashMap rightLanguageForAllStates ( final FSA fsa ) { final IntIntHashMap numbers = new IntIntHashMap ( ) ; fsa . visitInPostOrder ( new StateVisitor ( ) { public boolean accept ( int state ) { int thisNodeNumber = 0 ; for ( int arc = fsa . getFirstArc ( state ) ; arc != 0 ; arc = fsa . getNextArc (...
Calculate the size of right language for each state in an FSA . The right language is the number of sequences encoded from a given node in the automaton .
123,658
static int readVInt ( byte [ ] array , int offset ) { byte b = array [ offset ] ; int value = b & 0x7F ; for ( int shift = 7 ; b < 0 ; shift += 7 ) { b = array [ ++ offset ] ; value |= ( b & 0x7F ) << shift ; } return value ; }
Read a v - int .
123,659
public static Dictionary read ( Path location ) throws IOException { final Path metadata = DictionaryMetadata . getExpectedMetadataLocation ( location ) ; try ( InputStream fsaStream = Files . newInputStream ( location ) ; InputStream metadataStream = Files . newInputStream ( metadata ) ) { return read ( fsaStream , me...
Attempts to load a dictionary using the path to the FSA file and the expected metadata extension .
123,660
public static Dictionary read ( URL dictURL ) throws IOException { final URL expectedMetadataURL ; try { String external = dictURL . toExternalForm ( ) ; expectedMetadataURL = new URL ( DictionaryMetadata . getExpectedMetadataFileName ( external ) ) ; } catch ( MalformedURLException e ) { throw new IOException ( "Could...
Attempts to load a dictionary using the URL to the FSA file and the expected metadata extension .
123,661
public static Dictionary read ( InputStream fsaStream , InputStream metadataStream ) throws IOException { return new Dictionary ( FSA . read ( fsaStream ) , DictionaryMetadata . read ( metadataStream ) ) ; }
Attempts to load a dictionary from opened streams of FSA dictionary data and associated metadata . Input streams are not closed automatically .
123,662
public void set ( final int i , final int j , final int val ) { p [ ( j - i + editDistance + 1 ) * rowLength + j ] = val ; }
Set an item in hMatrix . No checking for i &amp ; j is done . They must be correct .
123,663
private final ByteBuffer advance ( ) { if ( position == 0 ) { return null ; } while ( position > 0 ) { final int lastIndex = position - 1 ; final int arc = arcs [ lastIndex ] ; if ( arc == 0 ) { position -- ; continue ; } arcs [ lastIndex ] = fsa . getNextArc ( arc ) ; final int bufferLength = this . buffer . length ; ...
Advances to the next available final state .
123,664
private void pushNode ( int node ) { if ( position == arcs . length ) { arcs = Arrays . copyOf ( arcs , arcs . length + EXPECTED_MAX_STATES ) ; } arcs [ position ++ ] = fsa . getFirstArc ( node ) ; }
Descends to a given node adds its arcs to the stack to be traversed .
123,665
public static FSAHeader read ( InputStream in ) throws IOException { if ( in . read ( ) != ( ( FSA_MAGIC >>> 24 ) ) || in . read ( ) != ( ( FSA_MAGIC >>> 16 ) & 0xff ) || in . read ( ) != ( ( FSA_MAGIC >>> 8 ) & 0xff ) || in . read ( ) != ( ( FSA_MAGIC ) & 0xff ) ) { throw new IOException ( "Invalid file header, probab...
Read FSA header and version from a stream consuming read bytes .
123,666
public static void write ( OutputStream os , byte version ) throws IOException { os . write ( FSA_MAGIC >> 24 ) ; os . write ( FSA_MAGIC >> 16 ) ; os . write ( FSA_MAGIC >> 8 ) ; os . write ( FSA_MAGIC ) ; os . write ( version ) ; }
Writes FSA magic bytes and version information .
123,667
static final int decodeFromBytes ( final byte [ ] arcs , final int start , final int n ) { int r = 0 ; for ( int i = n ; -- i >= 0 ; ) { r = r << 8 | ( arcs [ start + i ] & 0xff ) ; } return r ; }
Returns an n - byte integer encoded in byte - packed representation .
123,668
protected static void main ( String [ ] args , CliTool ... commands ) { if ( commands . length == 1 ) { main ( args , commands [ 0 ] ) ; } else { JCommander jc = new JCommander ( ) ; for ( CliTool command : commands ) { jc . addCommand ( command ) ; } jc . addConverterFactory ( new CustomParameterConverters ( ) ) ; jc ...
Parse and execute one of the commands .
123,669
protected static void main ( String [ ] args , CliTool command ) { JCommander jc = new JCommander ( command ) ; jc . addConverterFactory ( new CustomParameterConverters ( ) ) ; jc . setProgramName ( command . getClass ( ) . getAnnotation ( Parameters . class ) . commandNames ( ) [ 0 ] ) ; ExitStatus exitStatus = ExitSt...
Parse and execute a single command .
123,670
static String byteAsChar ( byte v ) { int chr = v & 0xff ; return String . format ( Locale . ROOT , "%s (0x%02x)" , ( Character . isWhitespace ( chr ) || chr > 127 ) ? "[non-printable]" : Character . toString ( ( char ) chr ) , v & 0xFF ) ; }
Convert a byte to an informative string .
123,671
public static FSA read ( InputStream stream ) throws IOException { final FSAHeader header = FSAHeader . read ( stream ) ; switch ( header . version ) { case FSA5 . VERSION : return new FSA5 ( stream ) ; case CFSA . VERSION : return new CFSA ( stream ) ; case CFSA2 . VERSION : return new CFSA2 ( stream ) ; default : thr...
A factory for reading automata in any of the supported versions .
123,672
public static < T extends FSA > T read ( InputStream stream , Class < ? extends T > clazz ) throws IOException { FSA fsa = read ( stream ) ; if ( ! clazz . isInstance ( fsa ) ) { throw new IOException ( String . format ( Locale . ROOT , "Expected FSA type %s, but read an incompatible type %s." , clazz . getName ( ) , f...
A factory for reading a specific FSA subclass including proper casting .
123,673
private static int forAllLines ( InputStream is , byte separator , LineConsumer lineConsumer ) throws IOException { int lines = 0 ; byte [ ] buffer = new byte [ 0 ] ; int b , pos = 0 ; while ( ( b = is . read ( ) ) != - 1 ) { if ( b == separator ) { buffer = lineConsumer . process ( buffer , pos ) ; pos = 0 ; lines ++ ...
Read all byte - separated sequences .
123,674
public static NtlmPasswordAuthentication authenticate ( HttpServletRequest req , HttpServletResponse resp , byte [ ] challenge ) throws IOException , ServletException { String msg = req . getHeader ( "Authorization" ) ; if ( msg != null && msg . startsWith ( "NTLM " ) ) { byte [ ] src = Base64 . decode ( msg . substrin...
Performs NTLM authentication for the servlet request .
123,675
boolean verify ( byte [ ] data , int offset , ServerMessageBlock response ) { update ( macSigningKey , 0 , macSigningKey . length ) ; int index = offset ; update ( data , index , ServerMessageBlock . SIGNATURE_OFFSET ) ; index += ServerMessageBlock . SIGNATURE_OFFSET ; byte [ ] sequence = new byte [ 8 ] ; ServerMessage...
Performs MAC signature verification . This calculates the signature of the SMB and compares it to the signature field on the SMB itself .
123,676
public static String encode ( byte [ ] bytes ) { int length = bytes . length ; if ( length == 0 ) return "" ; StringBuffer buffer = new StringBuffer ( ( int ) Math . ceil ( ( double ) length / 3d ) * 4 ) ; int remainder = length % 3 ; length -= remainder ; int block ; int i = 0 ; while ( i < length ) { block = ( ( byte...
Base - 64 encodes the supplied block of data . Line wrapping is not applied on output .
123,677
public static byte [ ] decode ( String string ) { int length = string . length ( ) ; if ( length == 0 ) return new byte [ 0 ] ; int pad = ( string . charAt ( length - 2 ) == '=' ) ? 2 : ( string . charAt ( length - 1 ) == '=' ) ? 1 : 0 ; int size = length * 3 / 4 - pad ; byte [ ] buffer = new byte [ size ] ; int block ...
Decodes the supplied Base - 64 encoded string .
123,678
public Post reblog ( String blogName , Map < String , ? > options ) { return client . postReblog ( blogName , id , reblog_key , options ) ; }
Reblog this post
123,679
public void setDate ( Date date ) { DateFormat df = new SimpleDateFormat ( "yyyy/MM/dd HH:mm:ss" ) ; df . setTimeZone ( TimeZone . getTimeZone ( "GMT" ) ) ; setDate ( df . format ( date ) ) ; }
Set the date as a date
123,680
public void addTag ( String tag ) { if ( this . tags == null ) { tags = new ArrayList < String > ( ) ; } this . tags . add ( tag ) ; }
Add a tag
123,681
public void save ( ) throws IOException { if ( id == null ) { this . id = client . postCreate ( blog_name , detail ( ) ) ; } else { client . postEdit ( blog_name , id , detail ( ) ) ; } }
Save this post
123,682
protected Map < String , Object > detail ( ) { final Map < String , Object > map = new HashMap < String , Object > ( ) ; map . put ( "state" , state ) ; map . put ( "tags" , getTagString ( ) ) ; map . put ( "format" , format ) ; map . put ( "slug" , slug ) ; map . put ( "date" , date ) ; map . put ( "type" , getType ( ...
Detail for this post
123,683
public void setPhoto ( Photo photo ) { PhotoType type = photo . getType ( ) ; if ( postType != null && ! postType . equals ( type ) ) { throw new IllegalArgumentException ( "Photos must all be the same type (source or data)" ) ; } else if ( postType == PhotoType . SOURCE && pendingPhotos . size ( ) > 0 ) { throw new Il...
Set the photo for this post
123,684
public List < Blog > getBlogs ( ) { if ( blogs != null ) { for ( Blog blog : blogs ) { blog . setClient ( client ) ; } } return this . blogs ; }
Get the blog List for this user
123,685
private void extractErrors ( JsonObject object ) { JsonObject response ; try { response = object . getAsJsonObject ( "response" ) ; } catch ( ClassCastException ex ) { return ; } if ( response == null ) { return ; } JsonArray e = response . getAsJsonArray ( "errors" ) ; if ( e == null ) { return ; } errors = new ArrayL...
Pull the errors out of the response if present
123,686
private void extractMessage ( JsonObject object ) { JsonObject meta = object . getAsJsonObject ( "meta" ) ; if ( meta != null ) { JsonPrimitive msg = meta . getAsJsonPrimitive ( "msg" ) ; if ( msg != null ) { this . message = msg . getAsString ( ) ; return ; } } JsonPrimitive error = object . getAsJsonPrimitive ( "erro...
Pull the message out of the response
123,687
public void xauth ( final String email , final String password ) { setToken ( this . requestBuilder . postXAuth ( email , password ) ) ; }
Performs an XAuth authentication .
123,688
public List < Post > userDashboard ( Map < String , ? > options ) { return requestBuilder . get ( "/user/dashboard" , options ) . getPosts ( ) ; }
Get the user dashboard for the authenticated User
123,689
public List < Blog > userFollowing ( Map < String , ? > options ) { return requestBuilder . get ( "/user/following" , options ) . getBlogs ( ) ; }
Get the blogs the given user is following
123,690
public Blog blogInfo ( String blogName ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "api_key" , this . apiKey ) ; return requestBuilder . get ( JumblrClient . blogPath ( blogName , "/info" ) , map ) . getBlog ( ) ; }
Get the blog info for a given blog
123,691
public List < User > blogFollowers ( String blogName , Map < String , ? > options ) { return requestBuilder . get ( JumblrClient . blogPath ( blogName , "/followers" ) , options ) . getUsers ( ) ; }
Get the followers for a given blog
123,692
public List < Post > blogLikes ( String blogName , Map < String , ? > options ) { if ( options == null ) { options = Collections . emptyMap ( ) ; } Map < String , Object > soptions = JumblrClient . safeOptionMap ( options ) ; soptions . put ( "api_key" , this . apiKey ) ; return requestBuilder . get ( JumblrClient . bl...
Get the public likes for a given blog
123,693
public List < Post > blogPosts ( String blogName , Map < String , ? > options ) { if ( options == null ) { options = Collections . emptyMap ( ) ; } Map < String , Object > soptions = JumblrClient . safeOptionMap ( options ) ; soptions . put ( "api_key" , apiKey ) ; String path = "/posts" ; if ( soptions . containsKey (...
Get the posts for a given blog
123,694
public Post blogPost ( String blogName , Long postId ) { HashMap < String , String > options = new HashMap < String , String > ( ) ; options . put ( "id" , postId . toString ( ) ) ; List < Post > posts = this . blogPosts ( blogName , options ) ; return posts . size ( ) > 0 ? posts . get ( 0 ) : null ; }
Get an individual post by id
123,695
public List < Post > blogQueuedPosts ( String blogName , Map < String , ? > options ) { return requestBuilder . get ( JumblrClient . blogPath ( blogName , "/posts/queue" ) , options ) . getPosts ( ) ; }
Get the queued posts for a given blog
123,696
public List < Post > userLikes ( Map < String , ? > options ) { return requestBuilder . get ( "/user/likes" , options ) . getLikedPosts ( ) ; }
Get the likes for the authenticated user
123,697
public String blogAvatar ( String blogName , Integer size ) { String pathExt = size == null ? "" : "/" + size . toString ( ) ; return requestBuilder . getRedirectUrl ( JumblrClient . blogPath ( blogName , "/avatar" + pathExt ) ) ; }
Get a specific size avatar for a given blog
123,698
public void like ( Long postId , String reblogKey ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "id" , postId . toString ( ) ) ; map . put ( "reblog_key" , reblogKey ) ; requestBuilder . post ( "/user/like" , map ) ; }
Like a given post
123,699
public void follow ( String blogName ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "url" , JumblrClient . blogUrl ( blogName ) ) ; requestBuilder . post ( "/user/follow" , map ) ; }
Follow a given blog