idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
32,700
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private void writeJSON ( Object value ) throws JSONException { if ( JSONObject . NULL . equals ( value ) ) { write ( zipNull , 3 ) ; } else if ( Boolean . FALSE . equals ( value ) ) { write ( zipFalse , 3 ) ; } else if ( Boolean . TRUE . equals ( value ) ) { write ( zipTrue , 3 ) ; } else { if ( value instanceof Map ) { value = new JSONObject ( ( Map ) value ) ; } else if ( value instanceof Collection ) { value = new JSONArray ( ( Collection ) value ) ; } else if ( value . getClass ( ) . isArray ( ) ) { value = new JSONArray ( value ) ; } if ( value instanceof JSONObject ) { write ( ( JSONObject ) value ) ; } else if ( value instanceof JSONArray ) { write ( ( JSONArray ) value ) ; } else { throw new JSONException ( "Unrecognized object" ) ; } } }
Write a JSON value .
225
5
32,701
private void writeName ( String name ) throws JSONException { // If this name has already been registered, then emit its integer and // increment its usage count. Kim kim = new Kim ( name ) ; int integer = this . namekeep . find ( kim ) ; if ( integer != none ) { one ( ) ; write ( integer , this . namekeep ) ; } else { // Otherwise, emit the string with Huffman encoding, and register it. zero ( ) ; write ( kim , this . namehuff , this . namehuffext ) ; write ( end , namehuff ) ; this . namekeep . register ( kim ) ; } }
Write the name of an object property . Names have their own Keep and Huffman encoder because they are expected to be a more restricted set .
140
29
32,702
private void write ( JSONObject jsonobject ) throws JSONException { // JSONzip has two encodings for objects: Empty Objects (zipEmptyObject) and // non-empty objects (zipObject). boolean first = true ; Iterator < String > keys = jsonobject . keys ( ) ; while ( keys . hasNext ( ) ) { if ( probe ) { log ( ) ; } Object key = keys . next ( ) ; if ( key instanceof String ) { if ( first ) { first = false ; write ( zipObject , 3 ) ; } else { one ( ) ; } writeName ( ( String ) key ) ; Object value = jsonobject . get ( ( String ) key ) ; if ( value instanceof String ) { zero ( ) ; writeString ( ( String ) value ) ; } else { one ( ) ; writeValue ( value ) ; } } } if ( first ) { write ( zipEmptyObject , 3 ) ; } else { zero ( ) ; } }
Write a JSON object .
205
5
32,703
private void writeValue ( Object value ) throws JSONException { if ( value instanceof Number ) { String string = JSONObject . numberToString ( ( Number ) value ) ; int integer = this . valuekeep . find ( string ) ; if ( integer != none ) { write ( 2 , 2 ) ; write ( integer , this . valuekeep ) ; return ; } if ( value instanceof Integer || value instanceof Long ) { long longer = ( ( Number ) value ) . longValue ( ) ; if ( longer >= 0 && longer < int14 ) { write ( 0 , 2 ) ; if ( longer < int4 ) { zero ( ) ; write ( ( int ) longer , 4 ) ; return ; } one ( ) ; if ( longer < int7 ) { zero ( ) ; write ( ( int ) ( longer - int4 ) , 7 ) ; return ; } one ( ) ; write ( ( int ) ( longer - int7 ) , 14 ) ; return ; } } write ( 1 , 2 ) ; for ( int i = 0 ; i < string . length ( ) ; i += 1 ) { write ( bcd ( string . charAt ( i ) ) , 4 ) ; } write ( endOfNumber , 4 ) ; this . valuekeep . register ( string ) ; } else { write ( 3 , 2 ) ; writeJSON ( value ) ; } }
Write a value .
287
4
32,704
protected boolean filter ( IWord word ) { /* * normally word with length less than 2 will * be something, well could be ignored */ if ( word . getValue ( ) . length ( ) < 2 ) { return false ; } //type check switch ( word . getType ( ) ) { //case IWord.T_BASIC_LATIN: case IWord . T_LETTER_NUMBER : case IWord . T_OTHER_NUMBER : case IWord . T_CJK_PINYIN : case IWord . T_PUNCTUATION : case IWord . T_UNRECOGNIZE_WORD : { return false ; } } //part of speech check String [ ] poss = word . getPartSpeech ( ) ; if ( poss == null ) return true ; char pos = poss [ 0 ] . charAt ( 0 ) ; switch ( pos ) { case ' ' : { if ( poss [ 0 ] . equals ( "en" ) ) return true ; return false ; } case ' ' : { if ( poss [ 0 ] . equals ( "mix" ) ) return true ; return false ; } case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : //@date 2015-11-23 case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : { return false ; } /*case 'n': case 'v': case 'a': case 't': case 's': case 'f': { return true; }*/ } return true ; }
word item filter
354
3
32,705
private void init ( ) { //request.setCharacterEncoding(setting.getCharset()); response . setCharacterEncoding ( config . getCharset ( ) ) ; response . setContentType ( "text/html;charset=" + config . getCharset ( ) ) ; response . setStatus ( HttpServletResponse . SC_OK ) ; }
request initialize work
81
3
32,706
public int getInt ( String name ) { int val = 0 ; try { val = Integer . valueOf ( request . getParameter ( name ) ) ; } catch ( NumberFormatException e ) { } return val ; }
get a integer arguments
46
4
32,707
public float getFloat ( String name ) { float fval = 0F ; try { fval = Float . valueOf ( request . getParameter ( name ) ) ; } catch ( NumberFormatException e ) { } return fval ; }
get a float arguments
50
4
32,708
public long getLong ( String name ) { long val = 0 ; try { val = Long . valueOf ( request . getParameter ( name ) ) ; } catch ( NumberFormatException e ) { } return val ; }
get a long argument
46
4
32,709
public double getDouble ( String name ) { double val = 0 ; try { val = Double . valueOf ( request . getParameter ( name ) ) ; } catch ( NumberFormatException e ) { } return val ; }
get a double argument
46
4
32,710
public boolean getBoolean ( String name ) { boolean val = false ; try { val = Boolean . valueOf ( request . getParameter ( name ) ) ; } catch ( NumberFormatException e ) { } return val ; }
get a boolean argument
47
4
32,711
public byte [ ] getRawData ( ) throws IOException { int contentLength = request . getContentLength ( ) ; if ( contentLength < 0 ) { return null ; } byte [ ] buffer = new byte [ contentLength ] ; ServletInputStream is = request . getInputStream ( ) ; for ( int i = 0 ; i < contentLength ; ) { int rLen = is . read ( buffer , i , contentLength - i ) ; if ( rLen == - 1 ) { break ; } i += rLen ; } return buffer ; }
get the original raw data
117
5
32,712
public String getRawDataAsString ( ) throws IOException { byte [ ] buffer = getRawData ( ) ; if ( buffer == null ) { return null ; } String encoding = request . getCharacterEncoding ( ) ; if ( encoding == null ) { encoding = "utf-8" ; } return new String ( buffer , encoding ) ; }
get the original request raw data as String
73
8
32,713
public JSONObject getRawDataAsJson ( ) throws IOException { String input = getRawDataAsString ( ) ; if ( input == null ) { return null ; } return new JSONObject ( input ) ; }
get the original request raw data as json
46
8
32,714
static void logchar ( int integer , int width ) { if ( integer > ' ' && integer <= ' ' ) { log ( "'" + ( char ) integer + "':" + width + " " ) ; } else { log ( integer , width ) ; } }
Write a character or its code to the console .
57
10
32,715
public boolean postMortem ( PostMortem pm ) { JSONzip that = ( JSONzip ) pm ; return this . namehuff . postMortem ( that . namehuff ) && this . namekeep . postMortem ( that . namekeep ) && this . stringkeep . postMortem ( that . stringkeep ) && this . stringhuff . postMortem ( that . stringhuff ) && this . valuekeep . postMortem ( that . valuekeep ) ; }
This method is used for testing the implementation of JSONzip . It is not suitable for any other purpose . It is used to compare a Compressor and a Decompressor verifying that the data structures that were built during zipping and unzipping were the same .
110
53
32,716
public boolean postMortem ( PostMortem pm ) { // Go through every integer in the domain, generating its bit sequence, and // then prove that that bit sequence produces the same integer. for ( int integer = 0 ; integer < this . domain ; integer += 1 ) { if ( ! postMortem ( integer ) ) { JSONzip . log ( "\nBad huff " ) ; JSONzip . logchar ( integer , integer ) ; return false ; } } return this . table . postMortem ( ( ( Huff ) pm ) . table ) ; }
Compare two Huffman tables .
121
6
32,717
public int read ( BitReader bitreader ) throws JSONException { try { this . width = 0 ; Symbol symbol = this . table ; while ( symbol . integer == none ) { this . width += 1 ; symbol = bitreader . bit ( ) ? symbol . one : symbol . zero ; } tick ( symbol . integer ) ; if ( JSONzip . probe ) { JSONzip . logchar ( symbol . integer , this . width ) ; } return symbol . integer ; } catch ( Throwable e ) { throw new JSONException ( e ) ; } }
Read bits until a symbol can be identified . The weight of the read symbol will be incremented .
115
20
32,718
private void write ( Symbol symbol , BitWriter bitwriter ) throws JSONException { try { Symbol back = symbol . back ; if ( back != null ) { this . width += 1 ; write ( back , bitwriter ) ; if ( back . zero == symbol ) { bitwriter . zero ( ) ; } else { bitwriter . one ( ) ; } } } catch ( Throwable e ) { throw new JSONException ( e ) ; } }
Recur from a symbol back emitting bits . We recur before emitting to make the bits come out in the right order .
92
25
32,719
public void write ( int value , BitWriter bitwriter ) throws JSONException { this . width = 0 ; write ( this . symbols [ value ] , bitwriter ) ; tick ( value ) ; if ( JSONzip . probe ) { JSONzip . logchar ( value , this . width ) ; } }
Write the bits corresponding to a symbol . The weight of the symbol will be incremented .
63
18
32,720
private boolean bit ( ) throws JSONException { boolean value ; try { value = this . bitreader . bit ( ) ; if ( probe ) { log ( value ? 1 : 0 ) ; } return value ; } catch ( Throwable e ) { throw new JSONException ( e ) ; } }
Read one bit .
61
4
32,721
private Object getAndTick ( Keep keep , BitReader bitreader ) throws JSONException { try { int width = keep . bitsize ( ) ; int integer = bitreader . read ( width ) ; Object value = keep . value ( integer ) ; if ( JSONzip . probe ) { JSONzip . log ( "\"" + value + "\"" ) ; JSONzip . log ( integer , width ) ; } if ( integer >= keep . length ) { throw new JSONException ( "Deep error." ) ; } keep . tick ( integer ) ; return value ; } catch ( Throwable e ) { throw new JSONException ( e ) ; } }
Read enough bits to obtain an integer from the keep and increase that integer s weight .
136
17
32,722
private int read ( int width ) throws JSONException { try { int value = this . bitreader . read ( width ) ; if ( probe ) { log ( value , width ) ; } return value ; } catch ( Throwable e ) { throw new JSONException ( e ) ; } }
Read an integer specifying its width in bits .
60
9
32,723
private String read ( Huff huff , Huff ext , Keep keep ) throws JSONException { Kim kim ; int at = 0 ; int allocation = 256 ; byte [ ] bytes = new byte [ allocation ] ; if ( bit ( ) ) { return getAndTick ( keep , this . bitreader ) . toString ( ) ; } while ( true ) { if ( at >= allocation ) { allocation *= 2 ; bytes = java . util . Arrays . copyOf ( bytes , allocation ) ; } int c = huff . read ( this . bitreader ) ; if ( c == end ) { break ; } while ( ( c & 128 ) == 128 ) { bytes [ at ] = ( byte ) c ; at += 1 ; c = ext . read ( this . bitreader ) ; } bytes [ at ] = ( byte ) c ; at += 1 ; } if ( at == 0 ) { return "" ; } kim = new Kim ( bytes , at ) ; keep . register ( kim ) ; return kim . toString ( ) ; }
Read Huffman encoded characters into a keep .
222
9
32,724
private JSONArray readArray ( boolean stringy ) throws JSONException { JSONArray jsonarray = new JSONArray ( ) ; jsonarray . put ( stringy ? read ( this . stringhuff , this . stringhuffext , this . stringkeep ) : readValue ( ) ) ; while ( true ) { if ( probe ) { log ( ) ; } if ( ! bit ( ) ) { if ( ! bit ( ) ) { return jsonarray ; } jsonarray . put ( stringy ? readValue ( ) : read ( this . stringhuff , this . stringhuffext , this . stringkeep ) ) ; } else { jsonarray . put ( stringy ? read ( this . stringhuff , this . stringhuffext , this . stringkeep ) : readValue ( ) ) ; } } }
Read a JSONArray .
172
5
32,725
private Object readJSON ( ) throws JSONException { switch ( read ( 3 ) ) { case zipObject : return readObject ( ) ; case zipArrayString : return readArray ( true ) ; case zipArrayValue : return readArray ( false ) ; case zipEmptyObject : return new JSONObject ( ) ; case zipEmptyArray : return new JSONArray ( ) ; case zipTrue : return Boolean . TRUE ; case zipFalse : return Boolean . FALSE ; default : return JSONObject . NULL ; } }
Read a JSON value . The type of value is determined by the next 3 bits .
104
17
32,726
public void add ( int val ) { if ( size == items . length ) resize ( items . length * 2 + 1 ) ; items [ size ++ ] = val ; }
Append a new Integer to the end .
36
9
32,727
public void remove ( int idx ) { if ( idx < 0 || idx > size ) throw new IndexOutOfBoundsException ( ) ; int numMove = size - idx - 1 ; if ( numMove > 0 ) System . arraycopy ( items , idx + 1 , items , idx , numMove ) ; size -- ; }
remove the element at the specified position use System . arraycopy instead of a loop may be more efficient
75
20
32,728
public JSONArray put ( int index , Map < String , Object > value ) throws JSONException { this . put ( index , new JSONObject ( value ) ) ; return this ; }
Put a value in the JSONArray where the value will be a JSONObject that is produced from a Map .
38
22
32,729
public boolean similar ( Object other ) { if ( ! ( other instanceof JSONArray ) ) { return false ; } int len = this . length ( ) ; if ( len != ( ( JSONArray ) other ) . length ( ) ) { return false ; } for ( int i = 0 ; i < len ; i += 1 ) { Object valueThis = this . get ( i ) ; Object valueOther = ( ( JSONArray ) other ) . get ( i ) ; if ( valueThis instanceof JSONObject ) { if ( ! ( ( JSONObject ) valueThis ) . similar ( valueOther ) ) { return false ; } } else if ( valueThis instanceof JSONArray ) { if ( ! ( ( JSONArray ) valueThis ) . similar ( valueOther ) ) { return false ; } } else if ( ! valueThis . equals ( valueOther ) ) { return false ; } } return true ; }
Determine if two JSONArrays are similar . They must contain similar sequences .
190
17
32,730
public int copy ( byte [ ] bytes , int at ) { System . arraycopy ( this . bytes , 0 , bytes , at , this . length ) ; return at + this . length ; }
Copy the contents of this kim to a byte array .
41
12
32,731
public int get ( int at ) throws JSONException { if ( at < 0 || at > this . length ) { throw new JSONException ( "Bad character at " + at ) ; } return ( ( int ) this . bytes [ at ] ) & 0xFF ; }
Get a byte from a kim .
57
8
32,732
public void reset ( Reader input ) throws IOException { if ( input != null ) { reader = new IPushbackReader ( new BufferedReader ( input ) ) ; } idx = - 1 ; }
input stream and reader reset .
43
6
32,733
protected void pushBack ( String str ) { char [ ] chars = str . toCharArray ( ) ; for ( int j = chars . length - 1 ; j >= 0 ; j -- ) { reader . unread ( chars [ j ] ) ; } idx -= chars . length ; }
push back a string to the stream
61
7
32,734
protected IWord getNextLatinWord ( int c , int pos ) throws IOException { /* * clear or just return the English punctuation as * a single word with PUNCTUATION type and part of speech */ if ( StringUtil . isEnPunctuation ( c ) ) { String str = String . valueOf ( ( char ) c ) ; if ( config . CLEAR_STOPWORD && dic . match ( ILexicon . STOP_WORD , str ) ) { return null ; } IWord w = new Word ( str , IWord . T_PUNCTUATION ) ; w . setPosition ( pos ) ; w . setPartSpeech ( IWord . PUNCTUATION ) ; return w ; } IWord w = nextLatinWord ( c , pos ) ; w . setPosition ( pos ) ; /* @added: 2013-12-16 * check and do the secondary segmentation work. * This will split 'qq2013' to 'qq, 2013'. */ if ( config . EN_SECOND_SEG && ( ctrlMask & ISegment . START_SS_MASK ) != 0 ) { enSecondSeg ( w , false ) ; } if ( config . CLEAR_STOPWORD && dic . match ( ILexicon . STOP_WORD , w . getValue ( ) ) ) { w = null ; //Let gc do its work return null ; } if ( config . APPEND_CJK_SYN ) { appendLatinSyn ( w ) ; } return w ; }
get the next Latin word from the current position of the input stream
333
13
32,735
protected IWord getNextMixedWord ( char [ ] chars , int cjkidx ) throws IOException { IStringBuffer buff = new IStringBuffer ( ) ; buff . clear ( ) . append ( chars , cjkidx ) ; String tstring = buff . toString ( ) ; if ( ! dic . match ( ILexicon . MIX_ASSIST_WORD , tstring ) ) { return null ; } /* * check and append the behind Latin string */ if ( behindLatin == null ) { behindLatin = nextLatinString ( readNext ( ) ) ; } IWord wd = null ; buff . append ( behindLatin ) ; tstring = buff . toString ( ) ; if ( dic . match ( ILexicon . CJK_WORD , tstring ) ) { wd = dic . get ( ILexicon . CJK_WORD , tstring ) ; } if ( ( ctrlMask & ISegment . CHECK_EC_MASK ) != 0 || dic . match ( ILexicon . MIX_ASSIST_WORD , tstring ) ) { ialist . clear ( ) ; int chr = - 1 , j , mc = 0 ; for ( j = 0 ; j < dic . mixSuffixLength && ( chr = readNext ( ) ) != - 1 ; j ++ ) { buff . append ( ( char ) chr ) ; ialist . add ( chr ) ; tstring = buff . toString ( ) ; if ( dic . match ( ILexicon . CJK_WORD , tstring ) ) { wd = dic . get ( ILexicon . CJK_WORD , tstring ) ; mc = j + 1 ; } } //push back the read chars. for ( int i = j - 1 ; i >= mc ; i -- ) { pushBack ( ialist . get ( i ) ) ; } } buff . clear ( ) ; buff = null ; if ( wd != null ) { behindLatin = null ; } return wd ; }
get the next mixed word CJK - English or CJK - English - CJK or whatever
446
19
32,736
protected IWord getNextPunctuationPairWord ( int c , int pos ) throws IOException { IWord w = null , w2 = null ; String text = getPairPunctuationText ( c ) ; //handle the punctuation. String str = String . valueOf ( ( char ) c ) ; if ( ! ( config . CLEAR_STOPWORD && dic . match ( ILexicon . STOP_WORD , str ) ) ) { w = new Word ( str , IWord . T_PUNCTUATION ) ; w . setPartSpeech ( IWord . PUNCTUATION ) ; w . setPosition ( pos ) ; } //handle the pair text. if ( text != null && text . length ( ) > 0 && ! ( config . CLEAR_STOPWORD && dic . match ( ILexicon . STOP_WORD , text ) ) ) { w2 = new Word ( text , ILexicon . CJK_WORD ) ; w2 . setPartSpeech ( IWord . PPT_POSPEECH ) ; w2 . setPosition ( pos + 1 ) ; if ( w == null ) w = w2 ; else wordPool . add ( w2 ) ; } /* here: * 1. the punctuation is clear. * 2. the pair text is null or being cleared. * @date 2013-09-06 */ if ( w == null && w2 == null ) { return null ; } return w ; }
get the next punctuation pair word from the current position of the input stream .
320
16
32,737
protected void appendWordFeatures ( IWord word ) { //add the pinyin to the pool if ( config . APPEND_CJK_PINYIN && config . LOAD_CJK_PINYIN && word . getPinyin ( ) != null ) { IWord pinyin = new Word ( word . getPinyin ( ) , IWord . T_CJK_PINYIN ) ; pinyin . setPosition ( word . getPosition ( ) ) ; pinyin . setEntity ( word . getEntity ( ) ) ; wordPool . add ( pinyin ) ; } //add the synonyms words to the pool if ( config . APPEND_CJK_SYN && config . LOAD_CJK_SYN && word . getSyn ( ) != null ) { SegKit . appendSynonyms ( wordPool , word ) ; } }
check and append the pinyin and the synonyms words of the specified word
193
16
32,738
protected void appendLatinSyn ( IWord w ) { IWord ew ; /* * @added 2014-07-07 * w maybe EC_MIX_WORD, so check its syn first * and make sure it is not a EC_MIX_WORD then check the EN_WORD */ if ( w . getSyn ( ) == null ) { ew = dic . get ( ILexicon . CJK_WORD , w . getValue ( ) ) ; } else { ew = w ; } if ( ew != null && ew . getSyn ( ) != null ) { ew . setPosition ( w . getPosition ( ) ) ; SegKit . appendSynonyms ( wordPool , ew ) ; } }
Check and append the synonyms words of specified word included the CJK and basic Latin words All the synonyms words share the same position part of speech word type with the primitive word
159
36
32,739
protected IWord [ ] getNextMatch ( char [ ] chars , int index ) { ArrayList < IWord > mList = new ArrayList < IWord > ( 8 ) ; //StringBuilder isb = new StringBuilder(); isb . clear ( ) ; char c = chars [ index ] ; isb . append ( c ) ; String temp = isb . toString ( ) ; if ( dic . match ( ILexicon . CJK_WORD , temp ) ) { mList . add ( dic . get ( ILexicon . CJK_WORD , temp ) ) ; } String _key = null ; for ( int j = 1 ; j < config . MAX_LENGTH && ( ( j + index ) < chars . length ) ; j ++ ) { isb . append ( chars [ j + index ] ) ; _key = isb . toString ( ) ; if ( dic . match ( ILexicon . CJK_WORD , _key ) ) { mList . add ( dic . get ( ILexicon . CJK_WORD , _key ) ) ; } } /* * if match no words from the current position * to idx+Config.MAX_LENGTH, just return the Word with * a value of temp as a unrecognited word. */ if ( mList . isEmpty ( ) ) { mList . add ( new Word ( temp , ILexicon . UNMATCH_CJK_WORD ) ) ; } /* for ( int j = 0; j < mList.size(); j++ ) { System.out.println(mList.get(j)); }*/ IWord [ ] words = new IWord [ mList . size ( ) ] ; mList . toArray ( words ) ; mList . clear ( ) ; return words ; }
match the next CJK word in the dictionary
389
9
32,740
protected char [ ] nextCJKSentence ( int c ) throws IOException { isb . clear ( ) ; int ch ; isb . append ( ( char ) c ) ; //reset the CE check mask. ctrlMask &= ~ ISegment . CHECK_CE_MASk ; while ( ( ch = readNext ( ) ) != - 1 ) { if ( StringUtil . isWhitespace ( ch ) ) { pushBack ( ch ) ; break ; } if ( ! StringUtil . isCJKChar ( ch ) ) { pushBack ( ch ) ; /*check Chinese English mixed word*/ if ( StringUtil . isEnLetter ( ch ) || StringUtil . isEnNumeric ( ch ) ) { ctrlMask |= ISegment . CHECK_CE_MASk ; } break ; } isb . append ( ( char ) ch ) ; } return isb . toString ( ) . toCharArray ( ) ; }
load a CJK char list from the stream start from the current position till the char is not a CJK char
208
23
32,741
protected String nextLatinString ( int c ) throws IOException { isb . clear ( ) ; if ( c > 65280 ) c -= 65248 ; if ( c >= 65 && c <= 90 ) c += 32 ; isb . append ( ( char ) c ) ; int ch ; int _ctype = 0 ; ctrlMask &= ~ ISegment . CHECK_EC_MASK ; while ( ( ch = readNext ( ) ) != - 1 ) { //Covert the full-width char to half-width char. if ( ch > 65280 ) ch -= 65248 ; _ctype = StringUtil . getEnCharType ( ch ) ; //Whitespace check. if ( _ctype == StringUtil . EN_WHITESPACE ) { break ; } //English punctuation check. if ( _ctype == StringUtil . EN_PUNCTUATION ) { if ( ! config . isKeepPunctuation ( ( char ) ch ) ) { pushBack ( ch ) ; break ; } } //Not EN_KNOW, and it could be letter, numeric. if ( _ctype == StringUtil . EN_UNKNOW ) { pushBack ( ch ) ; if ( StringUtil . isCJKChar ( ch ) ) { ctrlMask |= ISegment . CHECK_EC_MASK ; } break ; } //covert the lower case letter to upper case. if ( ch >= 65 && ch <= 90 ) ch += 32 ; isb . append ( ( char ) ch ) ; /* * global English word length limitation */ if ( isb . length ( ) > config . MAX_LATIN_LENGTH ) { break ; } } /* * check and remove the dot punctuation after it */ for ( int j = isb . length ( ) - 1 ; j > 0 ; j -- ) { if ( isb . charAt ( j ) == ' ' ) { isb . deleteCharAt ( j ) ; } } return isb . toString ( ) ; }
the simple version of the next basic Latin fetch logic Just return the next Latin string with the keep punctuation after it
440
23
32,742
protected String nextLetterNumber ( int c ) throws IOException { //StringBuilder isb = new StringBuilder(); isb . clear ( ) ; isb . append ( ( char ) c ) ; int ch ; while ( ( ch = readNext ( ) ) != - 1 ) { if ( StringUtil . isWhitespace ( ch ) ) { pushBack ( ch ) ; break ; } if ( ! StringUtil . isLetterNumber ( ch ) ) { pushBack ( ch ) ; break ; } isb . append ( ( char ) ch ) ; } return isb . toString ( ) ; }
find the next other letter from the current position find the letter number from the current position count until the char in the specified position is not a letter number or whitespace
129
33
32,743
protected String nextOtherNumber ( int c ) throws IOException { //StringBuilder isb = new StringBuilder(); isb . clear ( ) ; isb . append ( ( char ) c ) ; int ch ; while ( ( ch = readNext ( ) ) != - 1 ) { if ( StringUtil . isWhitespace ( ch ) ) { pushBack ( ch ) ; break ; } if ( ! StringUtil . isOtherNumber ( ch ) ) { pushBack ( ch ) ; break ; } isb . append ( ( char ) ch ) ; } return isb . toString ( ) ; }
find the other number from the current position count until the char in the specified position is not a other number or whitespace
129
24
32,744
protected String nextCNNumeric ( char [ ] chars , int index ) throws IOException { //StringBuilder isb = new StringBuilder(); isb . clear ( ) ; isb . append ( chars [ index ] ) ; ctrlMask &= ~ ISegment . CHECK_CF_MASK ; //reset the fraction check mask. for ( int j = index + 1 ; j < chars . length ; j ++ ) { /* * check and deal with '分之' if the * current char is not a Chinese numeric. * (try to recognize a Chinese fraction) * * @added 2013-12-14 */ if ( NumericUtil . isCNNumeric ( chars [ j ] ) == - 1 ) { if ( j + 2 < chars . length && chars [ j ] == ' && chars [ j + 1 ] == ' /* check and make sure chars[j+2] is a chinese numeric. * or error will happen on situation like '四六分之' . * @added 2013-12-14 */ && NumericUtil . isCNNumeric ( chars [ j + 2 ] ) != - 1 ) { isb . append ( chars [ j ++ ] ) ; isb . append ( chars [ j ++ ] ) ; isb . append ( chars [ j ] ) ; //set the chinese fraction check mask. ctrlMask |= ISegment . CHECK_CF_MASK ; continue ; } else { break ; } } //append the buffer. isb . append ( chars [ j ] ) ; } return isb . toString ( ) ; }
find the Chinese number from the current position count until the char in the specified position is not a other number or whitespace
340
24
32,745
@ Override protected IWord getNextCJKWord ( int c , int pos ) throws IOException { String key = null ; char [ ] chars = nextCJKSentence ( c ) ; int cjkidx = 0 , ignidx = 0 , mnum = 0 ; IWord word = null ; ArrayList < IWord > mList = new ArrayList < IWord > ( 8 ) ; while ( cjkidx < chars . length ) { /// @Note added at 2017/04/29 /// check and append the single char word String sstr = String . valueOf ( chars [ cjkidx ] ) ; if ( dic . match ( ILexicon . CJK_WORD , sstr ) ) { IWord sWord = dic . get ( ILexicon . CJK_WORD , sstr ) . clone ( ) ; sWord . setPosition ( pos + cjkidx ) ; mList . add ( sWord ) ; } mnum = 0 ; isb . clear ( ) . append ( chars [ cjkidx ] ) ; //System.out.println("ignore idx: " + ignidx); for ( int j = 1 ; j < config . MAX_LENGTH && ( cjkidx + j ) < chars . length ; j ++ ) { isb . append ( chars [ cjkidx + j ] ) ; key = isb . toString ( ) ; if ( dic . match ( ILexicon . CJK_WORD , key ) ) { mnum = 1 ; ignidx = Math . max ( ignidx , cjkidx + j ) ; word = dic . get ( ILexicon . CJK_WORD , key ) . clone ( ) ; word . setPosition ( pos + cjkidx ) ; mList . add ( word ) ; } } /* * no matches here: * should the current character chars[cjkidx] be a single word ? * lets do the current check */ if ( mnum == 0 && ( cjkidx == 0 || cjkidx > ignidx ) ) { String temp = String . valueOf ( chars [ cjkidx ] ) ; if ( ! dic . match ( ILexicon . CJK_WORD , temp ) ) { word = new Word ( temp , ILexicon . UNMATCH_CJK_WORD ) ; word . setPosition ( pos + cjkidx ) ; mList . add ( word ) ; } } cjkidx ++ ; } /* * do all the words analysis * 1, clear the stop words * 1, check and append the pinyin or synonyms words */ for ( IWord w : mList ) { key = w . getValue ( ) ; if ( config . CLEAR_STOPWORD && dic . match ( ILexicon . STOP_WORD , key ) ) { continue ; } wordPool . add ( w ) ; appendWordFeatures ( w ) ; } //let gc do its work mList . clear ( ) ; mList = null ; return wordPool . size ( ) == 0 ? null : wordPool . remove ( ) ; }
get the next CJK word from the current position of the input stream and this function is the core part the most segmentation implements
686
26
32,746
private void process ( ) { if ( requestUri . length ( ) > 1 ) { parts = new ArrayList < String > ( 10 ) ; for ( int i = 1 ; i < requestUri . length ( ) ; ) { int sIdx = i ; int eIdx = requestUri . indexOf ( ' ' , sIdx + 1 ) ; //not matched or reach the end if ( eIdx == - 1 ) { parts . add ( requestUri . substring ( sIdx ) ) ; break ; } parts . add ( requestUri . substring ( sIdx , eIdx ) ) ; i = eIdx + 1 ; } /* * check and add a empty method name * with request style like /tokenizer/ */ if ( requestUri . charAt ( requestUri . length ( ) - 1 ) == ' ' ) { parts . add ( "" ) ; } int length = parts . size ( ) ; if ( length > 1 ) { IStringBuffer sb = new IStringBuffer ( ) ; for ( int i = 0 ; i < length - 1 ; i ++ ) { int l = sb . length ( ) ; sb . append ( parts . get ( i ) ) ; //make sure the first letter is uppercase char chr = sb . charAt ( l ) ; if ( chr >= 90 ) { chr -= 32 ; sb . set ( l , chr ) ; } } controller = sb . toString ( ) ; } method = parts . get ( length - 1 ) ; } }
do the request uri process
339
6
32,747
public String get ( int idx ) { if ( idx < 0 || idx >= parts . size ( ) ) { throw new IndexOutOfBoundsException ( ) ; } return parts . get ( idx ) ; }
the specifiled part of the request uri
48
10
32,748
private PathEntry getPathEntry ( UriEntry uri ) { PathEntry pathEntry = new PathEntry ( ContextRouter . MAP_PATH_TYPE , "default" ) ; int length = uri . getLength ( ) ; // like /a or / if ( length < 2 ) return pathEntry ; String requestUri = uri . getRequestUri ( ) ; String last_str = uri . get ( length - 1 ) ; if ( last_str . equals ( "*" ) || last_str . equals ( "" ) ) { // StringBuffer buffer = new StringBuffer(); // buffer.append('/'); // // for(int i = 0; i < length - 1; i++) // { // buffer.append(uri.get(i) + "/"); // } // position of last / charactor int lastPosition = requestUri . lastIndexOf ( ' ' ) ; pathEntry . type = ContextRouter . MATCH_PATH_TYPE ; pathEntry . key = requestUri . substring ( 0 , lastPosition + 1 ) ; // @TODO maybe we should get parameters to pathEntry } else { pathEntry . key = requestUri ; } return pathEntry ; }
get the final key with specified path
258
7
32,749
private void resizeTo ( int length ) { if ( length <= 0 ) throw new IllegalArgumentException ( "length <= 0" ) ; if ( length != buff . length ) { int len = ( length > buff . length ) ? buff . length : length ; //System.out.println("resize:"+length); char [ ] obuff = buff ; buff = new char [ length ] ; /*for ( int j = 0; j < len; j++ ) { buff[j] = obuff[j]; }*/ System . arraycopy ( obuff , 0 , buff , 0 , len ) ; } }
resize the buffer this will have to copy the old chars from the old buffer to the new buffer
131
20
32,750
public IStringBuffer append ( String str ) { if ( str == null ) throw new NullPointerException ( ) ; //check the necessary to resize the buffer. if ( count + str . length ( ) > buff . length ) { resizeTo ( ( count + str . length ( ) ) * 2 + 1 ) ; } for ( int j = 0 ; j < str . length ( ) ; j ++ ) { buff [ count ++ ] = str . charAt ( j ) ; } return this ; }
append a string to the buffer
106
6
32,751
public IStringBuffer append ( char [ ] chars , int start , int length ) { if ( chars == null ) throw new NullPointerException ( ) ; if ( start < 0 ) throw new IndexOutOfBoundsException ( ) ; if ( length <= 0 ) throw new IndexOutOfBoundsException ( ) ; if ( start + length > chars . length ) throw new IndexOutOfBoundsException ( ) ; //check the necessary to resize the buffer. if ( count + length > buff . length ) { resizeTo ( ( count + length ) * 2 + 1 ) ; } for ( int j = 0 ; j < length ; j ++ ) { buff [ count ++ ] = chars [ start + j ] ; } return this ; }
append parts of the chars to the buffer
156
8
32,752
public IStringBuffer append ( char [ ] chars , int start ) { append ( chars , start , chars . length - start ) ; return this ; }
append the rest of the chars to the buffer
32
9
32,753
public IStringBuffer append ( char c ) { if ( count == buff . length ) { resizeTo ( buff . length * 2 + 1 ) ; } buff [ count ++ ] = c ; return this ; }
append a char to the buffer
44
6
32,754
public char charAt ( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException ( "idx{" + idx + "} < 0" ) ; if ( idx >= count ) throw new IndexOutOfBoundsException ( "idx{" + idx + "} >= buffer.length" ) ; return buff [ idx ] ; }
get the char at a specified position in the buffer
82
10
32,755
public IStringBuffer deleteCharAt ( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException ( "idx < 0" ) ; if ( idx >= count ) throw new IndexOutOfBoundsException ( "idx >= buffer.length" ) ; //here we got a bug for j < count //change over it to count - 1 //thanks for the feedback of xuyijun@gmail.com //@date 2013-08-22 for ( int j = idx ; j < count - 1 ; j ++ ) { buff [ j ] = buff [ j + 1 ] ; } count -- ; return this ; }
delete the char at the specified position
141
7
32,756
public void set ( int idx , char chr ) { if ( idx < 0 ) throw new IndexOutOfBoundsException ( "idx < 0" ) ; if ( idx >= count ) throw new IndexOutOfBoundsException ( "idx >= buffer.length" ) ; buff [ idx ] = chr ; }
set the char at the specified index
73
7
32,757
protected IWord getNextTimeMergedWord ( IWord word , int eIdx ) throws IOException { int pIdx = TimeUtil . getDateTimeIndex ( word . getEntity ( eIdx ) ) ; if ( pIdx == TimeUtil . DATETIME_NONE ) { return null ; } IWord [ ] wMask = TimeUtil . createDateTimePool ( ) ; TimeUtil . fillDateTimePool ( wMask , pIdx , word ) ; IWord dWord = null ; int mergedNum = 0 ; while ( ( dWord = super . next ( ) ) != null ) { String [ ] entity = dWord . getEntity ( ) ; if ( entity == null ) { eWordPool . push ( dWord ) ; break ; } if ( ArrayUtil . startsWith ( "time.a" , entity ) > - 1 ) { if ( TimeUtil . DATETIME_NONE == TimeUtil . fillDateTimePool ( wMask , dWord ) ) { eWordPool . push ( dWord ) ; break ; } } else if ( ArrayUtil . startsWith ( "datetime.hi" , entity ) > - 1 ) { /* * check and merge the date time time part with a style * like 15:45 or 15:45:36 eg... */ TimeUtil . fillTimeToPool ( wMask , dWord . getValue ( ) ) ; } else if ( ArrayUtil . startsWith ( Entity . E_DATETIME_P , entity ) > - 1 ) { int tIdx = TimeUtil . fillDateTimePool ( wMask , dWord ) ; if ( tIdx == TimeUtil . DATETIME_NONE || wMask [ tIdx - 1 ] == null ) { eWordPool . push ( dWord ) ; break ; } } else { eWordPool . push ( dWord ) ; break ; } mergedNum ++ ; } if ( mergedNum == 0 ) { return null ; } buffer . clear ( ) ; for ( int i = 0 ; i < wMask . length ; i ++ ) { if ( wMask [ i ] == null ) { continue ; } if ( buffer . length ( ) > 0 && ( i + 1 ) < wMask . length ) { buffer . append ( ' ' ) ; } buffer . append ( wMask [ i ] . getValue ( ) ) ; } dWord = new Word ( buffer . toString ( ) , IWord . T_BASIC_LATIN ) ; dWord . setPosition ( word . getPosition ( ) ) ; dWord . setPartSpeech ( IWord . TIME_POSPEECH ) ; //check and define the entity buffer . clear ( ) . append ( "datetime." ) ; for ( int i = 0 ; i < wMask . length ; i ++ ) { if ( wMask [ i ] == null ) continue ; buffer . append ( TimeUtil . getTimeKey ( wMask [ i ] ) ) ; } dWord . setEntity ( new String [ ] { buffer . toString ( ) } ) ; return dWord ; }
get and return the next time merged date - time word
677
11
32,758
protected IWord getNextDatetimeWord ( IWord word , int entityIdx ) throws IOException { IWord dWord = super . next ( ) ; if ( dWord == null ) { return null ; } String [ ] entity = dWord . getEntity ( ) ; if ( entity == null ) { eWordPool . add ( dWord ) ; return null ; } int eIdx = 0 ; if ( ( eIdx = ArrayUtil . startsWith ( "datetime.h" , entity ) ) > - 1 ) { // do nothing here } else if ( ( eIdx = ArrayUtil . startsWith ( "time.a" , entity ) ) > - 1 || ( eIdx = ArrayUtil . startsWith ( Entity . E_DATETIME_P , entity ) ) > - 1 ) { /* * @Note: added at 2017/04/01 * 1, A word start with time.h or datetime.h could be merged * 2, if the new time merged word could not be merged with the origin word * and we should put the dWord to the first of the eWordPool cuz #getNextTimeMergedWord * may append some IWord to the end of eWordPool */ IWord mWord = getNextTimeMergedWord ( dWord , eIdx ) ; if ( mWord == null ) { eWordPool . addFirst ( dWord ) ; return null ; } String mEntity = mWord . getEntity ( 0 ) ; if ( ! ( mEntity . contains ( ".h" ) || mEntity . contains ( ".a" ) ) ) { eWordPool . addFirst ( mWord ) ; return null ; } eIdx = 0 ; dWord = mWord ; entity = dWord . getEntity ( ) ; } else { eWordPool . add ( dWord ) ; return null ; } buffer . clear ( ) . append ( word . getValue ( ) ) . append ( ' ' ) . append ( dWord . getValue ( ) ) ; dWord = new Word ( buffer . toString ( ) , IWord . T_BASIC_LATIN ) ; dWord . setPosition ( word . getPosition ( ) ) ; dWord . setPartSpeech ( IWord . TIME_POSPEECH ) ; //re-define the entity //int sIdx = entity.indexOf('.') + 1; // int sIdx = entity[eIdx].charAt(0) == 't' ? 5 : 9; int sIdx = 9 ; // datetime buffer . clear ( ) . append ( word . getEntity ( 0 ) ) . append ( entity [ eIdx ] . substring ( sIdx ) ) ; dWord . addEntity ( buffer . toString ( ) ) ; return dWord ; }
get and return the next date - time word
605
9
32,759
private IWord getNumericUnitComposedWord ( String numeric , IWord unitWord ) { IStringBuffer sb = new IStringBuffer ( ) ; sb . clear ( ) . append ( numeric ) . append ( unitWord . getValue ( ) ) ; IWord wd = new Word ( sb . toString ( ) , IWord . T_CJK_WORD ) ; String [ ] entity = unitWord . getEntity ( ) ; int eIdx = ArrayUtil . startsWith ( Entity . E_TIME_P , entity ) ; if ( eIdx > - 1 ) { sb . clear ( ) . append ( entity [ eIdx ] . replace ( "time." , "datetime." ) ) ; } else { sb . clear ( ) . append ( Entity . E_NUC_PREFIX ) . append ( unitWord . getEntity ( 0 ) ) ; } wd . setEntity ( new String [ ] { sb . toString ( ) } ) ; wd . setPartSpeech ( IWord . QUANTIFIER ) ; sb . clear ( ) ; sb = null ; return wd ; }
internal method to define the composed entity for numeric and unit word composed word
252
14
32,760
public List < Issue > getIssuesBySummary ( String projectKey , String summaryField ) throws RedmineException { if ( ( projectKey != null ) && ( projectKey . length ( ) > 0 ) ) { return transport . getObjectsList ( Issue . class , new BasicNameValuePair ( "subject" , summaryField ) , new BasicNameValuePair ( "project_id" , projectKey ) ) ; } else { return transport . getObjectsList ( Issue . class , new BasicNameValuePair ( "subject" , summaryField ) ) ; } }
There could be several issues with the same summary so the method returns List .
123
15
32,761
public List < SavedQuery > getSavedQueries ( String projectKey ) throws RedmineException { Set < NameValuePair > params = new HashSet <> ( ) ; if ( ( projectKey != null ) && ( projectKey . length ( ) > 0 ) ) { params . add ( new BasicNameValuePair ( "project_id" , projectKey ) ) ; } return transport . getObjectsList ( SavedQuery . class , params ) ; }
Get saved queries for the given project available to the current user .
101
13
32,762
public static < T > void addIfNotNull ( JSONWriter writer , String field , T value , JsonObjectWriter < T > objWriter ) throws JSONException { if ( value == null ) return ; writer . key ( field ) ; writer . object ( ) ; objWriter . write ( writer , value ) ; writer . endObject ( ) ; }
Adds an object if object is not null .
74
9
32,763
public static < T > void addScalarArray ( JSONWriter writer , String field , Collection < T > items , JsonObjectWriter < T > objWriter ) throws JSONException { writer . key ( field ) ; writer . array ( ) ; for ( T item : items ) { objWriter . write ( writer , item ) ; } writer . endArray ( ) ; }
Adds a list of scalar values .
79
8
32,764
public URI addAPIKey ( String uri ) { try { final URIBuilder builder = new URIBuilder ( uri ) ; if ( apiAccessKey != null ) { builder . setParameter ( "key" , apiAccessKey ) ; } return builder . build ( ) ; } catch ( URISyntaxException e ) { throw new RedmineInternalError ( e ) ; } }
Adds API key to URI if the key is specified
80
10
32,765
public static SSLSocketFactory createSocketFactory ( Collection < KeyStore > extraStores ) throws KeyStoreException , KeyManagementException { final Collection < X509TrustManager > managers = new ArrayList <> ( ) ; for ( KeyStore ks : extraStores ) { addX509Managers ( managers , ks ) ; } /* Add default manager. */ addX509Managers ( managers , null ) ; final TrustManager tm = new CompositeTrustManager ( managers ) ; try { final SSLContext ctx = SSLContext . getInstance ( "SSL" ) ; ctx . init ( null , new TrustManager [ ] { tm } , null ) ; return new SSLSocketFactory ( ctx ) ; } catch ( NoSuchAlgorithmException e ) { throw new Error ( "No SSL protocols supported :(" , e ) ; } }
Creates a new SSL socket factory which supports both system - installed keys and all additional keys in the provided keystores .
180
24
32,766
private static void addX509Managers ( final Collection < X509TrustManager > managers , KeyStore ks ) throws KeyStoreException , Error { try { final TrustManagerFactory tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; tmf . init ( ks ) ; for ( TrustManager tm : tmf . getTrustManagers ( ) ) { if ( tm instanceof X509TrustManager ) { managers . add ( ( X509TrustManager ) tm ) ; } } } catch ( NoSuchAlgorithmException e ) { throw new Error ( "Default trust manager algorithm is not supported!" , e ) ; } }
Adds X509 keystore - backed trust manager into the list of managers .
147
15
32,767
public < T > T addObject ( T object , NameValuePair ... params ) throws RedmineException { final EntityConfig < T > config = getConfig ( object . getClass ( ) ) ; if ( config . writer == null ) { throw new RuntimeException ( "can't create object: writer is not implemented or is not registered in RedmineJSONBuilder for object " + object ) ; } URI uri = getURIConfigurator ( ) . getObjectsURI ( object . getClass ( ) , params ) ; HttpPost httpPost = new HttpPost ( uri ) ; String body = RedmineJSONBuilder . toSimpleJSON ( config . singleObjectName , object , config . writer ) ; setEntity ( httpPost , body ) ; String response = send ( httpPost ) ; logger . debug ( response ) ; return parseResponse ( response , config . singleObjectName , config . parser ) ; }
Performs an add object request .
195
7
32,768
public < T > void deleteChildId ( Class < ? > parentClass , String parentId , T object , Integer value ) throws RedmineException { URI uri = getURIConfigurator ( ) . getChildIdURI ( parentClass , parentId , object . getClass ( ) , value ) ; HttpDelete httpDelete = new HttpDelete ( uri ) ; String response = send ( httpDelete ) ; logger . debug ( response ) ; }
Performs delete child Id request .
98
7
32,769
public < T extends Identifiable > void deleteObject ( Class < T > classs , String id ) throws RedmineException { final URI uri = getURIConfigurator ( ) . getObjectURI ( classs , id ) ; final HttpDelete http = new HttpDelete ( uri ) ; send ( http ) ; }
Deletes an object .
72
5
32,770
public < R > R download ( String uri , ContentHandler < BasicHttpResponse , R > handler ) throws RedmineException { final URI requestUri = configurator . addAPIKey ( uri ) ; final HttpGet request = new HttpGet ( requestUri ) ; if ( onBehalfOfUser != null ) { request . addHeader ( "X-Redmine-Switch-User" , onBehalfOfUser ) ; } return errorCheckingCommunicator . sendRequest ( request , handler ) ; }
Downloads redmine content .
112
6
32,771
public < T > T getChildEntry ( Class < ? > parentClass , String parentId , Class < T > classs , String childId , NameValuePair ... params ) throws RedmineException { final EntityConfig < T > config = getConfig ( classs ) ; final URI uri = getURIConfigurator ( ) . getChildIdURI ( parentClass , parentId , classs , childId , params ) ; HttpGet http = new HttpGet ( uri ) ; String response = send ( http ) ; return parseResponse ( response , config . singleObjectName , config . parser ) ; }
Delivers a single child entry by its identifier .
133
10
32,772
public Project addTrackers ( Collection < Tracker > trackers ) { if ( ! storage . isPropertySet ( TRACKERS ) ) //checks because trackers storage is not created for new projects storage . set ( TRACKERS , new HashSet <> ( ) ) ; storage . get ( TRACKERS ) . addAll ( trackers ) ; return this ; }
Adds the specified trackers to this project . If this project is created or updated on the redmine server each tracker id must be a valid tracker on the server .
77
33
32,773
public static RedmineManager createUnauthenticated ( String uri , HttpClient httpClient ) { return createWithUserAuth ( uri , null , null , httpClient ) ; }
Creates a non - authenticating redmine manager .
39
11
32,774
public static RedmineManager createWithUserAuth ( String uri , String login , String password ) { return createWithUserAuth ( uri , login , password , createDefaultHttpClient ( uri ) ) ; }
Creates a new RedmineManager with user - based authentication .
45
13
32,775
public static RedmineManager createWithUserAuth ( String uri , String login , String password , HttpClient httpClient ) { final Transport transport = new Transport ( new URIConfigurator ( uri , null ) , httpClient ) ; transport . setCredentials ( login , password ) ; return new RedmineManager ( transport ) ; }
Creates a new redmine managen with user - based authentication .
74
14
32,776
public void update ( ) throws RedmineException { String urlSafeTitle = getUrlSafeString ( getTitle ( ) ) ; transport . updateChildEntry ( Project . class , getProjectKey ( ) , this , urlSafeTitle ) ; }
projectKey must be set before calling this . Version must be set to the latest version of the document .
50
21
32,777
private InputStream decodeStream ( String encoding , InputStream initialStream ) throws IOException { if ( encoding == null ) return initialStream ; if ( "gzip" . equals ( encoding ) ) return new GZIPInputStream ( initialStream ) ; if ( "deflate" . equals ( encoding ) ) return new InflaterInputStream ( initialStream ) ; throw new IOException ( "Unsupported transport encoding " + encoding ) ; }
Decodes a transport stream .
92
6
32,778
public static void updateCollections ( PropertyStorage storage , Transport transport ) { storage . getProperties ( ) . forEach ( e -> { if ( Collection . class . isAssignableFrom ( e . getKey ( ) . getType ( ) ) ) { // found a collection in properties ( ( Collection ) e . getValue ( ) ) . forEach ( i -> { if ( i instanceof FluentStyle ) { ( ( FluentStyle ) i ) . setTransport ( transport ) ; } } ) ; } } ) ; }
go over all properties in the storage and set transport on FluentStyle instances inside collections if any . only process one level without recursion - to avoid potential cycles and such .
114
35
32,779
public static void writeProject ( JSONWriter writer , Project project ) throws IllegalArgumentException , JSONException { /* Validate project */ if ( project . getName ( ) == null ) throw new IllegalArgumentException ( "Project name must be set to create a new project" ) ; if ( project . getIdentifier ( ) == null ) throw new IllegalArgumentException ( "Project identifier must be set to create a new project" ) ; writeProject ( project , writer ) ; }
Writes a create project request .
101
7
32,780
public static < T > String toSimpleJSON ( String tag , T object , JsonObjectWriter < T > writer ) throws RedmineInternalError { final StringWriter swriter = new StringWriter ( ) ; final JSONWriter jsWriter = new JSONWriter ( swriter ) ; try { jsWriter . object ( ) ; jsWriter . key ( tag ) ; jsWriter . object ( ) ; writer . write ( jsWriter , object ) ; jsWriter . endObject ( ) ; jsWriter . endObject ( ) ; } catch ( JSONException e ) { throw new RedmineInternalError ( "Unexpected JSONException" , e ) ; } return swriter . toString ( ) ; }
Converts object to a simple json .
143
8
32,781
public static Router getRouter ( Class < ? extends Router > routerType ) { return routers . computeIfAbsent ( routerType , Routers :: create ) ; }
Get router instance by a given router class . The class should have a default constructor . Otherwise no router can be created
35
23
32,782
public Mono < Void > send ( GatewayMessage response ) { return Mono . defer ( ( ) -> outbound . sendObject ( Mono . just ( response ) . map ( codec :: encode ) . map ( TextWebSocketFrame :: new ) ) . then ( ) . doOnSuccessOrError ( ( avoid , th ) -> logSend ( response , th ) ) ) ; }
Method to send normal response .
78
6
32,783
public Mono < Void > onClose ( Disposable disposable ) { return Mono . create ( sink -> inbound . withConnection ( connection -> connection . onDispose ( disposable ) . onTerminate ( ) . subscribe ( sink :: success , sink :: error , sink :: success ) ) ) ; }
Lambda setter for reacting on channel close occurrence .
62
12
32,784
public boolean dispose ( Long streamId ) { boolean result = false ; if ( streamId != null ) { Disposable disposable = subscriptions . remove ( streamId ) ; result = disposable != null ; if ( result ) { LOGGER . debug ( "Dispose subscription by sid={}, session={}" , streamId , id ) ; disposable . dispose ( ) ; } } return result ; }
Disposing stored subscription by given stream id .
81
9
32,785
@ Override public Mono < ServiceDiscovery > start ( ) { return Mono . defer ( ( ) -> { Map < String , String > metadata = endpoint != null ? Collections . singletonMap ( endpoint . id ( ) , ClusterMetadataCodec . encodeMetadata ( endpoint ) ) : Collections . emptyMap ( ) ; ClusterConfig clusterConfig = copyFrom ( this . clusterConfig ) . addMetadata ( metadata ) . build ( ) ; ScalecubeServiceDiscovery serviceDiscovery = new ScalecubeServiceDiscovery ( this , clusterConfig ) ; return Cluster . join ( clusterConfig ) . doOnSuccess ( cluster -> serviceDiscovery . cluster = cluster ) . thenReturn ( serviceDiscovery ) ; } ) ; }
Starts scalecube service discoevery . Joins a cluster with local services as metadata .
153
19
32,786
private static Class < ? > parameterizedReturnType ( Method method ) { Type type = method . getGenericReturnType ( ) ; if ( type instanceof ParameterizedType ) { try { return Class . forName ( ( ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ) . getTypeName ( ) ) ; } catch ( ClassNotFoundException e ) { return Object . class ; } } else { return Object . class ; } }
extract parameterized return value of a method .
103
10
32,787
public void calculate ( ServiceMessage message ) { // client to service eval ( message . header ( SERVICE_RECV_TIME ) , message . header ( CLIENT_SEND_TIME ) , ( v1 , v2 ) -> clientToServiceTimer . update ( v1 - v2 , TimeUnit . MILLISECONDS ) ) ; // service to client eval ( message . header ( CLIENT_RECV_TIME ) , message . header ( SERVICE_SEND_TIME ) , ( v1 , v2 ) -> serviceToClientTimer . update ( v1 - v2 , TimeUnit . MILLISECONDS ) ) ; }
Calculates latencies by the headers into received message .
134
12
32,788
public static Builder from ( ServiceMessage message ) { return ServiceMessage . builder ( ) . data ( message . data ( ) ) . headers ( message . headers ( ) ) ; }
Instantiates new message with the same data and headers as at given message .
37
16
32,789
public static ServiceMessage error ( int errorType , int errorCode , String errorMessage ) { return ServiceMessage . builder ( ) . qualifier ( Qualifier . asError ( errorType ) ) . data ( new ErrorData ( errorCode , errorMessage ) ) . build ( ) ; }
Instantiates new message with error qualifier for given error type and specified error code and message .
59
19
32,790
void setHeaders ( Map < String , String > headers ) { this . headers = Collections . unmodifiableMap ( new HashMap <> ( headers ) ) ; }
Sets headers for deserialization purpose .
36
9
32,791
public String header ( String name ) { Objects . requireNonNull ( name ) ; return headers . get ( name ) ; }
Returns header value by given header name .
26
8
32,792
public boolean isError ( ) { String qualifier = qualifier ( ) ; return qualifier != null && qualifier . contains ( Qualifier . ERROR_NAMESPACE ) ; }
Describes whether the message is an error .
35
9
32,793
public int errorType ( ) { if ( ! isError ( ) ) { throw new IllegalStateException ( "Message is not an error" ) ; } try { return Integer . parseInt ( Qualifier . getQualifierAction ( qualifier ( ) ) ) ; } catch ( NumberFormatException e ) { throw new IllegalStateException ( "Error type must be a number" ) ; } }
Returns error type . Error type is an identifier of a group of errors .
81
15
32,794
public static io . scalecube . transport . Address toAddress ( io . scalecube . services . transport . api . Address address ) { return io . scalecube . transport . Address . create ( address . host ( ) , address . port ( ) ) ; }
Converts one address to another .
57
7
32,795
public static io . scalecube . transport . Address [ ] toAddresses ( Address [ ] addresses ) { return Arrays . stream ( addresses ) . map ( ClusterAddresses :: toAddress ) . toArray ( io . scalecube . transport . Address [ ] :: new ) ; }
Converts one address array to another address array .
61
10
32,796
protected final HttpServer prepareHttpServer ( LoopResources loopResources , int port , GatewayMetrics metrics ) { return HttpServer . create ( ) . tcpConfiguration ( tcpServer -> { if ( loopResources != null ) { tcpServer = tcpServer . runOn ( loopResources ) ; } if ( metrics != null ) { tcpServer = tcpServer . doOnConnection ( connection -> { metrics . incConnection ( ) ; connection . onDispose ( metrics :: decConnection ) ; } ) ; } return tcpServer . addressSupplier ( ( ) -> new InetSocketAddress ( port ) ) ; } ) ; }
Builds generic http server with given parameters .
129
9
32,797
private < T > T encodeAndTransform ( ClientMessage message , BiFunction < ByteBuf , ByteBuf , T > transformer ) throws MessageCodecException { ByteBuf dataBuffer = Unpooled . EMPTY_BUFFER ; ByteBuf headersBuffer = Unpooled . EMPTY_BUFFER ; if ( message . hasData ( ByteBuf . class ) ) { dataBuffer = message . data ( ) ; } else if ( message . hasData ( ) ) { dataBuffer = ByteBufAllocator . DEFAULT . buffer ( ) ; try { dataCodec . encode ( new ByteBufOutputStream ( dataBuffer ) , message . data ( ) ) ; } catch ( Throwable ex ) { ReferenceCountUtil . safestRelease ( dataBuffer ) ; LOGGER . error ( "Failed to encode data on: {}, cause: {}" , message , ex ) ; throw new MessageCodecException ( "Failed to encode data on message q=" + message . qualifier ( ) , ex ) ; } } if ( ! message . headers ( ) . isEmpty ( ) ) { headersBuffer = ByteBufAllocator . DEFAULT . buffer ( ) ; try { headersCodec . encode ( new ByteBufOutputStream ( headersBuffer ) , message . headers ( ) ) ; } catch ( Throwable ex ) { ReferenceCountUtil . safestRelease ( headersBuffer ) ; ReferenceCountUtil . safestRelease ( dataBuffer ) ; // release data as well LOGGER . error ( "Failed to encode headers on: {}, cause: {}" , message , ex ) ; throw new MessageCodecException ( "Failed to encode headers on message q=" + message . qualifier ( ) , ex ) ; } } return transformer . apply ( dataBuffer , headersBuffer ) ; }
Encoder function .
381
4
32,798
public static Address from ( String hostAndPort ) { String [ ] split = hostAndPort . split ( ":" ) ; if ( split . length != 2 ) { throw new IllegalArgumentException ( ) ; } String host = split [ 0 ] ; int port = Integer . parseInt ( split [ 1 ] ) ; return new Address ( host , port ) ; }
Create address .
77
3
32,799
public static String asString ( String namespace , String action ) { return DELIMITER + namespace + DELIMITER + action ; }
Builds qualifier string out of given namespace and action .
29
11