idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
10,900
public static Long getValue ( final Long value , final Long defaultValue ) { return value == null ? defaultValue : value ; }
Returns defaultValue if given value is null ; else returns it self .
27
14
10,901
public boolean read ( ) throws IOException { valid = false ; File file = new File ( filename ) ; FileReader reader = new FileReader ( file ) ; if ( file . exists ( ) ) { // Load the file contents contents = getContents ( reader , "\n" ) ; if ( contents != null ) valid = true ; else logger . severe ( "Unable to read file contents: " + file . getAbsolutePath ( ) ) ; } else { logger . severe ( "File does not exist: " + file . getAbsolutePath ( ) ) ; } try { if ( reader != null ) reader . close ( ) ; } catch ( IOException e ) { } return valid ; }
Reads the contents of the file .
147
8
10,902
public boolean read ( InputStream stream ) throws IOException { valid = false ; InputStreamReader reader = new InputStreamReader ( stream ) ; // Load the file contents contents = getContents ( reader , "\n" ) ; if ( contents != null ) valid = true ; else logger . severe ( "Unable to read file contents: " + filename ) ; try { if ( reader != null ) reader . close ( ) ; } catch ( IOException e ) { } return valid ; }
Reads the contents of the given stream .
101
9
10,903
private String getContents ( Reader reader , String terminator ) throws IOException { String line = null ; StringBuffer buff = new StringBuffer ( ) ; BufferedReader in = new BufferedReader ( reader ) ; while ( ( line = in . readLine ( ) ) != null ) { buff . append ( line ) ; if ( terminator != null ) buff . append ( terminator ) ; } reader . close ( ) ; return buff . toString ( ) ; }
Read the contents of the file using the given reader .
98
11
10,904
private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; type = null ; types = null ; }
Explicitly set all transient fields .
36
8
10,905
public void generatePdf ( OutputStream out , List < Map < String , Object > > rows , List < ColumnDef > columns ) { try { Document document = new Document ( ) ; PdfWriter . getInstance ( document , out ) ; if ( columns == null ) { if ( rows . size ( ) > 0 ) return ; columns = new ArrayList < ColumnDef > ( CollectionUtils . collect ( rows . get ( 0 ) . keySet ( ) , new Transformer ( ) { @ Override public Object transform ( final Object input ) { return new ColumnDef ( ) { { setName ( ( String ) input ) ; } } ; } } ) ) ; } if ( columns . size ( ) > 14 ) document . setPageSize ( PageSize . A1 ) ; else if ( columns . size ( ) > 10 ) document . setPageSize ( PageSize . A2 ) ; else if ( columns . size ( ) > 7 ) document . setPageSize ( PageSize . A3 ) ; else document . setPageSize ( PageSize . A4 ) ; document . open ( ) ; Font font = FontFactory . getFont ( FontFactory . COURIER , 8 , Font . NORMAL , BaseColor . BLACK ) ; Font headerFont = FontFactory . getFont ( FontFactory . COURIER , 8 , Font . BOLD , BaseColor . BLACK ) ; int size = columns . size ( ) ; PdfPTable table = new PdfPTable ( size ) ; for ( ColumnDef column : columns ) { PdfPCell c1 = new PdfPCell ( new Phrase ( column . getName ( ) , headerFont ) ) ; c1 . setHorizontalAlignment ( Element . ALIGN_CENTER ) ; table . addCell ( c1 ) ; } table . setHeaderRows ( 1 ) ; if ( rows != null ) for ( Map < String , Object > row : rows ) { for ( ColumnDef column : columns ) { table . addCell ( new Phrase ( String . valueOf ( row . get ( column . getName ( ) ) ) , font ) ) ; } } document . add ( table ) ; document . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Takes the output and transforms it into a PDF file .
486
12
10,906
public void generateCsv ( OutputStream out , List < Map < String , Object > > rows , List < ColumnDef > columns ) { ICsvMapWriter csvWriter = null ; try { csvWriter = new CsvMapWriter ( new OutputStreamWriter ( out ) , CsvPreference . STANDARD_PREFERENCE ) ; // the header elements are used to map the bean values to each column (names must match) String [ ] header = new String [ ] { } ; CellProcessor [ ] processors = new CellProcessor [ ] { } ; if ( columns != null ) { header = ( String [ ] ) CollectionUtils . collect ( columns , new Transformer ( ) { @ Override public Object transform ( Object input ) { ColumnDef column = ( ColumnDef ) input ; return column . getName ( ) ; } } ) . toArray ( new String [ 0 ] ) ; processors = ( CellProcessor [ ] ) CollectionUtils . collect ( columns , new Transformer ( ) { @ Override public Object transform ( Object input ) { return new Optional ( ) ; } } ) . toArray ( new CellProcessor [ 0 ] ) ; } else if ( rows . size ( ) > 0 ) { header = new ArrayList < String > ( rows . get ( 0 ) . keySet ( ) ) . toArray ( new String [ 0 ] ) ; processors = ( CellProcessor [ ] ) CollectionUtils . collect ( rows . get ( 0 ) . keySet ( ) , new Transformer ( ) { @ Override public Object transform ( Object input ) { return new Optional ( ) ; } } ) . toArray ( new CellProcessor [ 0 ] ) ; } if ( header . length > 0 ) csvWriter . writeHeader ( header ) ; if ( rows != null ) for ( Map < String , Object > row : rows ) { csvWriter . write ( row , header , processors ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; //To change body of catch statement use File | Settings | File Templates. } finally { if ( csvWriter != null ) { try { csvWriter . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; //To change body of catch statement use File | Settings | File Templates. } } } }
Takes the output and transforms it into a csv file .
501
13
10,907
public void generateXls ( OutputStream out , List < Map < String , Object > > rows , List < ColumnDef > columns ) { try { Workbook wb = new HSSFWorkbook ( ) ; // or new XSSFWorkbook(); String safeName = WorkbookUtil . createSafeSheetName ( "Report" ) ; // returns " O'Brien's sales " Sheet reportSheet = wb . createSheet ( safeName ) ; short rowc = 0 ; Row nrow = reportSheet . createRow ( rowc ++ ) ; short cellc = 0 ; if ( rows == null ) return ; if ( columns == null && rows . size ( ) > 0 ) { columns = new ArrayList < ColumnDef > ( CollectionUtils . collect ( rows . get ( 0 ) . keySet ( ) , new Transformer ( ) { @ Override public Object transform ( final Object input ) { return new ColumnDef ( ) { { setName ( ( String ) input ) ; } } ; } } ) ) ; } if ( columns != null ) { for ( ColumnDef column : columns ) { Cell cell = nrow . createCell ( cellc ++ ) ; cell . setCellValue ( column . getName ( ) ) ; } } for ( Map < String , Object > row : rows ) { nrow = reportSheet . createRow ( rowc ++ ) ; cellc = 0 ; for ( ColumnDef column : columns ) { Cell cell = nrow . createCell ( cellc ++ ) ; cell . setCellValue ( String . valueOf ( row . get ( column . getName ( ) ) ) ) ; } } wb . write ( out ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; //To change body of catch statement use File | Settings | File Templates. } }
Takes the output and transforms it into a Excel file .
394
12
10,908
private void readPackageListFromFile ( String path , DocFile pkgListPath ) throws Fault { DocFile file = pkgListPath . resolve ( DocPaths . PACKAGE_LIST ) ; if ( ! ( file . isAbsolute ( ) || linkoffline ) ) { file = file . resolveAgainst ( DocumentationTool . Location . DOCUMENTATION_OUTPUT ) ; } try { if ( file . exists ( ) && file . canRead ( ) ) { boolean pathIsRelative = ! DocFile . createFileForInput ( configuration , path ) . isAbsolute ( ) && ! isUrl ( path ) ; readPackageList ( file . openInputStream ( ) , path , pathIsRelative ) ; } else { throw new Fault ( configuration . getText ( "doclet.File_error" , file . getPath ( ) ) , null ) ; } } catch ( IOException exc ) { throw new Fault ( configuration . getText ( "doclet.File_error" , file . getPath ( ) ) , exc ) ; } }
Read the package - list file which is available locally .
226
11
10,909
private void sort ( List < ClassDoc > list ) { List < ClassDoc > classes = new ArrayList < ClassDoc > ( ) ; List < ClassDoc > interfaces = new ArrayList < ClassDoc > ( ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { ClassDoc cd = list . get ( i ) ; if ( cd . isClass ( ) ) { classes . add ( cd ) ; } else { interfaces . add ( cd ) ; } } list . clear ( ) ; list . addAll ( classes ) ; list . addAll ( interfaces ) ; }
Sort the given mixed list of classes and interfaces to a list of classes followed by interfaces traversed . Don t sort alphabetically .
128
26
10,910
public static < T > T runCallableWithCpuCores ( Callable < T > task , int cpuCores ) throws ExecutionException , InterruptedException { ForkJoinPool forkJoinPool = new ForkJoinPool ( cpuCores ) ; return forkJoinPool . submit ( task ) . get ( ) ; }
Creates a custom thread pool that are executed in parallel processes with the given number of the cpu cores
67
20
10,911
public static < T > T runAsyncSupplierWithCpuCores ( Supplier < T > supplier , int cpuCores ) throws ExecutionException , InterruptedException { ForkJoinPool forkJoinPool = new ForkJoinPool ( cpuCores ) ; CompletableFuture < T > future = CompletableFuture . supplyAsync ( supplier , forkJoinPool ) ; return future . get ( ) ; }
Creates a custom thread pool that are executed in parallel processes with the will run with the given number of the cpu cores
85
24
10,912
public static Thread [ ] resolveRunningThreads ( ) { final Set < Thread > threadSet = Thread . getAllStackTraces ( ) . keySet ( ) ; final Thread [ ] threadArray = threadSet . toArray ( new Thread [ threadSet . size ( ) ] ) ; return threadArray ; }
Finds all threads the are currently running .
65
9
10,913
public final Trace alert ( Class < ? > c , String message ) { return _trace . alert ( c , message ) ; }
Reports an error condition .
27
5
10,914
public Iterable < DFactory > queryByBaseUrl ( java . lang . String baseUrl ) { return queryByField ( null , DFactoryMapper . Field . BASEURL . getFieldName ( ) , baseUrl ) ; }
query - by method for field baseUrl
49
8
10,915
public Iterable < DFactory > queryByClientId ( java . lang . String clientId ) { return queryByField ( null , DFactoryMapper . Field . CLIENTID . getFieldName ( ) , clientId ) ; }
query - by method for field clientId
49
8
10,916
public Iterable < DFactory > queryByClientSecret ( java . lang . String clientSecret ) { return queryByField ( null , DFactoryMapper . Field . CLIENTSECRET . getFieldName ( ) , clientSecret ) ; }
query - by method for field clientSecret
51
8
10,917
private Sentence constructSentence ( List < Token > tokens ) throws IOException { Sentence sentence ; try { sentence = new SimpleSentence ( tokens , strict ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( e . getMessage ( ) ) ; } return sentence ; }
Construct a sentence . If strictness is used and invariants do not hold convert the exception to an IOException .
63
23
10,918
public boolean checkAccess ( AccessFlags flags ) { boolean isPublic = flags . is ( AccessFlags . ACC_PUBLIC ) ; boolean isProtected = flags . is ( AccessFlags . ACC_PROTECTED ) ; boolean isPrivate = flags . is ( AccessFlags . ACC_PRIVATE ) ; boolean isPackage = ! ( isPublic || isProtected || isPrivate ) ; if ( ( showAccess == AccessFlags . ACC_PUBLIC ) && ( isProtected || isPrivate || isPackage ) ) return false ; else if ( ( showAccess == AccessFlags . ACC_PROTECTED ) && ( isPrivate || isPackage ) ) return false ; else if ( ( showAccess == 0 ) && ( isPrivate ) ) return false ; else return true ; }
Checks access of class field or method .
164
9
10,919
public static boolean matchProduces ( InternalRoute route , InternalRequest < ? > request ) { if ( nonEmpty ( request . getAccept ( ) ) ) { List < MediaType > matchedAcceptTypes = getAcceptedMediaTypes ( route . getProduces ( ) , request . getAccept ( ) ) ; if ( nonEmpty ( matchedAcceptTypes ) ) { request . setMatchedAccept ( matchedAcceptTypes . get ( 0 ) ) ; return true ; } } return false ; }
Matches route produces configurer and Accept - header in an incoming provider
101
14
10,920
public static boolean matchConsumes ( InternalRoute route , InternalRequest < ? > request ) { if ( route . getConsumes ( ) . contains ( WILDCARD ) ) { return true ; } return route . getConsumes ( ) . contains ( request . getContentType ( ) ) ; }
Matches route consumes configurer and Content - Type header in an incoming provider
63
15
10,921
public static byte [ ] getBytes ( final InputStream sourceInputStream ) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; for ( int len = 0 ; ( len = sourceInputStream . read ( buffer ) ) != - 1 ; ) { byteArrayOutputStream . write ( buffer , 0 , len ) ; } byte [ ] arrayOfByte = byteArrayOutputStream . toByteArray ( ) ; return arrayOfByte ; }
Get bytes from given input stream .
114
7
10,922
public static boolean write ( final InputStream sourceInputStream , final OutputStream destinationOutputStream ) throws IOException { byte [ ] buffer = buildBuffer ( BUFFER_SIZE ) ; for ( int len = 0 ; ( len = sourceInputStream . read ( buffer ) ) != - 1 ; ) { destinationOutputStream . write ( buffer , 0 , len ) ; } destinationOutputStream . flush ( ) ; return true ; }
Write source input stream bytes into destination output stream .
88
10
10,923
public static boolean write ( final byte [ ] sourceBytes , final OutputStream destinationOutputStream ) throws IOException { BufferedOutputStream bufferedOutputStream = new BufferedOutputStream ( destinationOutputStream ) ; bufferedOutputStream . write ( sourceBytes , 0 , sourceBytes . length ) ; bufferedOutputStream . flush ( ) ; return true ; }
Write source bytes into destination output stream .
74
8
10,924
public < T extends DataObject > List < T > asList ( Class < T > type ) throws InstantiationException , IllegalAccessException { Map < String , Field > fields = new HashMap < String , Field > ( ) ; for ( String column : columns ) try { fields . put ( column , Beans . getKnownField ( type , column ) ) ; } catch ( Exception x ) { } List < T > list = new ArrayList < T > ( ) ; for ( Object [ ] row : rows ) { T object = type . newInstance ( ) ; for ( int i = 0 ; i < row . length ; ++ i ) { Field field = fields . get ( columns [ i ] ) ; if ( field != null ) { Beans . setValue ( object , field , row [ i ] ) ; } } list . add ( object ) ; } return list ; }
Retrieves the contents of this result set as a List of DataObjects .
184
17
10,925
public CachedResultSet rename ( String ... names ) { for ( int i = 0 ; i < names . length ; ++ i ) { this . columns [ i ] = names [ i ] ; } return this ; }
Renames the columns of a CachedResultSet .
46
11
10,926
public Map < String , Integer > buildIndex ( ) { Map < String , Integer > index = new HashMap < String , Integer > ( ) ; for ( int i = 0 ; i < columns . length ; ++ i ) { index . put ( columns [ i ] , i ) ; } return index ; }
Builds a name - to - column index for quick access to data by columm names .
65
19
10,927
@ Programmatic public Paperclip attach ( final DocumentAbstract documentAbstract , final String roleName , final Object attachTo ) { Paperclip paperclip = findByDocumentAndAttachedToAndRoleName ( documentAbstract , attachTo , roleName ) ; if ( paperclip != null ) { return paperclip ; } final Class < ? extends Paperclip > subtype = subtypeClassFor ( attachTo ) ; paperclip = repositoryService . instantiate ( subtype ) ; paperclip . setDocument ( documentAbstract ) ; paperclip . setRoleName ( roleName ) ; if ( documentAbstract instanceof Document ) { final Document document = ( Document ) documentAbstract ; paperclip . setDocumentCreatedAt ( document . getCreatedAt ( ) ) ; } if ( ! repositoryService . isPersistent ( attachTo ) ) { transactionService . flushTransaction ( ) ; } final Bookmark bookmark = bookmarkService . bookmarkFor ( attachTo ) ; paperclip . setAttachedTo ( attachTo ) ; paperclip . setAttachedToStr ( bookmark . toString ( ) ) ; repositoryService . persistAndFlush ( paperclip ) ; return paperclip ; }
This is an idempotent operation .
240
9
10,928
private void scanFraction ( int pos ) { skipIllegalUnderscores ( ) ; if ( ' ' <= reader . ch && reader . ch <= ' ' ) { scanDigits ( pos , 10 ) ; } int sp1 = reader . sp ; if ( reader . ch == ' ' || reader . ch == ' ' ) { reader . putChar ( true ) ; skipIllegalUnderscores ( ) ; if ( reader . ch == ' ' || reader . ch == ' ' ) { reader . putChar ( true ) ; } skipIllegalUnderscores ( ) ; if ( ' ' <= reader . ch && reader . ch <= ' ' ) { scanDigits ( pos , 10 ) ; return ; } lexError ( pos , "malformed.fp.lit" ) ; reader . sp = sp1 ; } }
Read fractional part of floating point number .
179
9
10,929
private boolean isMagicComment ( ) { assert reader . ch == ' ' ; int parens = 0 ; boolean stringLit = false ; int lbp = reader . bp ; char lch = reader . buf [ ++ lbp ] ; if ( ! Character . isJavaIdentifierStart ( lch ) ) { // The first thing after the @ has to be the annotation identifier return false ; } while ( lbp < reader . buflen ) { lch = reader . buf [ ++ lbp ] ; // We are outside any annotation values if ( Character . isWhitespace ( lch ) && ! spacesincomments && parens == 0 ) { return false ; } else if ( lch == ' ' && parens == 0 ) { // At most one annotation per magic comment return false ; } else if ( lch == ' ' && ! stringLit ) { ++ parens ; } else if ( lch == ' ' && ! stringLit ) { -- parens ; } else if ( lch == ' ' ) { // TODO: handle more complicated string literals, // char literals, escape sequences, unicode, etc. stringLit = ! stringLit ; } else if ( lch == ' ' && ! stringLit && lbp + 1 < reader . buflen && reader . buf [ lbp + 1 ] == ' ' ) { // We reached the end of the comment, make sure no // parens are open return parens == 0 ; } else if ( ! Character . isJavaIdentifierPart ( lch ) && ! Character . isWhitespace ( lch ) && lch != ' ' && // separator in fully-qualified annotation name // TODO: this also allows /*@A...*/ which should not be recognized. ! spacesincomments && parens == 0 && ! stringLit ) { return false ; } // Do we need anything else for annotation values, e.g. String literals? } // came to end of file before '*/' return false ; }
with annotation values .
439
4
10,930
protected Tokens . Comment processComment ( int pos , int endPos , CommentStyle style ) { if ( scannerDebug ) System . out . println ( "processComment(" + pos + "," + endPos + "," + style + ")=|" + new String ( reader . getRawCharacters ( pos , endPos ) ) + "|" ) ; char [ ] buf = reader . getRawCharacters ( pos , endPos ) ; return new BasicComment < UnicodeReader > ( new UnicodeReader ( fac , buf , buf . length ) , style ) ; }
Called when a complete comment has been scanned . pos and endPos will mark the comment boundary .
117
20
10,931
public boolean isZeroVATAllowed ( @ Nonnull final Locale aCountry , final boolean bUndefinedValue ) { ValueEnforcer . notNull ( aCountry , "Country" ) ; // first get locale specific VAT types final VATCountryData aVATCountryData = getVATCountryData ( aCountry ) ; return aVATCountryData != null ? aVATCountryData . isZeroVATAllowed ( ) : bUndefinedValue ; }
Check if zero VAT is allowed for the passed country
98
10
10,932
@ Nullable public VATCountryData getVATCountryData ( @ Nonnull final Locale aLocale ) { ValueEnforcer . notNull ( aLocale , "Locale" ) ; final Locale aCountry = CountryCache . getInstance ( ) . getCountry ( aLocale ) ; return m_aVATItemsPerCountry . get ( aCountry ) ; }
Get the VAT data of the passed country .
80
9
10,933
@ Nullable public IVATItem findVATItem ( @ Nullable final EVATItemType eType , @ Nullable final BigDecimal aPercentage ) { if ( eType == null || aPercentage == null ) return null ; return findFirst ( x -> x . getType ( ) . equals ( eType ) && x . hasPercentage ( aPercentage ) ) ; }
Find a matching VAT item with the passed properties independent of the country .
83
14
10,934
@ Nullable public IVATItem findFirst ( @ Nonnull final Predicate < ? super IVATItem > aFilter ) { return CollectionHelper . findFirst ( m_aAllVATItems . values ( ) , aFilter ) ; }
Find the first matching VAT item .
51
7
10,935
@ Nonnull @ ReturnsMutableCopy public ICommonsList < IVATItem > findAll ( @ Nonnull final Predicate < ? super IVATItem > aFilter ) { final ICommonsList < IVATItem > ret = new CommonsArrayList <> ( ) ; CollectionHelper . findAll ( m_aAllVATItems . values ( ) , aFilter , ret :: add ) ; return ret ; }
Find all matching VAT items .
89
6
10,936
static private String serialize ( Throwable ex , int depth , int level ) { StringBuffer buff = new StringBuffer ( ) ; String str = ex . toString ( ) ; // Split the first line if it's too long int pos = str . indexOf ( ":" ) ; if ( str . length ( ) < 80 || pos == - 1 ) { buff . append ( str ) ; } else { String str1 = str . substring ( 0 , pos ) ; String str2 = str . substring ( pos + 2 ) ; if ( str2 . indexOf ( str1 ) == - 1 ) { buff . append ( str1 ) ; buff . append ( ": \n\t" ) ; } buff . append ( str2 ) ; } if ( depth > 0 ) { StackTraceElement [ ] elements = ex . getStackTrace ( ) ; for ( int i = 0 ; i < elements . length ; i ++ ) { buff . append ( "\n\tat " ) ; buff . append ( elements [ i ] ) ; if ( i == ( depth - 1 ) && elements . length > depth ) { buff . append ( "\n\t... " + ( elements . length - depth ) + " more ..." ) ; i = elements . length ; } } } if ( ex . getCause ( ) != null && level < 3 ) { buff . append ( "\nCaused by: " ) ; buff . append ( serialize ( ex . getCause ( ) , depth , ++ level ) ) ; } return buff . toString ( ) ; }
Serializes the given exception as a stack trace string .
333
11
10,937
public static String serialize ( Object [ ] objs ) { StringBuffer buff = new StringBuffer ( ) ; for ( int i = 0 ; i < objs . length ; i ++ ) { if ( objs [ i ] != null ) { buff . append ( objs [ i ] . toString ( ) ) ; if ( i != objs . length - 1 ) buff . append ( "," ) ; } } return buff . toString ( ) ; }
Returns the given array serialized as a string .
98
10
10,938
public static String encode ( String str ) { String ret = str ; try { // Obfuscate the string if ( ret != null ) ret = new String ( Base64 . encodeBase64 ( ret . getBytes ( ) ) ) ; } catch ( NoClassDefFoundError e ) { System . out . println ( "WARNING: unable to encode: " + e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) ) ; } return ret ; }
Returns the given string after if it has been encoded .
104
11
10,939
public static String encodeBytes ( byte [ ] bytes ) { String ret = null ; try { // Obfuscate the string if ( bytes != null ) ret = new String ( Base64 . encodeBase64 ( bytes ) ) ; } catch ( NoClassDefFoundError e ) { ret = new String ( bytes ) ; System . out . println ( "WARNING: unable to encode: " + e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) ) ; } return ret ; }
Returns the given byte array after if it has been encoded .
110
12
10,940
public static String decode ( String str ) { String ret = str ; try { // De-obfuscate the string if ( ret != null ) ret = new String ( Base64 . decodeBase64 ( ret . getBytes ( ) ) ) ; } catch ( NoClassDefFoundError e ) { System . out . println ( "WARNING: unable to decode: " + e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) ) ; } return ret ; }
Returns the given string after if it has been decoded .
106
12
10,941
public static byte [ ] decodeBytes ( String str ) { byte [ ] ret = null ; try { // De-obfuscate the string if ( str != null ) ret = Base64 . decodeBase64 ( str . getBytes ( ) ) ; } catch ( NoClassDefFoundError e ) { ret = str . getBytes ( ) ; System . out . println ( "WARNING: unable to decode: " + e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) ) ; } return ret ; }
Returns the given byte array after if it has been decoded .
116
13
10,942
public static String truncate ( String str , int count ) { if ( count < 0 || str . length ( ) <= count ) return str ; int pos = count ; for ( int i = count ; i >= 0 && ! Character . isWhitespace ( str . charAt ( i ) ) ; i -- , pos -- ) ; return str . substring ( 0 , pos ) + "..." ; }
Returns the given string truncated at a word break before the given number of characters .
85
17
10,943
public static int getOccurenceCount ( char c , String s ) { int ret = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == c ) ++ ret ; } return ret ; }
Returns the number of occurences of the given character in the given string .
60
16
10,944
public static int getOccurrenceCount ( String expr , String str ) { int ret = 0 ; Pattern p = Pattern . compile ( expr ) ; Matcher m = p . matcher ( str ) ; while ( m . find ( ) ) ++ ret ; return ret ; }
Returns the number of occurrences of the substring in the given string .
57
14
10,945
public static boolean endsWith ( StringBuffer buffer , String suffix ) { if ( suffix . length ( ) > buffer . length ( ) ) return false ; int endIndex = suffix . length ( ) - 1 ; int bufferIndex = buffer . length ( ) - 1 ; while ( endIndex >= 0 ) { if ( buffer . charAt ( bufferIndex ) != suffix . charAt ( endIndex ) ) return false ; bufferIndex -- ; endIndex -- ; } return true ; }
Checks that a string buffer ends up with a given string .
99
13
10,946
public static String toReadableForm ( String str ) { String ret = str ; if ( str != null && str . length ( ) > 0 && str . indexOf ( "\n" ) != - 1 && str . indexOf ( "\r" ) == - 1 ) { str . replaceAll ( "\n" , "\r\n" ) ; } return ret ; }
Converts the given string with CR and LF character correctly formatted .
79
13
10,947
public static String urlEncode ( String str ) { String ret = str ; try { ret = URLEncoder . encode ( str , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { logger . severe ( "Failed to encode value: " + str ) ; } return ret ; }
Encode the special characters in the string to its URL encoded representation .
68
14
10,948
public static String stripSpaces ( String s ) { StringBuffer buff = new StringBuffer ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c != ' ' ) buff . append ( c ) ; } return buff . toString ( ) ; }
Returns the given string with all spaces removed .
75
9
10,949
public static String removeControlCharacters ( String s , boolean removeCR ) { String ret = s ; if ( ret != null ) { ret = ret . replaceAll ( "_x000D_" , "" ) ; if ( removeCR ) ret = ret . replaceAll ( "\r" , "" ) ; } return ret ; }
Remove any extraneous control characters from text fields .
68
10
10,950
public static void printCharacters ( String s ) { if ( s != null ) { logger . info ( "string length=" + s . length ( ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; logger . info ( "char[" + i + "]=" + c + " (" + ( int ) c + ")" ) ; } } }
Prints the character codes for the given string .
94
10
10,951
public static String stripDoubleQuotes ( String s ) { String ret = s ; if ( hasDoubleQuotes ( s ) ) ret = s . substring ( 1 , s . length ( ) - 1 ) ; return ret ; }
Returns the given string with leading and trailing quotes removed .
47
11
10,952
public static String stripClassNames ( String str ) { String ret = str ; if ( ret != null ) { while ( ret . startsWith ( "java.security.PrivilegedActionException:" ) || ret . startsWith ( "com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl:" ) || ret . startsWith ( "javax.jms.JMSSecurityException:" ) ) { ret = ret . substring ( ret . indexOf ( ":" ) + 1 ) . trim ( ) ; } } return ret ; }
Strips class name prefixes from the start of the given string .
120
15
10,953
public static String stripDomain ( String hostname ) { String ret = hostname ; int pos = hostname . indexOf ( "." ) ; if ( pos != - 1 ) ret = hostname . substring ( 0 , pos ) ; return ret ; }
Returns the given hostname with the domain removed .
54
10
10,954
public Class < ? > findClass ( String className , String versionRange ) { //if (ClassServiceBootstrap.repositoryAdmin == null) // return null; Class < ? > c = this . getClassFromBundle ( null , className , versionRange ) ; if ( c == null ) { Object resource = this . deployThisResource ( ClassFinderActivator . getPackageName ( className , false ) , versionRange , false ) ; if ( resource != null ) { c = this . getClassFromBundle ( null , className , versionRange ) ; // It is possible that the newly started bundle registered itself if ( c == null ) c = this . getClassFromBundle ( resource , className , versionRange ) ; } } return c ; }
Find resolve and return this class definition .
165
8
10,955
public URL findResourceURL ( String resourcePath , String versionRange ) { //if (ClassServiceBootstrap.repositoryAdmin == null) // return null; URL url = this . getResourceFromBundle ( null , resourcePath , versionRange ) ; if ( url == null ) { Object resource = this . deployThisResource ( ClassFinderActivator . getPackageName ( resourcePath , true ) , versionRange , false ) ; if ( resource != null ) url = this . getResourceFromBundle ( resource , resourcePath , versionRange ) ; } return url ; }
Find resolve and return this resource s URL .
122
9
10,956
public ResourceBundle findResourceBundle ( String resourcePath , Locale locale , String versionRange ) { //if (ClassServiceBootstrap.repositoryAdmin == null) // return null; ResourceBundle resourceBundle = this . getResourceBundleFromBundle ( null , resourcePath , locale , versionRange ) ; if ( resourceBundle == null ) { Object resource = this . deployThisResource ( ClassFinderActivator . getPackageName ( resourcePath , true ) , versionRange , false ) ; if ( resource != null ) { resourceBundle = this . getResourceBundleFromBundle ( resource , resourcePath , locale , versionRange ) ; if ( resourceBundle == null ) { Class < ? > c = this . getClassFromBundle ( resource , resourcePath , versionRange ) ; if ( c != null ) { try { resourceBundle = ( ResourceBundle ) c . newInstance ( ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; // Never } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; // Never } catch ( Exception e ) { e . printStackTrace ( ) ; // Never } } } } } return resourceBundle ; }
Find resolve and return this ResourceBundle .
267
9
10,957
public boolean shutdownService ( String serviceClass , Object service ) { if ( service == null ) return false ; if ( bundleContext == null ) return false ; String filter = null ; if ( serviceClass == null ) if ( ! ( service instanceof String ) ) serviceClass = service . getClass ( ) . getName ( ) ; if ( service instanceof String ) filter = ClassServiceUtility . addToFilter ( "" , BundleConstants . SERVICE_PID , ( String ) service ) ; ServiceReference [ ] refs ; try { refs = bundleContext . getServiceReferences ( serviceClass , filter ) ; if ( ( refs == null ) || ( refs . length == 0 ) ) return false ; for ( ServiceReference reference : refs ) { if ( ( bundleContext . getService ( reference ) == service ) || ( service instanceof String ) ) { if ( refs . length == 1 ) { // Last/only one, shut down the service // Lame code String dependentBaseBundleClassName = service . getClass ( ) . getName ( ) ; String packageName = ClassFinderActivator . getPackageName ( dependentBaseBundleClassName , false ) ; if ( service instanceof String ) packageName = ( String ) service ; Bundle bundle = this . findBundle ( null , bundleContext , packageName , null ) ; if ( bundle != null ) if ( ( bundle . getState ( ) & Bundle . ACTIVE ) != 0 ) { try { bundle . stop ( ) ; } catch ( BundleException e ) { e . printStackTrace ( ) ; } } return true ; } } } } catch ( InvalidSyntaxException e1 ) { e1 . printStackTrace ( ) ; } return false ; // Not found? }
Shutdown the bundle for this service .
374
8
10,958
public void startBundle ( Bundle bundle ) { if ( bundle != null ) if ( ( bundle . getState ( ) != Bundle . ACTIVE ) && ( bundle . getState ( ) != Bundle . STARTING ) ) { try { bundle . start ( ) ; } catch ( BundleException e ) { e . printStackTrace ( ) ; } } }
Start this bundle .
75
4
10,959
@ SuppressWarnings ( "unchecked" ) @ Override public Dictionary < String , String > getProperties ( String servicePid ) { Dictionary < String , String > properties = null ; try { if ( servicePid != null ) { ServiceReference caRef = bundleContext . getServiceReference ( ConfigurationAdmin . class . getName ( ) ) ; if ( caRef != null ) { ConfigurationAdmin configAdmin = ( ConfigurationAdmin ) bundleContext . getService ( caRef ) ; Configuration config = configAdmin . getConfiguration ( servicePid ) ; properties = config . getProperties ( ) ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; } return properties ; }
Get the configuration properties for this Pid .
151
9
10,960
@ Override public boolean saveProperties ( String servicePid , Dictionary < String , String > properties ) { try { if ( servicePid != null ) { ServiceReference caRef = bundleContext . getServiceReference ( ConfigurationAdmin . class . getName ( ) ) ; if ( caRef != null ) { ConfigurationAdmin configAdmin = ( ConfigurationAdmin ) bundleContext . getService ( caRef ) ; Configuration config = configAdmin . getConfiguration ( servicePid ) ; config . update ( properties ) ; return true ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; } return false ; }
Set the configuration properties for this Pid .
132
9
10,961
public static byte [ ] read ( InputStream in , boolean closeAfterwards ) throws IOException { byte [ ] buffer = new byte [ 32 * 1024 ] ; ByteArrayOutputStream bas = new ByteArrayOutputStream ( ) ; for ( int length ; ( length = in . read ( buffer , 0 , buffer . length ) ) > - 1 ; bas . write ( buffer , 0 , length ) ) ; if ( closeAfterwards ) in . close ( ) ; return bas . toByteArray ( ) ; }
Reads the whole contents of an input stream into a byte array closing the stream if so requested .
106
20
10,962
public void add ( Collection < AlertPolicy > policies ) { for ( AlertPolicy policy : policies ) this . policies . put ( policy . getId ( ) , policy ) ; }
Adds the policy list to the policies for the account .
37
11
10,963
public AlertChannelCache alertChannels ( long policyId ) { AlertChannelCache cache = channels . get ( policyId ) ; if ( cache == null ) channels . put ( policyId , cache = new AlertChannelCache ( policyId ) ) ; return cache ; }
Returns the cache of alert channels for the given policy creating one if it doesn t exist .
55
18
10,964
public void setAlertChannels ( Collection < AlertChannel > channels ) { for ( AlertChannel channel : channels ) { // Add the channel to any policies it is associated with List < Long > policyIds = channel . getLinks ( ) . getPolicyIds ( ) ; for ( long policyId : policyIds ) { AlertPolicy policy = policies . get ( policyId ) ; if ( policy != null ) alertChannels ( policyId ) . add ( channel ) ; else logger . severe ( String . format ( "Unable to find policy for channel '%s': %d" , channel . getName ( ) , policyId ) ) ; } } }
Sets the channels on the policies for the account .
139
11
10,965
public AlertConditionCache alertConditions ( long policyId ) { AlertConditionCache cache = conditions . get ( policyId ) ; if ( cache == null ) conditions . put ( policyId , cache = new AlertConditionCache ( policyId ) ) ; return cache ; }
Returns the cache of alert conditions for the given policy creating one if it doesn t exist .
55
18
10,966
public NrqlAlertConditionCache nrqlAlertConditions ( long policyId ) { NrqlAlertConditionCache cache = nrqlConditions . get ( policyId ) ; if ( cache == null ) nrqlConditions . put ( policyId , cache = new NrqlAlertConditionCache ( policyId ) ) ; return cache ; }
Returns the cache of NRQL alert conditions for the given policy creating one if it doesn t exist .
75
20
10,967
public ExternalServiceAlertConditionCache externalServiceAlertConditions ( long policyId ) { ExternalServiceAlertConditionCache cache = externalServiceConditions . get ( policyId ) ; if ( cache == null ) externalServiceConditions . put ( policyId , cache = new ExternalServiceAlertConditionCache ( policyId ) ) ; return cache ; }
Returns the cache of external service alert conditions for the given policy creating one if it doesn t exist .
69
20
10,968
public SyntheticsAlertConditionCache syntheticsAlertConditions ( long policyId ) { SyntheticsAlertConditionCache cache = syntheticsConditions . get ( policyId ) ; if ( cache == null ) syntheticsConditions . put ( policyId , cache = new SyntheticsAlertConditionCache ( policyId ) ) ; return cache ; }
Returns the cache of Synthetics alert conditions for the given policy creating one if it doesn t exist .
69
20
10,969
public PluginsAlertConditionCache pluginsAlertConditions ( long policyId ) { PluginsAlertConditionCache cache = pluginsConditions . get ( policyId ) ; if ( cache == null ) pluginsConditions . put ( policyId , cache = new PluginsAlertConditionCache ( policyId ) ) ; return cache ; }
Returns the cache of Plugins alert conditions for the given policy creating one if it doesn t exist .
66
20
10,970
public InfraAlertConditionCache infraAlertConditions ( long policyId ) { InfraAlertConditionCache cache = infraConditions . get ( policyId ) ; if ( cache == null ) infraConditions . put ( policyId , cache = new InfraAlertConditionCache ( policyId ) ) ; return cache ; }
Returns the cache of Infrastructure alert conditions for the given policy creating one if it doesn t exist .
69
19
10,971
static PrintWriter defaultWriter ( Context context ) { PrintWriter result = context . get ( outKey ) ; if ( result == null ) context . put ( outKey , result = new PrintWriter ( System . err ) ) ; return result ; }
The default writer for diagnostics
51
6
10,972
public void initRound ( Log other ) { this . noticeWriter = other . noticeWriter ; this . warnWriter = other . warnWriter ; this . errWriter = other . errWriter ; this . sourceMap = other . sourceMap ; this . recorded = other . recorded ; this . nerrors = other . nerrors ; this . nwarnings = other . nwarnings ; }
Propagate the previous log s information .
80
8
10,973
public void setVisibleSources ( Map < String , Source > vs ) { visibleSrcs = new HashSet < URI > ( ) ; for ( String s : vs . keySet ( ) ) { Source src = vs . get ( s ) ; visibleSrcs . add ( src . file ( ) . toURI ( ) ) ; } }
Specify which sources are visible to the compiler through - sourcepath .
74
14
10,974
public void save ( ) throws IOException { if ( ! needsSaving ) return ; try ( FileWriter out = new FileWriter ( javacStateFilename ) ) { StringBuilder b = new StringBuilder ( ) ; long millisNow = System . currentTimeMillis ( ) ; Date d = new Date ( millisNow ) ; SimpleDateFormat df = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss SSS" ) ; b . append ( "# javac_state ver 0.3 generated " + millisNow + " " + df . format ( d ) + "\n" ) ; b . append ( "# This format might change at any time. Please do not depend on it.\n" ) ; b . append ( "# M module\n" ) ; b . append ( "# P package\n" ) ; b . append ( "# S C source_tobe_compiled timestamp\n" ) ; b . append ( "# S L link_only_source timestamp\n" ) ; b . append ( "# G C generated_source timestamp\n" ) ; b . append ( "# A artifact timestamp\n" ) ; b . append ( "# D dependency\n" ) ; b . append ( "# I pubapi\n" ) ; b . append ( "# R arguments\n" ) ; b . append ( "R " ) . append ( theArgs ) . append ( "\n" ) ; // Copy over the javac_state for the packages that did not need recompilation. now . copyPackagesExcept ( prev , recompiledPackages , new HashSet < String > ( ) ) ; // Save the packages, ie package names, dependencies, pubapis and artifacts! // I.e. the lot. Module . saveModules ( now . modules ( ) , b ) ; String s = b . toString ( ) ; out . write ( s , 0 , s . length ( ) ) ; } }
Save the javac_state file .
419
9
10,975
public boolean performJavaCompilations ( File binDir , String serverSettings , String [ ] args , Set < String > recentlyCompiled , boolean [ ] rcValue ) { Map < String , Transformer > suffixRules = new HashMap < String , Transformer > ( ) ; suffixRules . put ( ".java" , compileJavaPackages ) ; compileJavaPackages . setExtra ( serverSettings ) ; compileJavaPackages . setExtra ( args ) ; rcValue [ 0 ] = perform ( binDir , suffixRules ) ; recentlyCompiled . addAll ( taintedPackages ( ) ) ; clearTaintedPackages ( ) ; boolean again = ! packagesWithChangedPublicApis . isEmpty ( ) ; taintPackagesDependingOnChangedPackages ( packagesWithChangedPublicApis , recentlyCompiled ) ; packagesWithChangedPublicApis = new HashSet < String > ( ) ; return again && rcValue [ 0 ] ; }
Compile all the java sources . Return true if it needs to be called again!
197
17
10,976
private void addFileToTransform ( Map < Transformer , Map < String , Set < URI > > > gs , Transformer t , Source s ) { Map < String , Set < URI > > fs = gs . get ( t ) ; if ( fs == null ) { fs = new HashMap < String , Set < URI > > ( ) ; gs . put ( t , fs ) ; } Set < URI > ss = fs . get ( s . pkg ( ) . name ( ) ) ; if ( ss == null ) { ss = new HashSet < URI > ( ) ; fs . put ( s . pkg ( ) . name ( ) , ss ) ; } ss . add ( s . file ( ) . toURI ( ) ) ; }
Store the source into the set of sources belonging to the given transform .
162
14
10,977
private void buildDeprecatedAPIInfo ( Configuration configuration ) { PackageDoc [ ] packages = configuration . packages ; PackageDoc pkg ; for ( int c = 0 ; c < packages . length ; c ++ ) { pkg = packages [ c ] ; if ( Util . isDeprecated ( pkg ) ) { getList ( PACKAGE ) . add ( pkg ) ; } } ClassDoc [ ] classes = configuration . root . classes ( ) ; for ( int i = 0 ; i < classes . length ; i ++ ) { ClassDoc cd = classes [ i ] ; if ( Util . isDeprecated ( cd ) ) { if ( cd . isOrdinaryClass ( ) ) { getList ( CLASS ) . add ( cd ) ; } else if ( cd . isInterface ( ) ) { getList ( INTERFACE ) . add ( cd ) ; } else if ( cd . isException ( ) ) { getList ( EXCEPTION ) . add ( cd ) ; } else if ( cd . isEnum ( ) ) { getList ( ENUM ) . add ( cd ) ; } else if ( cd . isError ( ) ) { getList ( ERROR ) . add ( cd ) ; } else if ( cd . isAnnotationType ( ) ) { getList ( ANNOTATION_TYPE ) . add ( cd ) ; } } composeDeprecatedList ( getList ( FIELD ) , cd . fields ( ) ) ; composeDeprecatedList ( getList ( METHOD ) , cd . methods ( ) ) ; composeDeprecatedList ( getList ( CONSTRUCTOR ) , cd . constructors ( ) ) ; if ( cd . isEnum ( ) ) { composeDeprecatedList ( getList ( ENUM_CONSTANT ) , cd . enumConstants ( ) ) ; } if ( cd . isAnnotationType ( ) ) { composeDeprecatedList ( getList ( ANNOTATION_TYPE_MEMBER ) , ( ( AnnotationTypeDoc ) cd ) . elements ( ) ) ; } } sortDeprecatedLists ( ) ; }
Build the sorted list of all the deprecated APIs in this run . Build separate lists for deprecated packages classes constructors methods and fields .
437
26
10,978
public Object parse ( String text ) throws DataValidationException { try { preValidate ( text ) ; Object object = _valueOf . invoke ( text ) ; postValidate ( object ) ; return object ; } catch ( DataValidationException x ) { throw x ; } catch ( IllegalArgumentException x ) { // various format errors from valueOf() - ignore the details throw new DataValidationException ( "FORMAT" , _name , text ) ; } catch ( Throwable t ) { throw new DataValidationException ( "" , _name , text , t ) ; } }
Parses a string to produce a validated value of this given data type .
124
16
10,979
public void preValidate ( String text ) throws DataValidationException { // size Trace . g . std . note ( Validator . class , "preValidate: size = " + _size ) ; if ( _size > 0 && text . length ( ) > _size ) { throw new DataValidationException ( "SIZE" , _name , text ) ; } // pattern Trace . g . std . note ( Validator . class , "preValidate: pattern = " + _pattern ) ; if ( _pattern != null && ! _pattern . matcher ( text ) . matches ( ) ) { throw new DataValidationException ( "PATTERN" , _name , text ) ; } }
Performs all data validation that is based on the string representation of the value before it is converted .
149
20
10,980
@ SuppressWarnings ( "unchecked" ) public void postValidate ( Object object ) throws DataValidationException { if ( _values != null || _ranges != null ) { if ( _values != null ) for ( Object value : _values ) { if ( value . equals ( object ) ) return ; } if ( _ranges != null ) for ( @ SuppressWarnings ( "rawtypes" ) Range r : _ranges ) { @ SuppressWarnings ( "rawtypes" ) Comparable o = ( Comparable ) object ; if ( r . inclusive ) { if ( ( r . min == null || r . min . compareTo ( o ) <= 0 ) && ( r . max == null || o . compareTo ( r . max ) <= 0 ) ) { return ; } } else { if ( ( r . min == null || r . min . compareTo ( o ) < 0 ) && ( r . max == null || o . compareTo ( r . max ) < 0 ) ) { return ; } } } throw new DataValidationException ( "VALUES/RANGES" , _name , object ) ; } }
Performs all data validation that is appicable to the data value itself
249
14
10,981
public void startRobot ( Robot newRobot ) { newRobot . getData ( ) . setActiveState ( DEFAULT_START_STATE ) ; Thread newThread = new Thread ( robotsThreads , newRobot , "Bot-" + newRobot . getSerialNumber ( ) ) ; newThread . start ( ) ; // jumpstarts the robot }
Starts the thread of a robot in the player s thread group
78
13
10,982
public static List < Player > loadPlayers ( List < String > playersFiles ) throws PlayerException { log . info ( "[loadPlayers] Loading all players" ) ; List < Player > players = new ArrayList <> ( ) ; if ( playersFiles . size ( ) < 1 ) { log . warn ( "[loadPlayers] No players to load" ) ; } for ( String singlePath : playersFiles ) { Player single = new Player ( new File ( singlePath ) ) ; players . add ( single ) ; } return players ; }
Creates a list of players using the paths provided
112
10
10,983
public void add ( Collection < Dashboard > dashboards ) { for ( Dashboard dashboard : dashboards ) this . dashboards . put ( dashboard . getId ( ) , dashboard ) ; }
Adds the dashboard list to the dashboards for the account .
40
12
10,984
@ Override public synchronized void write ( final Event event ) throws IOException { if ( ! acceptsEvents ) { log . warn ( "Writer not ready, discarding event: {}" , event ) ; return ; } delegate . write ( event ) ; uncommittedWriteCount ++ ; commitIfNeeded ( ) ; }
Write an Event via the delegate writer
66
7
10,985
@ Managed ( description = "Commit locally spooled events for flushing" ) @ Override public synchronized void forceCommit ( ) throws IOException { log . debug ( "Performing commit on delegate EventWriter [{}]" , delegate . getClass ( ) ) ; delegate . commit ( ) ; uncommittedWriteCount = 0 ; lastCommitNanos = getNow ( ) ; }
Perform a commit via the delegate writer
84
8
10,986
public OptionalFunction < T , R > orElse ( Supplier < R > supplier ) { return new OptionalFunction <> ( function , supplier ) ; }
Creates a new OptionalFunction that will use the given function for null values .
32
16
10,987
public OptionalFunction < T , R > orElseThrow ( Supplier < ? extends RuntimeException > exceptionSupplier ) { return new OptionalFunction <> ( this . function , ( ) -> { throw exceptionSupplier . get ( ) ; } ) ; }
Creates a new OptionalFunction that will throw the exception supplied by the given supplier for null values .
53
20
10,988
public static TimeZone getTimeZone ( String name ) { TimeZone ret = null ; if ( timezones != null ) { for ( int i = 0 ; i < timezones . length && ret == null ; i ++ ) { if ( timezones [ i ] . getName ( ) . equals ( name ) ) ret = timezones [ i ] . getTimeZone ( ) ; } } return ret ; }
Returns the cached timezone with the given name .
90
10
10,989
public static TimeZone getTimeZoneById ( String id ) { TimeZone ret = null ; if ( timezones != null ) { for ( int i = 0 ; i < timezones . length && ret == null ; i ++ ) { if ( timezones [ i ] . getId ( ) . equals ( id ) ) ret = timezones [ i ] . getTimeZone ( ) ; } } return ret ; }
Returns the cached timezone with the given ID .
91
10
10,990
public static TimeZone getTimeZoneByIdIgnoreCase ( String id ) { TimeZone ret = null ; if ( timezones != null ) { id = id . toLowerCase ( ) ; for ( int i = 0 ; i < timezones . length && ret == null ; i ++ ) { if ( timezones [ i ] . getId ( ) . toLowerCase ( ) . equals ( id ) ) ret = timezones [ i ] . getTimeZone ( ) ; } } return ret ; }
Returns the cached timezone with the given ID ignoring case .
110
12
10,991
private String getDisplayName ( ) { long hours = TimeUnit . MILLISECONDS . toHours ( tz . getRawOffset ( ) ) ; long minutes = Math . abs ( TimeUnit . MILLISECONDS . toMinutes ( tz . getRawOffset ( ) ) - TimeUnit . HOURS . toMinutes ( hours ) ) ; return String . format ( "(GMT%+d:%02d) %s" , hours , minutes , tz . getID ( ) ) ; }
Returns the display name of the timezone .
110
9
10,992
public void report ( DiagnosticPosition pos , String msg , Object ... args ) { JavaFileObject currentSource = log . currentSourceFile ( ) ; if ( verbose ) { if ( sourcesWithReportedWarnings == null ) sourcesWithReportedWarnings = new HashSet < JavaFileObject > ( ) ; if ( log . nwarnings < log . MaxWarnings ) { // generate message and remember the source file logMandatoryWarning ( pos , msg , args ) ; sourcesWithReportedWarnings . add ( currentSource ) ; } else if ( deferredDiagnosticKind == null ) { // set up deferred message if ( sourcesWithReportedWarnings . contains ( currentSource ) ) { // more errors in a file that already has reported warnings deferredDiagnosticKind = DeferredDiagnosticKind . ADDITIONAL_IN_FILE ; } else { // warnings in a new source file deferredDiagnosticKind = DeferredDiagnosticKind . IN_FILE ; } deferredDiagnosticSource = currentSource ; deferredDiagnosticArg = currentSource ; } else if ( ( deferredDiagnosticKind == DeferredDiagnosticKind . IN_FILE || deferredDiagnosticKind == DeferredDiagnosticKind . ADDITIONAL_IN_FILE ) && ! equal ( deferredDiagnosticSource , currentSource ) ) { // additional errors in more than one source file deferredDiagnosticKind = DeferredDiagnosticKind . ADDITIONAL_IN_FILES ; deferredDiagnosticArg = null ; } } else { if ( deferredDiagnosticKind == null ) { // warnings in a single source deferredDiagnosticKind = DeferredDiagnosticKind . IN_FILE ; deferredDiagnosticSource = currentSource ; deferredDiagnosticArg = currentSource ; } else if ( deferredDiagnosticKind == DeferredDiagnosticKind . IN_FILE && ! equal ( deferredDiagnosticSource , currentSource ) ) { // warnings in multiple source files deferredDiagnosticKind = DeferredDiagnosticKind . IN_FILES ; deferredDiagnosticArg = null ; } } }
Report a mandatory warning .
453
5
10,993
public static long combineInts ( String high , String low ) throws NumberFormatException { int highInt = Integer . parseInt ( high ) ; int lowInt = Integer . parseInt ( low ) ; /* * Shift the high integer into the upper 32 bits and add the low * integer. However, since this is really a single set of bits split in * half, the low part cannot be treated as negative by itself. Since * Java has no unsigned types, the top half of the long created by * up-casting the lower integer must be zeroed out before it's added. */ return ( ( long ) highInt << 32 ) + ( lowInt & 0x00000000FFFFFFFF L ) ; }
Combine two numbers that represent the high and low bits of a 64 - bit number .
145
18
10,994
public static Pair < String , String > splitLong ( long value ) { return Pair . of ( String . valueOf ( ( int ) ( value >> 32 ) ) , String . valueOf ( ( int ) value ) ) ; }
Split a single 64 bit number into integers representing the high and low 32 bits .
48
16
10,995
public static void sendExpectOk ( SocketManager socketManager , String message ) throws IOException { expectOk ( socketManager . sendAndWait ( message ) ) ; }
Send a message via the given socket manager which should always receive a case insensitive OK as the reply .
35
20
10,996
public static void expectOk ( String response ) throws ProtocolException { if ( ! "OK" . equalsIgnoreCase ( response ) ) { throw new ProtocolException ( response , Direction . RECEIVE ) ; } }
Check the response for an OK message . Throw an exception if response is not expected .
45
17
10,997
public void printError ( SourcePosition pos , String msg ) { if ( diagListener != null ) { report ( DiagnosticType . ERROR , pos , msg ) ; return ; } if ( nerrors < MaxErrors ) { String prefix = ( pos == null ) ? programName : pos . toString ( ) ; errWriter . println ( prefix + ": " + getText ( "javadoc.error" ) + " - " + msg ) ; errWriter . flush ( ) ; prompt ( ) ; nerrors ++ ; } }
Print error message increment error count . Part of DocErrorReporter .
115
14
10,998
public Object unmarshal ( Object map ) throws RpcException { return unmarshal ( getTypeClass ( ) , map , this . s , this . isOptional ) ; }
Converts o from a Map back to the Java Class associated with this Struct . Recursively unmarshals all the members of the map .
38
29
10,999
@ SuppressWarnings ( "unchecked" ) public Object marshal ( Object o ) throws RpcException { if ( o == null ) { return returnNullIfOptional ( ) ; } else if ( o instanceof BStruct ) { return validateMap ( structToMap ( o , this . s ) , this . s ) ; } else if ( o instanceof Map ) { return validateMap ( ( Map ) o , this . s ) ; } else { String msg = "Unable to convert class: " + o . getClass ( ) . getName ( ) ; throw RpcException . Error . INVALID_RESP . exc ( msg ) ; } }
Marshals native Java type o to a Map that can be serialized . Recursively marshals all of the Struct fields from o onto the map .
143
31