idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
11,800
public static int getSecond ( Date date ) { Calendar c = Calendar . getInstance ( ) ; c . setTime ( date ) ; return c . get ( Calendar . SECOND ) ; }
Get the second of the date
11,801
public static Date floor ( Date d ) { Calendar c = Calendar . getInstance ( ) ; c . setTime ( d ) ; c . set ( Calendar . HOUR_OF_DAY , 0 ) ; c . set ( Calendar . MINUTE , 0 ) ; c . set ( Calendar . SECOND , 0 ) ; c . set ( Calendar . MILLISECOND , 0 ) ; return c . getTime ( ) ; }
Rounds a date to hour 0 minute 0 second 0 and millisecond 0
11,802
public static boolean sameDay ( Date dateOne , Date dateTwo ) { if ( ( dateOne == null ) || ( dateTwo == null ) ) { return false ; } Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( dateOne ) ; int year = cal . get ( Calendar . YEAR ) ; int day = cal . get ( Calendar . DAY_OF_YEAR ) ; cal . setTime ( dateTwo ) ; int year2 = cal . get ( Calendar . YEAR ) ; int day2 = cal . get ( Calendar . DAY_OF_YEAR ) ; return ( ( year == year2 ) && ( day == day2 ) ) ; }
Test to see if two dates are in the same day of year
11,803
public static boolean sameWeek ( Date dateOne , Date dateTwo ) { if ( ( dateOne == null ) || ( dateTwo == null ) ) { return false ; } Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( dateOne ) ; int year = cal . get ( Calendar . YEAR ) ; int week = cal . get ( Calendar . WEEK_OF_YEAR ) ; cal . setTime ( dateTwo ) ; int year2 = cal . get ( Calendar . YEAR ) ; int week2 = cal . get ( Calendar . WEEK_OF_YEAR ) ; return ( ( year == year2 ) && ( week == week2 ) ) ; }
Test to see if two dates are in the same week
11,804
public static boolean sameMonth ( Date dateOne , Date dateTwo ) { if ( ( dateOne == null ) || ( dateTwo == null ) ) { return false ; } Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( dateOne ) ; int year = cal . get ( Calendar . YEAR ) ; int month = cal . get ( Calendar . MONTH ) ; cal . setTime ( dateTwo ) ; int year2 = cal . get ( Calendar . YEAR ) ; int month2 = cal . get ( Calendar . MONTH ) ; return ( ( year == year2 ) && ( month == month2 ) ) ; }
Test to see if two dates are in the same month
11,805
public static boolean sameHour ( Date dateOne , Date dateTwo ) { if ( ( dateOne == null ) || ( dateTwo == null ) ) { return false ; } Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( dateOne ) ; int year = cal . get ( Calendar . YEAR ) ; int month = cal . get ( Calendar . MONTH ) ; int day = cal . get ( Calendar . DAY_OF_YEAR ) ; int hour = cal . get ( Calendar . HOUR_OF_DAY ) ; cal . setTime ( dateTwo ) ; int year2 = cal . get ( Calendar . YEAR ) ; int month2 = cal . get ( Calendar . MONTH ) ; int day2 = cal . get ( Calendar . DAY_OF_YEAR ) ; int hour2 = cal . get ( Calendar . HOUR_OF_DAY ) ; return ( ( year == year2 ) && ( month == month2 ) && ( day == day2 ) && ( hour == hour2 ) ) ; }
Test to see if two dates are in the same hour of day
11,806
public static int getNumberOfDays ( Date first , Date second ) { Calendar c = Calendar . getInstance ( ) ; int result = 0 ; int compare = first . compareTo ( second ) ; if ( compare > 0 ) return 0 ; if ( compare == 0 ) return 1 ; c . setTime ( first ) ; int firstDay = c . get ( Calendar . DAY_OF_YEAR ) ; int firstYear = c . get ( Calendar . YEAR ) ; int firstDays = c . getActualMaximum ( Calendar . DAY_OF_YEAR ) ; c . setTime ( second ) ; int secondDay = c . get ( Calendar . DAY_OF_YEAR ) ; int secondYear = c . get ( Calendar . YEAR ) ; if ( firstYear == secondYear ) { result = secondDay - firstDay + 1 ; } else { result += firstDays - firstDay + 1 ; for ( int i = firstYear + 1 ; i < secondYear ; i ++ ) { c . set ( i , 0 , 0 ) ; result += c . getActualMaximum ( Calendar . DAY_OF_YEAR ) ; } result += secondDay ; } return result ; }
Get number of days between two dates
11,807
public static int [ ] getElapsedTime ( Date first , Date second ) { if ( first . compareTo ( second ) == 1 ) { return null ; } int difDays = 0 ; int difHours = 0 ; int difMinutes = 0 ; Calendar c = Calendar . getInstance ( ) ; c . setTime ( first ) ; int h1 = c . get ( Calendar . HOUR_OF_DAY ) ; int m1 = c . get ( Calendar . MINUTE ) ; c . setTime ( second ) ; int h2 = c . get ( Calendar . HOUR_OF_DAY ) ; int m2 = c . get ( Calendar . MINUTE ) ; if ( sameDay ( first , second ) ) { difHours = h2 - h1 ; } else { difDays = getNumberOfDays ( first , second ) - 1 ; if ( h1 >= h2 ) { difDays -- ; difHours = ( 24 - h1 ) + h2 ; } else { difHours = h2 - h1 ; } } if ( m1 >= m2 ) { difHours -- ; difMinutes = ( 60 - m1 ) + m2 ; } else { difMinutes = m2 - m1 ; } int [ ] result = new int [ 3 ] ; result [ 0 ] = difDays ; result [ 1 ] = difHours ; result [ 2 ] = difMinutes ; return result ; }
Get elapsedtime between two dates
11,808
public static Date addMinutes ( Date d , int minutes ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . MINUTE , minutes ) ; return cal . getTime ( ) ; }
Add minutes to a date
11,809
public static Date setMinutes ( Date d , int minutes ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . set ( Calendar . MINUTE , minutes ) ; return cal . getTime ( ) ; }
Set minutes to a date
11,810
public static Date addHours ( Date d , int hours ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . HOUR_OF_DAY , hours ) ; return cal . getTime ( ) ; }
Add hours to a date
11,811
public static Date setHours ( Date d , int hours ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . set ( Calendar . HOUR_OF_DAY , hours ) ; return cal . getTime ( ) ; }
Set hours to a date
11,812
public static Date addDays ( Date d , int days ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . DAY_OF_YEAR , days ) ; return cal . getTime ( ) ; }
Add days to a date
11,813
public static Date addWeeks ( Date d , int weeks ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . WEEK_OF_YEAR , weeks ) ; return cal . getTime ( ) ; }
Add weeks to a date
11,814
public static Date addMonths ( Date d , int months ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . MONTH , months ) ; return cal . getTime ( ) ; }
Add months to a date
11,815
public static int getLastDayOfMonth ( Date date ) { Calendar c = Calendar . getInstance ( ) ; c . setTime ( date ) ; return c . getActualMaximum ( Calendar . DATE ) ; }
Get last day from a month
11,816
public static Date getFromTimestamp ( Timestamp timestamp ) { if ( timestamp == null ) { return null ; } return new Date ( timestamp . getTime ( ) ) ; }
Get a date from a timestamp
11,817
public static Date getFirstDayFromCurrentWeek ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . set ( Calendar . DAY_OF_WEEK , Calendar . MONDAY ) ; cal . set ( Calendar . HOUR_OF_DAY , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; return cal . getTime ( ) ; }
Get first date from current week
11,818
public static Date getLastDayFromCurrentWeek ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; if ( cal . getFirstDayOfWeek ( ) == Calendar . SUNDAY ) { cal . add ( Calendar . WEEK_OF_YEAR , 1 ) ; } cal . set ( Calendar . DAY_OF_WEEK , Calendar . SUNDAY ) ; cal . set ( Calendar . HOUR_OF_DAY , 23 ) ; cal . set ( Calendar . MINUTE , 59 ) ; cal . set ( Calendar . SECOND , 59 ) ; cal . set ( Calendar . MILLISECOND , 999 ) ; return cal . getTime ( ) ; }
Get last date from current week
11,819
public static Date getFirstDayFromLastMonth ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . MONTH , - 1 ) ; cal . set ( Calendar . DAY_OF_MONTH , 1 ) ; cal . set ( Calendar . HOUR_OF_DAY , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; return cal . getTime ( ) ; }
Get first date from last month
11,820
public static Date getLastDayFromLastMonth ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . MONTH , - 1 ) ; cal . set ( Calendar . DAY_OF_MONTH , cal . getActualMaximum ( Calendar . DATE ) ) ; cal . set ( Calendar . HOUR_OF_DAY , 23 ) ; cal . set ( Calendar . MINUTE , 59 ) ; cal . set ( Calendar . SECOND , 59 ) ; cal . set ( Calendar . MILLISECOND , 999 ) ; return cal . getTime ( ) ; }
Get last date from last month
11,821
public static Date getFirstDayFromCurrentMonth ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . set ( Calendar . DAY_OF_MONTH , 1 ) ; cal . set ( Calendar . HOUR_OF_DAY , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; return cal . getTime ( ) ; }
Get first date from current month
11,822
public static Date getLastDayFromCurrentMonth ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . set ( Calendar . DAY_OF_MONTH , cal . getActualMaximum ( Calendar . DATE ) ) ; cal . set ( Calendar . HOUR_OF_DAY , 23 ) ; cal . set ( Calendar . MINUTE , 59 ) ; cal . set ( Calendar . SECOND , 59 ) ; cal . set ( Calendar . MILLISECOND , 999 ) ; return cal . getTime ( ) ; }
Get last date from current month
11,823
public static Date getFirstDayFromLastYear ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . YEAR , - 1 ) ; cal . set ( Calendar . MONTH , Calendar . JANUARY ) ; cal . set ( Calendar . DAY_OF_MONTH , 1 ) ; cal . set ( Calendar . HOUR_OF_DAY , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; return cal . getTime ( ) ; }
Get first date from last year
11,824
public static Date getFirstDayFromCurrentYear ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . set ( Calendar . MONTH , Calendar . JANUARY ) ; cal . set ( Calendar . DAY_OF_MONTH , 1 ) ; cal . set ( Calendar . HOUR_OF_DAY , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; return cal . getTime ( ) ; }
Get first date from current year
11,825
public static Date getLastDayFromCurrentYear ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . set ( Calendar . MONTH , Calendar . DECEMBER ) ; cal . set ( Calendar . DAY_OF_MONTH , 31 ) ; cal . set ( Calendar . HOUR_OF_DAY , 23 ) ; cal . set ( Calendar . MINUTE , 59 ) ; cal . set ( Calendar . SECOND , 59 ) ; cal . set ( Calendar . MILLISECOND , 999 ) ; return cal . getTime ( ) ; }
Get last date from current year
11,826
public static Date getLastNDay ( Date d , int n , int unitType ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( unitType , - n ) ; cal . set ( Calendar . HOUR_OF_DAY , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; return cal . getTime ( ) ; }
Get date with n unitType before
11,827
public void setTriggerContainer ( JComponent comp , JPanel content , boolean collapsed ) { add ( comp ) ; add ( _content = content ) ; _content . addComponentListener ( new ComponentAdapter ( ) { public void componentShown ( ComponentEvent event ) { EventQueue . invokeLater ( new Runnable ( ) { public void run ( ) { Rectangle r = _content . getBounds ( ) ; r . add ( 0 , 0 ) ; scrollRectToVisible ( r ) ; } } ) ; } } ) ; setCollapsed ( collapsed ) ; }
Set a component which contains the trigger button .
11,828
public void setTrigger ( AbstractButton trigger , Icon collapsed , Icon uncollapsed ) { _trigger = trigger ; _trigger . setHorizontalAlignment ( SwingConstants . LEFT ) ; _trigger . setHorizontalTextPosition ( SwingConstants . RIGHT ) ; _downIcon = collapsed ; _upIcon = uncollapsed ; _trigger . addActionListener ( this ) ; }
Set the trigger button .
11,829
public void setCollapsed ( boolean collapse ) { if ( collapse ) { _content . setVisible ( false ) ; _trigger . setIcon ( _downIcon ) ; } else { _content . setVisible ( true ) ; _trigger . setIcon ( _upIcon ) ; } SwingUtil . refresh ( this ) ; }
Set the collapsion state .
11,830
public static int [ ] add ( int [ ] list , int value ) { if ( list == null ) { return new int [ ] { value } ; } int llength = list . length ; for ( int i = 0 ; i < llength ; i ++ ) { if ( list [ i ] == value ) { return list ; } } int [ ] nlist = new int [ llength + 1 ] ; System . arraycopy ( list , 0 , nlist , 0 , llength ) ; nlist [ llength ] = value ; return nlist ; }
Adds the specified value to the list iff it is not already in the list .
11,831
public static boolean contains ( int [ ] list , int value ) { int llength = list . length ; for ( int i = 0 ; i < llength ; i ++ ) { if ( list [ i ] == value ) { return true ; } } return false ; }
Looks for an element that is equal to the supplied value .
11,832
public static int [ ] remove ( int [ ] list , int value ) { if ( list == null ) { return null ; } int llength = list . length ; for ( int i = 0 ; i < llength ; i ++ ) { if ( list [ i ] == value ) { return removeAt ( list , i ) ; } } return list ; }
Removes the first value that is equal to the supplied value . A new array will be created containing all other elements except the located element in the order they existed in the original list .
11,833
public static int [ ] removeAt ( int [ ] list , int index ) { int nlength = list . length - 1 ; int [ ] nlist = new int [ nlength ] ; System . arraycopy ( list , 0 , nlist , 0 , index ) ; System . arraycopy ( list , index + 1 , nlist , index , nlength - index ) ; return nlist ; }
Removes the value at the specified index . A new array will be created containing all other elements except the specified element in the order they existed in the original list .
11,834
public int incrementCount ( K key , int amount ) { int [ ] val = get ( key ) ; if ( val == null ) { put ( key , val = new int [ 1 ] ) ; } val [ 0 ] += amount ; return val [ 0 ] ; }
Increment the value associated with the specified key return the new value .
11,835
public int setCount ( K key , int count ) { int [ ] val = get ( key ) ; if ( val == null ) { put ( key , new int [ ] { count } ) ; return 0 ; } int oldVal = val [ 0 ] ; val [ 0 ] = count ; return oldVal ; }
Set the count for the specified key .
11,836
public void compress ( ) { for ( Iterator < int [ ] > itr = values ( ) . iterator ( ) ; itr . hasNext ( ) ; ) { if ( itr . next ( ) [ 0 ] == 0 ) { itr . remove ( ) ; } } }
Compress the count map - remove entries for which the value is 0 .
11,837
public static JInternalDialog createDialog ( JFrame frame , JPanel content ) { return createDialog ( frame , null , content ) ; }
Creates and shows an internal dialog with the specified panel .
11,838
public static JInternalDialog createDialog ( JFrame frame , String title , JPanel content ) { JInternalDialog dialog = new JInternalDialog ( frame ) ; dialog . setOpaque ( false ) ; if ( title != null ) { dialog . setTitle ( title ) ; } setContent ( dialog , content ) ; SwingUtil . centerComponent ( frame , dialog ) ; dialog . showDialog ( ) ; return dialog ; }
Creates and shows an internal dialog with the specified title and panel .
11,839
public static void setContent ( JInternalDialog dialog , JPanel content ) { Container holder = dialog . getContentPane ( ) ; holder . removeAll ( ) ; holder . add ( content , BorderLayout . CENTER ) ; dialog . pack ( ) ; }
Sets the content panel of the supplied internal dialog .
11,840
public static JInternalDialog getInternalDialog ( Component any ) { Component parent = any ; while ( parent != null && ! ( parent instanceof JInternalDialog ) ) { parent = parent . getParent ( ) ; } return ( JInternalDialog ) parent ; }
Returns the internal dialog that is a parent of the specified component .
11,841
public static void invalidateDialog ( Component any ) { JInternalDialog dialog = getInternalDialog ( any ) ; if ( dialog == null ) { return ; } SwingUtil . applyToHierarchy ( dialog , new SwingUtil . ComponentOp ( ) { public void apply ( Component comp ) { comp . invalidate ( ) ; } } ) ; dialog . setSize ( dialog . getPreferredSize ( ) ) ; }
Invalidates and resizes the entire dialog given any component within the dialog in question .
11,842
public int add ( K key , int amount ) { CountEntry < K > entry = _backing . get ( key ) ; if ( entry == null ) { _backing . put ( key , new CountEntry < K > ( key , amount ) ) ; return amount ; } return ( entry . count += amount ) ; }
Add the specified amount to the count for the specified key return the new count . Adding 0 will ensure that a Map . Entry is created for the specified key .
11,843
public int getCount ( K key ) { CountEntry < K > entry = _backing . get ( key ) ; return ( entry == null ) ? 0 : entry . count ; }
Get the count for the specified key . If the key is not present 0 is returned .
11,844
public void compress ( ) { for ( Iterator < CountEntry < K > > it = _backing . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { if ( it . next ( ) . count == 0 ) { it . remove ( ) ; } } }
Remove any keys for which the count is currently 0 .
11,845
protected < T > T pickPluck ( Iterable < ? extends T > iterable , T ifEmpty , boolean remove ) { if ( iterable instanceof Collection ) { @ SuppressWarnings ( "unchecked" ) Collection < ? extends T > coll = ( Collection < ? extends T > ) iterable ; int size = coll . size ( ) ; if ( size == 0 ) { return ifEmpty ; } if ( coll instanceof List ) { @ SuppressWarnings ( "unchecked" ) List < ? extends T > list = ( List < ? extends T > ) coll ; int idx = _r . nextInt ( size ) ; if ( remove ) { return list . remove ( idx ) ; } return list . get ( idx ) ; } Iterator < ? extends T > it = coll . iterator ( ) ; for ( int idx = _r . nextInt ( size ) ; idx > 0 ; idx -- ) { it . next ( ) ; } try { return it . next ( ) ; } finally { if ( remove ) { it . remove ( ) ; } } } if ( ! remove ) { return pick ( iterable . iterator ( ) , ifEmpty ) ; } Iterator < ? extends T > it = iterable . iterator ( ) ; if ( ! it . hasNext ( ) ) { return ifEmpty ; } Iterator < ? extends T > lagIt = iterable . iterator ( ) ; T pick = it . next ( ) ; lagIt . next ( ) ; for ( int count = 2 , lag = 1 ; it . hasNext ( ) ; count ++ , lag ++ ) { T next = it . next ( ) ; if ( 0 == _r . nextInt ( count ) ) { pick = next ; for ( ; lag > 0 ; lag -- ) { lagIt . next ( ) ; } } } lagIt . remove ( ) ; return pick ; }
Shared code for pick and pluck .
11,846
public void postUnit ( Unit unit ) { if ( shutdownRequested ( ) ) { throw new IllegalStateException ( "Cannot post units to shutdown invoker." ) ; } unit . queueStamp = System . currentTimeMillis ( ) ; _queue . append ( unit ) ; }
Posts a unit to this invoker for subsequent invocation on the invoker s thread .
11,847
public void shutdown ( ) { _shutdownRequested = true ; _queue . append ( new Unit ( ) { public boolean invoke ( ) { _running = false ; return false ; } } ) ; }
Shuts down the invoker thread by queueing up a unit that will cause the thread to exit after all currently queued units are processed .
11,848
protected void didInvokeUnit ( Unit unit , long start ) { if ( PERF_TRACK ) { long duration = System . currentTimeMillis ( ) - start ; Object key = unit . getClass ( ) ; recordMetrics ( key , duration ) ; long thresh = unit . getLongThreshold ( ) ; if ( thresh == 0 ) { thresh = _longThreshold ; } if ( duration > thresh ) { StringBuilder msg = new StringBuilder ( ) ; msg . append ( ( duration >= 10 * thresh ) ? "Really long" : "Long" ) ; msg . append ( " invoker unit [unit=" ) . append ( unit ) ; msg . append ( " (" ) . append ( key ) . append ( "), time=" ) . append ( duration ) . append ( "ms" ) ; if ( unit . getDetail ( ) != null ) { msg . append ( ", detail=" ) . append ( unit . getDetail ( ) ) ; } log . warning ( msg . append ( "]." ) . toString ( ) ) ; } } }
Called before we process an invoker unit .
11,849
public int compareTo ( ComparableTuple < L , R > other ) { int rv = ObjectUtil . compareTo ( left , other . left ) ; return ( rv != 0 ) ? rv : ObjectUtil . compareTo ( right , other . right ) ; }
from interface Comparable
11,850
public void parseStream ( InputStream stream ) throws IOException { try { _chars = new StringBuilder ( ) ; XMLUtil . parse ( this , stream ) ; } catch ( ParserConfigurationException pce ) { throw ( IOException ) new IOException ( ) . initCause ( pce ) ; } catch ( SAXException saxe ) { throw ( IOException ) new IOException ( ) . initCause ( saxe ) ; } }
Parse the given input stream .
11,851
protected InputStream getInputStream ( String path ) throws IOException { FileInputStream fis = new FileInputStream ( path ) ; return new BufferedInputStream ( fis ) ; }
Returns an input stream to read data from the given file name .
11,852
protected int parseInt ( String val ) { try { return ( val == null ) ? - 1 : Integer . parseInt ( val ) ; } catch ( NumberFormatException nfe ) { log . warning ( "Malformed integer value" , "val" , val ) ; return - 1 ; } }
Parse the given string as an integer and return the integer value or - 1 if the string is malformed .
11,853
public static String truncate ( String s , int maxLength , String append ) { if ( ( s == null ) || ( s . length ( ) <= maxLength ) ) { return s ; } else { return s . substring ( 0 , maxLength - append . length ( ) ) + append ; } }
Truncate the specified String if it is longer than maxLength . The string will be truncated at a position such that it is maxLength chars long after the addition of the append String .
11,854
public static String capitalize ( String s ) { if ( isBlank ( s ) ) { return s ; } char c = s . charAt ( 0 ) ; if ( Character . isUpperCase ( c ) ) { return s ; } else { return String . valueOf ( Character . toUpperCase ( c ) ) + s . substring ( 1 ) ; } }
Returns a version of the supplied string with the first letter capitalized .
11,855
public static String toUSLowerCase ( String s ) { return isBlank ( s ) ? s : s . toLowerCase ( Locale . US ) ; }
Returns a US locale lower case string . Useful when manipulating filenames and resource keys which would not have locale specific characters .
11,856
public static String toUSUpperCase ( String s ) { return isBlank ( s ) ? s : s . toUpperCase ( Locale . US ) ; }
Returns a US locale upper case string . Useful when manipulating filenames and resource keys which would not have locale specific characters .
11,857
public static String sanitize ( String source , CharacterValidator validator ) { if ( source == null ) { return null ; } int nn = source . length ( ) ; StringBuilder buf = new StringBuilder ( nn ) ; for ( int ii = 0 ; ii < nn ; ii ++ ) { char c = source . charAt ( ii ) ; if ( validator . isValid ( c ) ) { buf . append ( c ) ; } } return buf . toString ( ) ; }
Sanitize the specified String so that only valid characters are in it .
11,858
public static String sanitize ( String source , String charRegex ) { final StringBuilder buf = new StringBuilder ( " " ) ; final Matcher matcher = Pattern . compile ( charRegex ) . matcher ( buf ) ; return sanitize ( source , new CharacterValidator ( ) { public boolean isValid ( char c ) { buf . setCharAt ( 0 , c ) ; return matcher . matches ( ) ; } } ) ; }
Sanitize the specified String such that each character must match against the regex specified .
11,859
public static String pad ( String value , int width , char c ) { if ( width <= 0 ) { throw new IllegalArgumentException ( "Pad width must be greater than zero." ) ; } int l = value . length ( ) ; return ( l >= width ) ? value : value + fill ( c , width - l ) ; }
Pads the supplied string to the requested string width by appending the specified character to the end of the returned string . If the original string is wider than the requested width it is returned unmodified .
11,860
public static String fill ( char c , int count ) { char [ ] sameChars = new char [ count ] ; Arrays . fill ( sameChars , c ) ; return new String ( sameChars ) ; }
Returns a string containing the specified character repeated the specified number of times .
11,861
public static String [ ] split ( String source , String sep ) { if ( isBlank ( source ) ) { return new String [ 0 ] ; } int tcount = 0 , tpos = - 1 , tstart = 0 ; while ( ( tpos = source . indexOf ( sep , tpos + 1 ) ) != - 1 ) { tcount ++ ; } String [ ] tokens = new String [ tcount + 1 ] ; tpos = - 1 ; tcount = 0 ; while ( ( tpos = source . indexOf ( sep , tpos + 1 ) ) != - 1 ) { tokens [ tcount ] = source . substring ( tstart , tpos ) ; tstart = tpos + 1 ; tcount ++ ; } tokens [ tcount ] = source . substring ( tstart ) ; return tokens ; }
Splits the supplied string into components based on the specified separator string .
11,862
public static String wordWrap ( String str , int width ) { int size = str . length ( ) ; StringBuilder buf = new StringBuilder ( size + size / width ) ; int lastidx = 0 ; while ( lastidx < size ) { if ( lastidx + width >= size ) { buf . append ( str . substring ( lastidx ) ) ; break ; } int lastws = lastidx ; for ( int ii = lastidx , ll = lastidx + width ; ii < ll ; ii ++ ) { char c = str . charAt ( ii ) ; if ( c == '\n' ) { buf . append ( str . substring ( lastidx , ii + 1 ) ) ; lastidx = ii + 1 ; break ; } else if ( Character . isWhitespace ( c ) ) { lastws = ii ; } } if ( lastws == lastidx ) { buf . append ( str . substring ( lastidx , lastidx + width ) ) . append ( LINE_SEPARATOR ) ; lastidx += width ; } else if ( lastws > lastidx ) { buf . append ( str . substring ( lastidx , lastws ) ) . append ( LINE_SEPARATOR ) ; lastidx = lastws + 1 ; } } return buf . toString ( ) ; }
Wordwraps a string . Treats any whitespace character as a single character .
11,863
public List < String > getI18nkeys ( ) { if ( i18nkeys == null ) { return new ArrayList < String > ( ) ; } Collections . sort ( i18nkeys , new Comparator < String > ( ) { public int compare ( String o1 , String o2 ) { return Collator . getInstance ( ) . compare ( o1 , o2 ) ; } } ) ; return i18nkeys ; }
Get keys for internationalized strings
11,864
public String xlate ( String key , Object arg ) { return _msgmgr . getMessage ( _req , key , new Object [ ] { arg } ) ; }
Looks up the specified message and creates the translation string using the supplied argument .
11,865
public String xlate ( String key , Object arg1 , Object arg2 ) { return _msgmgr . getMessage ( _req , key , new Object [ ] { arg1 , arg2 } ) ; }
Looks up the specified message and creates the translation string using the supplied arguments .
11,866
protected String date ( int style , Object arg ) { Date when = massageDate ( arg ) ; if ( when == null ) { return "<!" + arg + ">" ; } return DateFormat . getDateInstance ( style , getLocale ( ) ) . format ( when ) ; }
Helper function for formatting dates .
11,867
public boolean export ( ) throws QueryException , NoDataFoundException { start = true ; testForData ( ) ; if ( needsFirstCrossing ( ) && ! ( this instanceof FirstCrossingExporter ) ) { FirstCrossingExporter fe = new FirstCrossingExporter ( bean ) ; fe . export ( ) ; templatesValues = fe . getTemplatesValues ( ) ; groupTemplateKeys = fe . getGroupTemplateKeys ( ) ; } initExport ( ) ; printHeaderBand ( ) ; if ( ! printContentBands ( ) ) { return false ; } printFooterBand ( ) ; finishExport ( ) ; if ( ( bean . getResult ( ) != null ) && ( ! ( this instanceof FirstCrossingExporter ) ) ) { bean . getResult ( ) . close ( ) ; } if ( this instanceof FirstCrossingExporter ) { try { bean . getResult ( ) . getResultSet ( ) . beforeFirst ( ) ; } catch ( SQLException ex ) { LOG . error ( ex . getMessage ( ) , ex ) ; } } return true ; }
header page band and footer page band are written in PDF and RTF exporters
11,868
protected Set < CellElement > getIgnoredCellElements ( Band band ) { Set < CellElement > result = new HashSet < CellElement > ( ) ; int rows = band . getRowCount ( ) ; int cols = band . getColumnCount ( ) ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < cols ; j ++ ) { BandElement element = band . getElementAt ( i , j ) ; if ( element == null ) { continue ; } int rowSpan = element . getRowSpan ( ) ; int colSpan = element . getColSpan ( ) ; if ( ( rowSpan > 1 ) && ( colSpan > 1 ) ) { for ( int k = 0 ; k < rowSpan ; k ++ ) { for ( int m = 0 ; m < colSpan ; m ++ ) { if ( ( k != 0 ) || ( m != 0 ) ) { result . add ( new CellElement ( i + k , j + m ) ) ; } } } } else if ( rowSpan > 1 ) { for ( int k = 1 ; k < rowSpan ; k ++ ) { result . add ( new CellElement ( i + k , j ) ) ; } } else if ( colSpan > 1 ) { for ( int k = 1 ; k < colSpan ; k ++ ) { result . add ( new CellElement ( i , j + k ) ) ; } } } } return result ; }
and the other merged cells are null band elements .
11,869
protected Set < CellElement > getIgnoredCellElementsForColSpan ( Band band ) { Set < CellElement > result = new HashSet < CellElement > ( ) ; int rows = band . getRowCount ( ) ; int cols = band . getColumnCount ( ) ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < cols ; j ++ ) { BandElement element = band . getElementAt ( i , j ) ; if ( element == null ) { continue ; } int colSpan = element . getColSpan ( ) ; if ( colSpan > 1 ) { for ( int k = 1 ; k < colSpan ; k ++ ) { result . add ( new CellElement ( i , j + k ) ) ; } } } } return result ; }
because there was no support for row span
11,870
void fireExporterEvent ( ExporterEvent evt ) { Object [ ] listeners = listenerList . getListenerList ( ) ; for ( int i = 0 ; i < listeners . length ; i += 2 ) { if ( listeners [ i ] == ExporterEventListener . class ) { ( ( ExporterEventListener ) listeners [ i + 1 ] ) . notify ( evt ) ; } } }
This private class is used to fire ExporterEvents
11,871
private String getFunctionTemplate ( GroupCache gc , FunctionBandElement fbe , boolean previous ) throws QueryException { StringBuilder templateKey = new StringBuilder ( ) ; if ( gc == null ) { templateKey . append ( "F_" ) . append ( fbe . getFunction ( ) ) . append ( "_" ) . append ( fbe . getColumn ( ) ) ; return templateKey . toString ( ) ; } String groupColumn = gc . getGroup ( ) . getColumn ( ) ; Object groupValue ; if ( previous ) { if ( resultSetRow == 0 ) { groupValue = getResult ( ) . nextValue ( groupColumn ) ; } else { groupValue = previousRow [ getResult ( ) . getColumnIndex ( groupColumn ) ] ; } } else { groupValue = getResult ( ) . nextValue ( groupColumn ) ; } groupTemplateKeys . put ( "G" + gc . getGroup ( ) . getName ( ) , "G" + gc . getGroup ( ) . getName ( ) + "_" + previousRow [ getResult ( ) . getColumnIndex ( groupColumn ) ] ) ; templateKey . append ( "G" ) . append ( gc . getGroup ( ) . getName ( ) ) . append ( "_F_" ) . append ( fbe . getFunction ( ) ) . append ( "_" ) . append ( fbe . getColumn ( ) ) . append ( "_" ) . append ( groupValue ) ; int group = Integer . parseInt ( gc . getGroup ( ) . getName ( ) ) ; StringBuilder result = new StringBuilder ( ) ; for ( int i = 1 ; i < group ; i ++ ) { result . append ( groupTemplateKeys . get ( "G" + i ) ) . append ( "_" ) ; } result . append ( templateKey . toString ( ) ) ; return result . toString ( ) ; }
string template used by functions in header and group header bands
11,872
protected String getCurrentValueForGroup ( String group ) { Object obj = groupValues . get ( group ) ; if ( obj == null ) { return "" ; } return obj . toString ( ) ; }
group is G1 G2 ...
11,873
public static String getValueFromElement ( Element element , String tagName ) { NodeList elementNodeList = element . getElementsByTagName ( tagName ) ; if ( elementNodeList == null ) { return "" ; } else { Element tagElement = ( Element ) elementNodeList . item ( 0 ) ; if ( tagElement == null ) { return "" ; } NodeList tagNodeList = tagElement . getChildNodes ( ) ; if ( tagNodeList == null || tagNodeList . getLength ( ) == 0 ) { return "" ; } return tagNodeList . item ( 0 ) . getNodeValue ( ) ; } }
Gets the string value of the tag element name passed
11,874
public static String convertDocToString ( Document doc ) throws TransformerException { TransformerFactory transfac = TransformerFactory . newInstance ( ) ; Transformer trans = transfac . newTransformer ( ) ; trans . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , YES ) ; trans . setOutputProperty ( OutputKeys . INDENT , YES ) ; StringWriter sw = new StringWriter ( ) ; StreamResult result = new StreamResult ( sw ) ; DOMSource source = new DOMSource ( doc ) ; trans . transform ( source , result ) ; return sw . toString ( ) ; }
Convert a DOM document to a string
11,875
public static boolean writeDocumentToFile ( Document doc , String localFile ) { try { TransformerFactory transfact = TransformerFactory . newInstance ( ) ; Transformer trans = transfact . newTransformer ( ) ; trans . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , YES ) ; trans . setOutputProperty ( OutputKeys . INDENT , YES ) ; trans . transform ( new DOMSource ( doc ) , new StreamResult ( new File ( localFile ) ) ) ; return true ; } catch ( TransformerConfigurationException ex ) { LOG . warn ( ERROR_WRITING , localFile , ex ) ; return false ; } catch ( TransformerException ex ) { LOG . warn ( ERROR_WRITING , localFile , ex ) ; return false ; } }
Write the Document out to a file using nice formatting
11,876
public static void appendChild ( Document doc , Element parentElement , String elementName , String elementValue ) { Element child = doc . createElement ( elementName ) ; Text text = doc . createTextNode ( elementValue ) ; child . appendChild ( text ) ; parentElement . appendChild ( child ) ; }
Add a child element to a parent element
11,877
private static void waiting ( int milliseconds ) { long t0 , t1 ; t0 = System . currentTimeMillis ( ) ; do { t1 = System . currentTimeMillis ( ) ; } while ( ( t1 - t0 ) < milliseconds ) ; }
Wait for a few milliseconds
11,878
public Collection < CompilationUnit > execute ( ) throws IOException { List < CompilationUnit > compiledUnits = new ArrayList < CompilationUnit > ( ) ; logger . debug ( "CompilationTask: execute" ) ; long start = System . currentTimeMillis ( ) ; for ( CompilationUnit unit : compilationUnits ) { if ( compileIfDirty ( unit ) ) { compiledUnits . add ( unit ) ; } } logger . debug ( "execute finished in {} millis" , System . currentTimeMillis ( ) - start ) ; return compiledUnits ; }
Execute the lazy compilation .
11,879
public void startDaemon ( final long interval ) { if ( daemon != null ) { throw new RuntimeException ( "Trying to start daemon while it is still running" ) ; } stopDaemon = false ; daemon = new Thread ( new Runnable ( ) { public void run ( ) { try { while ( ! stopDaemon ) { try { Collection < CompilationUnit > units = execute ( ) ; if ( ! units . isEmpty ( ) && compilationListener != null ) { compilationListener . notifySuccessfulCompilation ( units ) ; } } catch ( LessParseException e ) { System . out . println ( e . getMessage ( ) ) ; } Thread . sleep ( interval ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } daemon = null ; } } , "LessCompilationDaemon" ) ; daemon . setDaemon ( true ) ; daemon . start ( ) ; }
Start a daemon thread that will execute this CompilationTask periodically .
11,880
private boolean compileIfDirty ( CompilationUnit unit ) throws IOException { if ( isDirty ( unit ) ) { logger . debug ( "compiling less: {}" , unit ) ; long start = System . currentTimeMillis ( ) ; try { String sourceMapFileName = unit . getSourceMapFile ( ) != null ? unit . getSourceMapFile ( ) . getPath ( ) : null ; CompilationDetails compilationResult = lessCompiler . compileWithDetails ( unit . getSourceAsString ( ) , unit . getResourceReader ( ) , unit . getOptions ( ) , unit . getSourceLocation ( ) , unit . getDestination ( ) . getPath ( ) , sourceMapFileName ) ; if ( unit . getDestination ( ) != null ) { unit . getDestination ( ) . getAbsoluteFile ( ) . getParentFile ( ) . mkdirs ( ) ; IOUtils . writeFile ( compilationResult . getResult ( ) , unit . getDestination ( ) , unit . getEncoding ( ) ) ; } if ( unit . getSourceMapFile ( ) != null && compilationResult . getSourceMap ( ) != null ) { unit . getSourceMapFile ( ) . getAbsoluteFile ( ) . getParentFile ( ) . mkdirs ( ) ; IOUtils . writeFile ( compilationResult . getSourceMap ( ) , unit . getSourceMapFile ( ) , unit . getEncoding ( ) ) ; } updateImportsAndCache ( unit , compilationResult . getImports ( ) ) ; logger . info ( "compilation of less {} finished in {} millis" , unit , System . currentTimeMillis ( ) - start ) ; return true ; } catch ( LessParseException e ) { unit . setExceptionTimestamp ( System . currentTimeMillis ( ) ) ; cache ( unit ) ; throw e ; } } return false ; }
Compile a CompilationUnit if dirty .
11,881
public Series getSeries ( String id , String language ) throws TvDbException { StringBuilder urlBuilder = new StringBuilder ( ) ; urlBuilder . append ( BASE_URL ) . append ( apiKey ) . append ( SERIES_URL ) . append ( id ) . append ( "/" ) ; if ( StringUtils . isNotBlank ( language ) ) { urlBuilder . append ( language ) . append ( XML_EXTENSION ) ; } LOG . trace ( URL , urlBuilder . toString ( ) ) ; List < Series > seriesList = TvdbParser . getSeriesList ( urlBuilder . toString ( ) ) ; if ( seriesList . isEmpty ( ) ) { return null ; } else { return seriesList . get ( 0 ) ; } }
Get the series information
11,882
public Episode getEpisode ( String seriesId , int seasonNbr , int episodeNbr , String language ) throws TvDbException { return getTVEpisode ( seriesId , seasonNbr , episodeNbr , language , "/default/" ) ; }
Get a specific episode s information
11,883
private Episode getTVEpisode ( String seriesId , int seasonNbr , int episodeNbr , String language , String episodeType ) throws TvDbException { if ( ! isValidNumber ( seriesId ) || ! isValidNumber ( seasonNbr ) || ! isValidNumber ( episodeNbr ) ) { return new Episode ( ) ; } StringBuilder urlBuilder = new StringBuilder ( ) ; urlBuilder . append ( BASE_URL ) . append ( apiKey ) . append ( SERIES_URL ) . append ( seriesId ) . append ( episodeType ) . append ( seasonNbr ) . append ( "/" ) . append ( episodeNbr ) . append ( "/" ) ; if ( StringUtils . isNotBlank ( language ) ) { urlBuilder . append ( language ) . append ( XML_EXTENSION ) ; } LOG . trace ( URL , urlBuilder . toString ( ) ) ; return TvdbParser . getEpisode ( urlBuilder . toString ( ) ) ; }
Generic function to get either the standard TV episode list or the DVD list
11,884
public List < Actor > getActors ( String seriesId ) throws TvDbException { StringBuilder urlBuilder = new StringBuilder ( ) ; urlBuilder . append ( BASE_URL ) . append ( apiKey ) . append ( SERIES_URL ) . append ( seriesId ) . append ( "/actors.xml" ) ; LOG . trace ( URL , urlBuilder . toString ( ) ) ; return TvdbParser . getActors ( urlBuilder . toString ( ) ) ; }
Get a list of actors from the series id
11,885
public List < Series > searchSeries ( String title , String language ) throws TvDbException { StringBuilder urlBuilder = new StringBuilder ( ) ; try { urlBuilder . append ( BASE_URL ) . append ( "GetSeries.php?seriesname=" ) . append ( URLEncoder . encode ( title , "UTF-8" ) ) ; if ( StringUtils . isNotBlank ( language ) ) { urlBuilder . append ( "&language=" ) . append ( language ) ; } } catch ( UnsupportedEncodingException ex ) { LOG . trace ( "Failed to encode title: {}" , title , ex ) ; urlBuilder . append ( title ) ; } LOG . trace ( URL , urlBuilder . toString ( ) ) ; return TvdbParser . getSeriesList ( urlBuilder . toString ( ) ) ; }
Get a list of series using a title and language
11,886
public Episode getEpisodeById ( String episodeId , String language ) throws TvDbException { StringBuilder urlBuilder = new StringBuilder ( ) ; urlBuilder . append ( BASE_URL ) . append ( apiKey ) . append ( "/episodes/" ) . append ( episodeId ) . append ( "/" ) ; if ( StringUtils . isNotBlank ( language ) ) { urlBuilder . append ( language ) ; urlBuilder . append ( XML_EXTENSION ) ; } LOG . trace ( URL , urlBuilder . toString ( ) ) ; return TvdbParser . getEpisode ( urlBuilder . toString ( ) ) ; }
Get information for a specific episode
11,887
public TVDBUpdates getWeeklyUpdates ( int seriesId ) throws TvDbException { StringBuilder urlBuilder = new StringBuilder ( ) ; urlBuilder . append ( BASE_URL ) . append ( apiKey ) . append ( WEEKLY_UPDATES_URL ) ; LOG . trace ( URL , urlBuilder . toString ( ) ) ; return TvdbParser . getUpdates ( urlBuilder . toString ( ) , seriesId ) ; }
Get the weekly updates limited by Series ID
11,888
public static List < Actor > getActors ( String urlString ) throws TvDbException { List < Actor > results = new ArrayList < > ( ) ; Actor actor ; Document doc ; NodeList nlActor ; Node nActor ; Element eActor ; try { doc = DOMHelper . getEventDocFromUrl ( urlString ) ; if ( doc == null ) { return results ; } } catch ( WebServiceException ex ) { LOG . trace ( ERROR_GET_XML , ex ) ; return results ; } nlActor = doc . getElementsByTagName ( "Actor" ) ; for ( int loop = 0 ; loop < nlActor . getLength ( ) ; loop ++ ) { nActor = nlActor . item ( loop ) ; if ( nActor . getNodeType ( ) == Node . ELEMENT_NODE ) { eActor = ( Element ) nActor ; actor = new Actor ( ) ; actor . setId ( DOMHelper . getValueFromElement ( eActor , "id" ) ) ; String image = DOMHelper . getValueFromElement ( eActor , "Image" ) ; if ( ! image . isEmpty ( ) ) { actor . setImage ( URL_BANNER + image ) ; } actor . setName ( DOMHelper . getValueFromElement ( eActor , "Name" ) ) ; actor . setRole ( DOMHelper . getValueFromElement ( eActor , "Role" ) ) ; actor . setSortOrder ( DOMHelper . getValueFromElement ( eActor , "SortOrder" ) ) ; results . add ( actor ) ; } } Collections . sort ( results ) ; return results ; }
Get a list of the actors from the URL
11,889
public static List < Episode > getAllEpisodes ( String urlString , int season ) throws TvDbException { List < Episode > episodeList = new ArrayList < > ( ) ; Episode episode ; NodeList nlEpisode ; Node nEpisode ; Element eEpisode ; Document doc = DOMHelper . getEventDocFromUrl ( urlString ) ; nlEpisode = doc . getElementsByTagName ( EPISODE ) ; for ( int loop = 0 ; loop < nlEpisode . getLength ( ) ; loop ++ ) { nEpisode = nlEpisode . item ( loop ) ; if ( nEpisode . getNodeType ( ) == Node . ELEMENT_NODE ) { eEpisode = ( Element ) nEpisode ; episode = parseNextEpisode ( eEpisode ) ; if ( ( episode != null ) && ( season == - 1 || episode . getSeasonNumber ( ) == season ) ) { episodeList . add ( episode ) ; } } } return episodeList ; }
Get all the episodes from the URL
11,890
public static Banners getBanners ( String urlString ) throws TvDbException { Banners banners = new Banners ( ) ; Banner banner ; NodeList nlBanners ; Node nBanner ; Element eBanner ; Document doc = DOMHelper . getEventDocFromUrl ( urlString ) ; if ( doc != null ) { nlBanners = doc . getElementsByTagName ( BANNER ) ; for ( int loop = 0 ; loop < nlBanners . getLength ( ) ; loop ++ ) { nBanner = nlBanners . item ( loop ) ; if ( nBanner . getNodeType ( ) == Node . ELEMENT_NODE ) { eBanner = ( Element ) nBanner ; banner = parseNextBanner ( eBanner ) ; banners . addBanner ( banner ) ; } } } return banners ; }
Get a list of banners from the URL
11,891
public static Episode getEpisode ( String urlString ) throws TvDbException { Episode episode = new Episode ( ) ; NodeList nlEpisode ; Node nEpisode ; Element eEpisode ; Document doc = DOMHelper . getEventDocFromUrl ( urlString ) ; if ( doc == null ) { return new Episode ( ) ; } nlEpisode = doc . getElementsByTagName ( EPISODE ) ; for ( int loop = 0 ; loop < nlEpisode . getLength ( ) ; loop ++ ) { nEpisode = nlEpisode . item ( loop ) ; if ( nEpisode . getNodeType ( ) == Node . ELEMENT_NODE ) { eEpisode = ( Element ) nEpisode ; episode = parseNextEpisode ( eEpisode ) ; if ( episode != null ) { break ; } } } return episode ; }
Get the episode information from the URL
11,892
public static List < Series > getSeriesList ( String urlString ) throws TvDbException { List < Series > seriesList = new ArrayList < > ( ) ; Series series ; NodeList nlSeries ; Node nSeries ; Element eSeries ; Document doc = DOMHelper . getEventDocFromUrl ( urlString ) ; if ( doc == null ) { return Collections . emptyList ( ) ; } nlSeries = doc . getElementsByTagName ( SERIES ) ; for ( int loop = 0 ; loop < nlSeries . getLength ( ) ; loop ++ ) { nSeries = nlSeries . item ( loop ) ; if ( nSeries . getNodeType ( ) == Node . ELEMENT_NODE ) { eSeries = ( Element ) nSeries ; series = parseNextSeries ( eSeries ) ; if ( series != null ) { seriesList . add ( series ) ; } } } return seriesList ; }
Get a list of series from the URL
11,893
public static TVDBUpdates getUpdates ( String urlString , int seriesId ) throws TvDbException { TVDBUpdates updates = new TVDBUpdates ( ) ; Document doc = DOMHelper . getEventDocFromUrl ( urlString ) ; if ( doc != null ) { Node root = doc . getChildNodes ( ) . item ( 0 ) ; List < SeriesUpdate > seriesUpdates = new ArrayList < > ( ) ; List < EpisodeUpdate > episodeUpdates = new ArrayList < > ( ) ; List < BannerUpdate > bannerUpdates = new ArrayList < > ( ) ; NodeList updateNodes = root . getChildNodes ( ) ; Node updateNode ; for ( int i = 0 ; i < updateNodes . getLength ( ) ; i ++ ) { updateNode = updateNodes . item ( i ) ; switch ( updateNode . getNodeName ( ) ) { case SERIES : SeriesUpdate su = parseNextSeriesUpdate ( ( Element ) updateNode ) ; if ( isValidUpdate ( seriesId , su ) ) { seriesUpdates . add ( su ) ; } break ; case EPISODE : EpisodeUpdate eu = parseNextEpisodeUpdate ( ( Element ) updateNode ) ; if ( isValidUpdate ( seriesId , eu ) ) { episodeUpdates . add ( eu ) ; } break ; case BANNER : BannerUpdate bu = parseNextBannerUpdate ( ( Element ) updateNode ) ; if ( isValidUpdate ( seriesId , bu ) ) { bannerUpdates . add ( bu ) ; } break ; default : LOG . warn ( "Unknown update type '{}'" , updateNode . getNodeName ( ) ) ; } } updates . setTime ( DOMHelper . getValueFromElement ( ( Element ) root , TIME ) ) ; updates . setSeriesUpdates ( seriesUpdates ) ; updates . setEpisodeUpdates ( episodeUpdates ) ; updates . setBannerUpdates ( bannerUpdates ) ; } return updates ; }
Get a list of updates from the URL
11,894
public static String parseErrorMessage ( String errorMessage ) { StringBuilder response = new StringBuilder ( ) ; Pattern pattern = Pattern . compile ( ".*?/series/(\\d*?)/default/(\\d*?)/(\\d*?)/.*?" ) ; Matcher matcher = pattern . matcher ( errorMessage ) ; if ( matcher . find ( ) && matcher . groupCount ( ) == ERROR_MSG_GROUP_COUNT ) { int seriesId = Integer . parseInt ( matcher . group ( ERROR_MSG_SERIES ) ) ; int seasonId = Integer . parseInt ( matcher . group ( ERROR_MSG_SEASON ) ) ; int episodeId = Integer . parseInt ( matcher . group ( ERROR_MSG_EPISODE ) ) ; response . append ( "Series Id: " ) . append ( seriesId ) ; response . append ( ", Season: " ) . append ( seasonId ) ; response . append ( ", Episode: " ) . append ( episodeId ) ; response . append ( ": " ) ; if ( episodeId == 0 ) { response . append ( "Episode seems to be a misnamed pilot episode." ) ; } else if ( episodeId > MAX_EPISODE ) { response . append ( "Episode number seems to be too large." ) ; } else if ( seasonId == 0 && episodeId > 1 ) { response . append ( "This special episode does not exist." ) ; } else if ( errorMessage . toLowerCase ( ) . contains ( ERROR_NOT_ALLOWED_IN_PROLOG ) ) { response . append ( ERROR_RETRIEVE_EPISODE_INFO ) ; } else { response . append ( "Unknown episode error: " ) . append ( errorMessage ) ; } } else { if ( errorMessage . toLowerCase ( ) . contains ( ERROR_NOT_ALLOWED_IN_PROLOG ) ) { response . append ( ERROR_RETRIEVE_EPISODE_INFO ) ; } else { response . append ( "Episode error: " ) . append ( errorMessage ) ; } } return response . toString ( ) ; }
Parse the error message to return a more user friendly message
11,895
private static List < String > parseList ( String input , String delim ) { List < String > result = new ArrayList < > ( ) ; StringTokenizer st = new StringTokenizer ( input , delim ) ; while ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) . trim ( ) ; if ( token . length ( ) > 0 ) { result . add ( token ) ; } } return result ; }
Create a List from a delimited string
11,896
private static Banner parseNextBanner ( Element eBanner ) { Banner banner = new Banner ( ) ; String artwork ; artwork = DOMHelper . getValueFromElement ( eBanner , BANNER_PATH ) ; if ( ! artwork . isEmpty ( ) ) { banner . setUrl ( URL_BANNER + artwork ) ; } artwork = DOMHelper . getValueFromElement ( eBanner , VIGNETTE_PATH ) ; if ( ! artwork . isEmpty ( ) ) { banner . setVignette ( URL_BANNER + artwork ) ; } artwork = DOMHelper . getValueFromElement ( eBanner , THUMBNAIL_PATH ) ; if ( ! artwork . isEmpty ( ) ) { banner . setThumb ( URL_BANNER + artwork ) ; } banner . setId ( DOMHelper . getValueFromElement ( eBanner , "id" ) ) ; banner . setBannerType ( BannerListType . fromString ( DOMHelper . getValueFromElement ( eBanner , "BannerType" ) ) ) ; banner . setBannerType2 ( BannerType . fromString ( DOMHelper . getValueFromElement ( eBanner , "BannerType2" ) ) ) ; banner . setLanguage ( DOMHelper . getValueFromElement ( eBanner , LANGUAGE ) ) ; banner . setSeason ( DOMHelper . getValueFromElement ( eBanner , "Season" ) ) ; banner . setColours ( DOMHelper . getValueFromElement ( eBanner , "Colors" ) ) ; banner . setRating ( DOMHelper . getValueFromElement ( eBanner , RATING ) ) ; banner . setRatingCount ( DOMHelper . getValueFromElement ( eBanner , "RatingCount" ) ) ; try { banner . setSeriesName ( Boolean . parseBoolean ( DOMHelper . getValueFromElement ( eBanner , SERIES_NAME ) ) ) ; } catch ( WebServiceException ex ) { LOG . trace ( "Failed to transform SeriesName to boolean" , ex ) ; banner . setSeriesName ( false ) ; } return banner ; }
Parse the banner record from the document
11,897
private static Episode parseNextEpisode ( Element eEpisode ) { Episode episode = new Episode ( ) ; episode . setId ( DOMHelper . getValueFromElement ( eEpisode , "id" ) ) ; episode . setCombinedEpisodeNumber ( DOMHelper . getValueFromElement ( eEpisode , "Combined_episodenumber" ) ) ; episode . setCombinedSeason ( DOMHelper . getValueFromElement ( eEpisode , "Combined_season" ) ) ; episode . setDvdChapter ( DOMHelper . getValueFromElement ( eEpisode , "DVD_chapter" ) ) ; episode . setDvdDiscId ( DOMHelper . getValueFromElement ( eEpisode , "DVD_discid" ) ) ; episode . setDvdEpisodeNumber ( DOMHelper . getValueFromElement ( eEpisode , "DVD_episodenumber" ) ) ; episode . setDvdSeason ( DOMHelper . getValueFromElement ( eEpisode , "DVD_season" ) ) ; episode . setDirectors ( parseList ( DOMHelper . getValueFromElement ( eEpisode , "Director" ) , "|," ) ) ; episode . setEpImgFlag ( DOMHelper . getValueFromElement ( eEpisode , "EpImgFlag" ) ) ; episode . setEpisodeName ( DOMHelper . getValueFromElement ( eEpisode , "EpisodeName" ) ) ; episode . setEpisodeNumber ( getEpisodeValue ( eEpisode , "EpisodeNumber" ) ) ; episode . setFirstAired ( DOMHelper . getValueFromElement ( eEpisode , FIRST_AIRED ) ) ; episode . setGuestStars ( parseList ( DOMHelper . getValueFromElement ( eEpisode , "GuestStars" ) , "|," ) ) ; episode . setImdbId ( DOMHelper . getValueFromElement ( eEpisode , IMDB_ID ) ) ; episode . setLanguage ( DOMHelper . getValueFromElement ( eEpisode , LANGUAGE ) ) ; episode . setOverview ( DOMHelper . getValueFromElement ( eEpisode , OVERVIEW ) ) ; episode . setProductionCode ( DOMHelper . getValueFromElement ( eEpisode , "ProductionCode" ) ) ; episode . setRating ( DOMHelper . getValueFromElement ( eEpisode , RATING ) ) ; episode . setSeasonNumber ( getEpisodeValue ( eEpisode , "SeasonNumber" ) ) ; episode . setWriters ( parseList ( DOMHelper . getValueFromElement ( eEpisode , "Writer" ) , "|," ) ) ; episode . setAbsoluteNumber ( DOMHelper . getValueFromElement ( eEpisode , "absolute_number" ) ) ; String filename = DOMHelper . getValueFromElement ( eEpisode , "filename" ) ; if ( StringUtils . isNotBlank ( filename ) ) { episode . setFilename ( URL_BANNER + filename ) ; } episode . setLastUpdated ( DOMHelper . getValueFromElement ( eEpisode , LAST_UPDATED ) ) ; episode . setSeasonId ( DOMHelper . getValueFromElement ( eEpisode , "seasonid" ) ) ; episode . setSeriesId ( DOMHelper . getValueFromElement ( eEpisode , "seriesid" ) ) ; episode . setAirsAfterSeason ( getEpisodeValue ( eEpisode , "airsafter_season" ) ) ; episode . setAirsBeforeEpisode ( getEpisodeValue ( eEpisode , "airsbefore_episode" ) ) ; episode . setAirsBeforeSeason ( getEpisodeValue ( eEpisode , "airsbefore_season" ) ) ; return episode ; }
Parse the document for episode information
11,898
private static int getEpisodeValue ( Element eEpisode , String key ) { int episodeValue ; try { String value = DOMHelper . getValueFromElement ( eEpisode , key ) ; episodeValue = NumberUtils . toInt ( value , 0 ) ; } catch ( WebServiceException ex ) { LOG . trace ( "Failed to read episode value" , ex ) ; episodeValue = 0 ; } return episodeValue ; }
Process the key from the element into an integer .
11,899
private static Series parseNextSeries ( Element eSeries ) { Series series = new Series ( ) ; series . setId ( DOMHelper . getValueFromElement ( eSeries , "id" ) ) ; series . setActors ( parseList ( DOMHelper . getValueFromElement ( eSeries , "Actors" ) , "|," ) ) ; series . setAirsDayOfWeek ( DOMHelper . getValueFromElement ( eSeries , "Airs_DayOfWeek" ) ) ; series . setAirsTime ( DOMHelper . getValueFromElement ( eSeries , "Airs_Time" ) ) ; series . setContentRating ( DOMHelper . getValueFromElement ( eSeries , "ContentRating" ) ) ; series . setFirstAired ( DOMHelper . getValueFromElement ( eSeries , FIRST_AIRED ) ) ; series . setGenres ( parseList ( DOMHelper . getValueFromElement ( eSeries , "Genre" ) , "|," ) ) ; series . setImdbId ( DOMHelper . getValueFromElement ( eSeries , IMDB_ID ) ) ; series . setLanguage ( DOMHelper . getValueFromElement ( eSeries , "language" ) ) ; series . setNetwork ( DOMHelper . getValueFromElement ( eSeries , "Network" ) ) ; series . setOverview ( DOMHelper . getValueFromElement ( eSeries , OVERVIEW ) ) ; series . setRating ( DOMHelper . getValueFromElement ( eSeries , RATING ) ) ; series . setRuntime ( DOMHelper . getValueFromElement ( eSeries , "Runtime" ) ) ; series . setSeriesId ( DOMHelper . getValueFromElement ( eSeries , "SeriesID" ) ) ; series . setSeriesName ( DOMHelper . getValueFromElement ( eSeries , SERIES_NAME ) ) ; series . setStatus ( DOMHelper . getValueFromElement ( eSeries , "Status" ) ) ; String artwork = DOMHelper . getValueFromElement ( eSeries , TYPE_BANNER ) ; if ( ! artwork . isEmpty ( ) ) { series . setBanner ( URL_BANNER + artwork ) ; } artwork = DOMHelper . getValueFromElement ( eSeries , TYPE_FANART ) ; if ( ! artwork . isEmpty ( ) ) { series . setFanart ( URL_BANNER + artwork ) ; } artwork = DOMHelper . getValueFromElement ( eSeries , TYPE_POSTER ) ; if ( ! artwork . isEmpty ( ) ) { series . setPoster ( URL_BANNER + artwork ) ; } series . setLastUpdated ( DOMHelper . getValueFromElement ( eSeries , LAST_UPDATED ) ) ; series . setZap2ItId ( DOMHelper . getValueFromElement ( eSeries , "zap2it_id" ) ) ; return series ; }
Parse the series record from the document