idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
11,400
public static SiteIdentifier single ( final int siteId , final String siteString ) { return new SiteIdentifier ( ) { public int identifySite ( HttpServletRequest req ) { return siteId ; } public String getSiteString ( int siteId ) { return siteString ; } public int getSiteId ( String siteString ) { return siteId ; } public Iterator < Site > enumerateSites ( ) { return Collections . singletonList ( new Site ( siteId , siteString ) ) . iterator ( ) ; } } ; }
Returns a site identifier that returns the specified site always .
11,401
public static String generateRandomKey ( Random rand , int length ) { int numKeyChars = KEY_CHARS . length ( ) ; StringBuilder buf = new StringBuilder ( ) ; for ( int ii = 0 ; ii < length ; ii ++ ) { buf . append ( KEY_CHARS . charAt ( rand . nextInt ( numKeyChars ) ) ) ; } return buf . toString ( ) ; }
Return a key of the given length that contains random numbers .
11,402
public static boolean verifyLuhn ( String key ) { if ( StringUtil . isBlank ( key ) || key . matches ( ".*\\D.*" ) || key . matches ( "^[0]+$" ) ) { return false ; } return ( getLuhnRemainder ( key ) == 0 ) ; }
Verify the key with the Luhn check . If the key is all zeros then the luhn check is true but that is almost never what you want so explicitly check for zero and return false if it is .
11,403
public static int getLuhnRemainder ( String key ) { int len = key . length ( ) ; int sum = 0 ; for ( int multSeq = len % 2 , ii = 0 ; ii < len ; ii ++ ) { int c = key . charAt ( ii ) - '0' ; if ( ii % 2 == multSeq ) { c *= 2 ; } sum += ( c / 10 ) + ( c % 10 ) ; } return sum % 10 ; }
Return the luhn remainder for the given key .
11,404
public static void configureDefaultHandler ( Formatter formatter ) { Logger logger = LogManager . getLogManager ( ) . getLogger ( "" ) ; for ( Handler handler : logger . getHandlers ( ) ) { handler . setFormatter ( formatter ) ; } }
Configures the default logging handler to use an instance of the specified formatter when formatting messages .
11,405
public static void reverse ( byte [ ] values , int offset , int length ) { int aidx = offset ; int bidx = offset + length - 1 ; while ( bidx > aidx ) { byte value = values [ aidx ] ; values [ aidx ] = values [ bidx ] ; values [ bidx ] = value ; aidx ++ ; bidx -- ; } }
Reverses a subset of elements within the specified array .
11,406
public static void shuffle ( Object [ ] values , Random rnd ) { shuffle ( values , 0 , values . length , rnd ) ; }
Shuffles the elements in the given array into a random sequence .
11,407
public static byte [ ] insert ( byte [ ] values , byte value , int index ) { byte [ ] nvalues = new byte [ values . length + 1 ] ; if ( index > 0 ) { System . arraycopy ( values , 0 , nvalues , 0 , index ) ; } nvalues [ index ] = value ; if ( index < values . length ) { System . arraycopy ( values , index , nvalues , index + 1 , values . length - index ) ; } return nvalues ; }
Creates a new array one larger than the supplied array and with the specified value inserted into the specified slot .
11,408
public static < T extends Object > T [ ] insert ( T [ ] values , T value , int index ) { @ SuppressWarnings ( "unchecked" ) T [ ] nvalues = ( T [ ] ) Array . newInstance ( values . getClass ( ) . getComponentType ( ) , values . length + 1 ) ; if ( index > 0 ) { System . arraycopy ( values , 0 , nvalues , 0 , index ) ; } nvalues [ index ] = value ; if ( index < values . length ) { System . arraycopy ( values , index , nvalues , index + 1 , values . length - index ) ; } return nvalues ; }
Creates a new array one larger than the supplied array and with the specified value inserted into the specified slot . The type of the values array will be preserved .
11,409
public static < T extends Object > T [ ] append ( T [ ] values , T value ) { return insert ( values , value , values . length ) ; }
Creates a new array one larger than the supplied array and with the specified value inserted into the last slot . The type of the values array will be preserved .
11,410
public static IntSet difference ( IntSet set1 , IntSet set2 ) { return and ( set1 , notView ( set2 ) ) ; }
Creates a new IntSet initially populated with ints contained in set1 but not in set2 . Set2 may also contain elements not present in set1 these are ignored .
11,411
protected static void checkNotNull ( Object [ ] array ) { checkNotNull ( ( Object ) array ) ; for ( Object o : array ) { checkNotNull ( o ) ; } }
Validate the specified arguments .
11,412
public void setSentinel ( int sentinel ) { if ( _sentinel == sentinel ) { return ; } if ( contains ( sentinel ) ) { throw new IllegalArgumentException ( "Set contains sentinel value " + sentinel ) ; } for ( int ii = 0 ; ii < _buckets . length ; ii ++ ) { if ( _buckets [ ii ] == _sentinel ) { _buckets [ ii ] = sentinel ; } } _sentinel = sentinel ; }
Sets the sentinel value which cannot itself be stored in the set because it is used internally to represent an unused location .
11,413
public Interator interator ( ) { return new AbstractInterator ( ) { public boolean hasNext ( ) { checkConcurrentModification ( ) ; return _pos < _size ; } public int nextInt ( ) { checkConcurrentModification ( ) ; if ( _pos >= _size ) { throw new NoSuchElementException ( ) ; } if ( _idx == 0 ) { while ( _buckets [ _idx ++ ] != _sentinel ) ; } int mask = _buckets . length - 1 ; for ( ; _pos < _size ; _idx ++ ) { int value = _buckets [ _idx & mask ] ; if ( value != _sentinel ) { _pos ++ ; _idx ++ ; return value ; } } throw new RuntimeException ( "Ran out of elements getting next" ) ; } public void remove ( ) { checkConcurrentModification ( ) ; if ( _idx == 0 ) { throw new IllegalStateException ( "Next method not yet called" ) ; } int pidx = ( -- _idx ) & ( _buckets . length - 1 ) ; if ( _buckets [ pidx ] == _sentinel ) { throw new IllegalStateException ( "No element to remove" ) ; } _buckets [ pidx ] = _sentinel ; _pos -- ; _size -- ; _omodcount = ++ _modcount ; shift ( pidx ) ; } protected void checkConcurrentModification ( ) { if ( _modcount != _omodcount ) { throw new ConcurrentModificationException ( ) ; } } protected int _pos , _idx ; protected int _omodcount = _modcount ; } ; }
documentation inherited from interface IntSet
11,414
protected void rehash ( int ncount ) { int [ ] obuckets = _buckets ; createBuckets ( ncount ) ; for ( int idx = 0 , pos = 0 ; pos < _size ; idx ++ ) { int value = obuckets [ idx ] ; if ( value != _sentinel ) { readd ( value ) ; pos ++ ; } } }
Recreates the bucket array with the specified new count .
11,415
protected void readd ( int value ) { int mask = _buckets . length - 1 ; int start = hash ( value ) & mask , idx = start ; do { if ( _buckets [ idx ] == _sentinel ) { _buckets [ idx ] = value ; return ; } } while ( ( idx = idx + 1 & mask ) != start ) ; throw new RuntimeException ( "Ran out of buckets readding value " + value ) ; }
Adds a value that we know is neither equal to the sentinel nor already in the set .
11,416
private void writeObject ( ObjectOutputStream out ) throws IOException { out . defaultWriteObject ( ) ; for ( int idx = 0 , pos = 0 ; pos < _size ; idx ++ ) { int value = _buckets [ idx ] ; if ( value != _sentinel ) { out . writeInt ( value ) ; pos ++ ; } } }
Custom serializer .
11,417
private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; createBuckets ( getBucketCount ( _size ) ) ; for ( int ii = 0 ; ii < _size ; ii ++ ) { readd ( in . readInt ( ) ) ; } }
Custom deserializer .
11,418
protected static int getBucketCount ( int capacity , float loadFactor ) { int size = ( int ) ( capacity / loadFactor ) ; int highest = Integer . highestOneBit ( size ) ; return Math . max ( ( size == highest ) ? highest : ( highest << 1 ) , MIN_BUCKET_COUNT ) ; }
Computes the number of buckets needed to provide the given capacity with the specified load factor .
11,419
private void setGridAxisColors ( ro . nextreports . jofc2 . model . Chart flashChart , XAxis xAxis , YAxis yAxis ) { boolean isHorizontal = chart . getType ( ) . isHorizontal ( ) ; Color xGridColor = chart . getXGridColor ( ) ; Color yGridColor = chart . getYGridColor ( ) ; if ( xGridColor != null ) { getXAxis ( xAxis , yAxis , isHorizontal ) . setGridColour ( getHexColor ( xGridColor ) ) ; } if ( ( chart . getXShowGrid ( ) != null ) && ! chart . getXShowGrid ( ) ) { if ( flashChart . getBackgroundColour ( ) == null ) { getXAxis ( xAxis , yAxis , isHorizontal ) . setGridColour ( getHexColor ( DEFAULT_BACKGROUND ) ) ; } else { getXAxis ( xAxis , yAxis , isHorizontal ) . setGridColour ( flashChart . getBackgroundColour ( ) ) ; } } if ( yGridColor != null ) { getYAxis ( xAxis , yAxis , isHorizontal ) . setGridColour ( getHexColor ( yGridColor ) ) ; } if ( ( chart . getYShowGrid ( ) != null ) && ! chart . getYShowGrid ( ) ) { if ( flashChart . getBackgroundColour ( ) == null ) { getYAxis ( xAxis , yAxis , isHorizontal ) . setGridColour ( getHexColor ( DEFAULT_BACKGROUND ) ) ; } else { getYAxis ( xAxis , yAxis , isHorizontal ) . setGridColour ( flashChart . getBackgroundColour ( ) ) ; } } }
to hide a grid we set its color to chart background color
11,420
private void setTicks ( XAxis xAxis , YAxis yAxis , boolean showXLabel , boolean showYLabel ) { boolean isHorizontal = chart . getType ( ) . isHorizontal ( ) ; if ( ( ! showXLabel && ! isHorizontal ) || ( ! showYLabel && isHorizontal ) ) { xAxis . setTickHeight ( 0 ) ; } if ( ( ! showYLabel && ! isHorizontal ) || ( ! showXLabel && isHorizontal ) ) { yAxis . setTickLength ( 0 ) ; } }
hide ticks if we do not show labels
11,421
public void hijack ( ) { _mls = _comp . getMouseListeners ( ) ; for ( int ii = 0 ; ii < _mls . length ; ii ++ ) { _comp . removeMouseListener ( _mls [ ii ] ) ; } _mmls = _comp . getMouseMotionListeners ( ) ; for ( int ii = 0 ; ii < _mmls . length ; ii ++ ) { _comp . removeMouseMotionListener ( _mmls [ ii ] ) ; } _comp . addMouseMotionListener ( _motionCatcher ) ; }
Hijack the component s mouse listeners .
11,422
public static Cookie getCookie ( HttpServletRequest req , String name ) { Cookie [ ] cookies = req . getCookies ( ) ; if ( cookies != null ) { for ( int ii = 0 , nn = cookies . length ; ii < nn ; ii ++ ) { if ( cookies [ ii ] . getName ( ) . equals ( name ) ) { return cookies [ ii ] ; } } } return null ; }
Get the cookie of the specified name or null if not found .
11,423
public static String getCookieValue ( HttpServletRequest req , String name ) { Cookie c = getCookie ( req , name ) ; return ( c == null ) ? null : c . getValue ( ) ; }
Get the value of the cookie for the cookie of the specified name or null if not found .
11,424
public static void clearCookie ( HttpServletResponse rsp , String name ) { Cookie c = new Cookie ( name , "x" ) ; c . setPath ( "/" ) ; c . setMaxAge ( 0 ) ; rsp . addCookie ( c ) ; }
Clear the cookie with the specified name .
11,425
public final String translate ( InvocationContext ctx , String msg ) { return _msgmgr . getMessage ( ctx . getRequest ( ) , msg ) ; }
A convenience function for translating messages .
11,426
private void addMetaData ( ) { document . addTitle ( getDocumentTitle ( ) ) ; document . addAuthor ( ReleaseInfoAdapter . getCompany ( ) ) ; document . addCreator ( "NextReports " + ReleaseInfoAdapter . getVersionNumber ( ) ) ; document . addSubject ( "Created by NextReports Designer" + ReleaseInfoAdapter . getVersionNumber ( ) ) ; document . addCreationDate ( ) ; document . addKeywords ( ReleaseInfoAdapter . getHome ( ) ) ; }
to opening the document
11,427
public void reinit ( int operations , long period ) { _period = period ; if ( operations != _ops . length ) { long [ ] ops = new long [ operations ] ; if ( operations > _ops . length ) { int lastOp = _lastOp + operations - _ops . length ; System . arraycopy ( _ops , 0 , ops , 0 , _lastOp ) ; System . arraycopy ( _ops , _lastOp , ops , lastOp , _ops . length - _lastOp ) ; } else { int endCount = Math . min ( operations , _ops . length - _lastOp ) ; System . arraycopy ( _ops , _lastOp , ops , 0 , endCount ) ; System . arraycopy ( _ops , 0 , ops , endCount , operations - endCount ) ; _lastOp = 0 ; } _ops = ops ; } }
Updates the number of operations for this throttle to a new maximum retaining the current history of operations if the limit is being increased and truncating the oldest operations if the limit is decreased .
11,428
public static String stripBlankLines ( String text ) { if ( text == null ) { return null ; } try { StringBuffer output = new StringBuffer ( ) ; BufferedReader in = new BufferedReader ( new StringReader ( text ) ) ; boolean doneOneLine = false ; while ( true ) { String line = in . readLine ( ) ; if ( line == null ) { break ; } if ( line . trim ( ) . length ( ) > 0 ) { output . append ( line ) ; output . append ( '\n' ) ; doneOneLine = true ; } } if ( ! doneOneLine ) { output . append ( '\n' ) ; } return output . toString ( ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( e ) ; } }
Remove all blank lines from a string . A blank line is defined to be a line where the only characters are whitespace . We always ensure that the line contains a newline at the end .
11,429
public static String stripMultiLineComments ( String text ) { if ( text == null ) { return null ; } try { StringBuffer output = new StringBuffer ( ) ; boolean inMultiLine = false ; BufferedReader in = new BufferedReader ( new StringReader ( text ) ) ; while ( true ) { String line = in . readLine ( ) ; if ( line == null ) { break ; } if ( ! inMultiLine ) { int cstart = line . indexOf ( COMMENT_MULTILINE_START ) ; if ( cstart >= 0 ) { int cend = line . indexOf ( COMMENT_MULTILINE_END , cstart + COMMENT_MULTILINE_START . length ( ) ) ; if ( cend >= 0 ) { line = line . substring ( 0 , cstart ) + SPACE + line . substring ( cend + COMMENT_MULTILINE_END . length ( ) ) ; } else { inMultiLine = true ; line = line . substring ( 0 , cstart ) + SPACE ; } } else { } } else { int cend = line . indexOf ( COMMENT_MULTILINE_END ) ; if ( cend >= 0 ) { line = line . substring ( cend + COMMENT_MULTILINE_END . length ( ) ) ; inMultiLine = false ; } else { line = SPACE ; } } output . append ( line ) ; output . append ( '\n' ) ; } return output . toString ( ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( e ) ; } }
Remove all the multi - line comments from a block of text
11,430
public static String stripSingleLineComments ( String text ) { if ( text == null ) { return null ; } try { StringBuffer output = new StringBuffer ( ) ; BufferedReader in = new BufferedReader ( new StringReader ( text ) ) ; while ( true ) { String line = in . readLine ( ) ; if ( line == null ) { break ; } int cstart = line . indexOf ( COMMENT_SINGLELINE_START ) ; if ( cstart >= 0 ) { line = line . substring ( 0 , cstart ) ; } output . append ( line ) ; output . append ( '\n' ) ; } return output . toString ( ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( e ) ; } }
Remove all the single - line comments from a block of text
11,431
public static String trimLines ( String text ) { if ( text == null ) { return null ; } try { StringBuffer output = new StringBuffer ( ) ; BufferedReader in = new BufferedReader ( new StringReader ( text ) ) ; while ( true ) { String line = in . readLine ( ) ; if ( line == null ) { break ; } output . append ( line . trim ( ) ) ; output . append ( '\n' ) ; } return output . toString ( ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( e ) ; } }
Remove any leading or trailing spaces from a line of code . This function could be improved by making it strip unnecessary double spaces but since we would need to leave double spaces inside strings this is not simple and since the benefit is small we ll leave it for now
11,432
public static String deleteExcededSpaces ( String text ) { int size = text . length ( ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < size ; i ++ ) { char ch = text . charAt ( i ) ; if ( ch == ' ' ) { if ( i > 0 ) { char ch2 = text . charAt ( i - 1 ) ; if ( ( ch2 != ' ' ) && ( i < size - 1 ) && ( ! text . substring ( i + 1 ) . trim ( ) . equals ( "" ) ) ) { sb . append ( ch ) ; } } } else { sb . append ( ch ) ; } } return sb . toString ( ) ; }
Only one space between words .
11,433
public User loadUser ( HttpServletRequest req ) throws PersistenceException { String authcook = CookieUtil . getCookieValue ( req , _userAuthCookie ) ; if ( USERMGR_DEBUG ) { log . info ( "Loading user by cookie" , _userAuthCookie , authcook ) ; } return loadUser ( authcook ) ; }
Fetches the necessary authentication information from the http request and loads the user identified by that information .
11,434
public User loadUser ( String authcode ) throws PersistenceException { User user = ( authcode == null ) ? null : _repository . loadUserBySession ( authcode ) ; if ( USERMGR_DEBUG ) { log . info ( "Loaded user by authcode" , "code" , authcode , "user" , user ) ; } return user ; }
Loads up a user based on the supplied session authentication token .
11,435
public User login ( String username , Password password , boolean persist , HttpServletRequest req , HttpServletResponse rsp , Authenticator auth ) throws PersistenceException , AuthenticationFailedException { User user = _repository . loadUser ( username ) ; if ( user == null ) { throw new NoSuchUserException ( "error.no_such_user" ) ; } auth . authenticateUser ( user , username , password ) ; effectLogin ( user , persist ? PERSIST_EXPIRE_DAYS : NON_PERSIST_EXPIRE_DAYS , req , rsp ) ; return user ; }
Attempts to authenticate the requester and initiate an authenticated session for them . An authenticated session involves their receiving a cookie that proves them to be authenticated and an entry in the session database being created that maps their information to their userid . If this call completes the session was established and the proper cookies were set in the supplied response object . If invalid authentication information is provided or some other error occurs an exception will be thrown .
11,436
public void effectLogin ( User user , int expires , HttpServletRequest req , HttpServletResponse rsp ) throws PersistenceException { String authcode = _repository . registerSession ( user , Math . max ( expires , 1 ) ) ; Cookie acookie = new Cookie ( _userAuthCookie , authcode ) ; if ( ! "false" . equalsIgnoreCase ( _config . getProperty ( "auth_cookie.strip_hostname" ) ) ) { CookieUtil . widenDomain ( req , acookie ) ; } acookie . setPath ( "/" ) ; acookie . setMaxAge ( ( expires > 0 ) ? ( expires * 24 * 60 * 60 ) : - 1 ) ; if ( USERMGR_DEBUG ) { log . info ( "Setting cookie " + acookie + "." ) ; } rsp . addCookie ( acookie ) ; }
If a user is already known to be authenticated for one reason or other this method can be used to give them the appropriate authentication cookies to effect their login .
11,437
public boolean exists ( HttpServletRequest req , String path ) { return ( getMessage ( req , path , false ) != null ) ; }
Return true if the specifed path exists in the resource bundle .
11,438
public String getMessage ( HttpServletRequest req , String path ) { return getMessage ( req , path , true ) ; }
Looks up the message with the specified path in the resource bundle most appropriate for the locales described as preferred by the request . Always reports missing paths .
11,439
protected ResourceBundle [ ] resolveBundles ( HttpServletRequest req ) { ResourceBundle [ ] bundles = null ; if ( req != null ) { bundles = ( ResourceBundle [ ] ) req . getAttribute ( getBundleCacheName ( ) ) ; } if ( bundles != null ) { return bundles ; } ClassLoader siteLoader = null ; String siteString = null ; if ( _siteIdent != null ) { int siteId = _siteIdent . identifySite ( req ) ; siteString = _siteIdent . getSiteString ( siteId ) ; if ( _siteLoader != null ) { try { siteLoader = _siteLoader . getSiteClassLoader ( siteId ) ; } catch ( IOException ioe ) { log . warning ( "Unable to fetch site-specific classloader" , "siteId" , siteId , "error" , ioe ) ; } } } bundles = new ResourceBundle [ 2 ] ; if ( siteLoader != null ) { bundles [ 0 ] = resolveBundle ( req , _siteBundlePath , siteLoader , false ) ; } else if ( siteString != null ) { bundles [ 0 ] = resolveBundle ( req , siteString + "_" + _bundlePath , getClass ( ) . getClassLoader ( ) , true ) ; } bundles [ 1 ] = resolveBundle ( req , _bundlePath , getClass ( ) . getClassLoader ( ) , false ) ; if ( bundles [ 0 ] != null || bundles [ 1 ] != null && req != null ) { req . setAttribute ( getBundleCacheName ( ) , bundles ) ; } return bundles ; }
Finds the closest matching resource bundle for the locales specified as preferred by the client in the supplied http request .
11,440
protected ResourceBundle resolveBundle ( HttpServletRequest req , String bundlePath , ClassLoader loader , boolean silent ) { ResourceBundle bundle = null ; if ( req != null ) { Enumeration < ? > locales = req . getLocales ( ) ; while ( locales . hasMoreElements ( ) ) { Locale locale = ( Locale ) locales . nextElement ( ) ; try { bundle = ResourceBundle . getBundle ( bundlePath , locale , loader ) ; if ( bundle . getLocale ( ) . equals ( locale ) ) { break ; } } catch ( MissingResourceException mre ) { } } } if ( bundle == null ) { Locale locale = ( req == null ) ? _deflocale : req . getLocale ( ) ; try { bundle = ResourceBundle . getBundle ( bundlePath , locale , loader ) ; } catch ( MissingResourceException mre ) { if ( ! silent ) { log . warning ( "Unable to resolve any message bundle" , "req" , getURL ( req ) , "locale" , locale , "bundlePath" , bundlePath , "classLoader" , loader , "siteBundlePath" , _siteBundlePath , "siteLoader" , _siteLoader ) ; } } } return bundle ; }
Resolves the default resource bundle based on the locale information provided in the supplied http request object .
11,441
public static boolean unpackJar ( JarFile jar , File target ) { boolean failure = false ; Enumeration < ? > entries = jar . entries ( ) ; while ( ! failure && entries . hasMoreElements ( ) ) { JarEntry entry = ( JarEntry ) entries . nextElement ( ) ; File efile = new File ( target , entry . getName ( ) ) ; if ( entry . isDirectory ( ) ) { if ( ! efile . exists ( ) && ! efile . mkdir ( ) ) { log . warning ( "Failed to create jar entry path" , "jar" , jar , "entry" , entry ) ; } continue ; } File parent = new File ( efile . getParent ( ) ) ; if ( ! parent . exists ( ) && ! parent . mkdirs ( ) ) { log . warning ( "Failed to create jar entry parent" , "jar" , jar , "parent" , parent ) ; continue ; } BufferedOutputStream fout = null ; InputStream jin = null ; try { fout = new BufferedOutputStream ( new FileOutputStream ( efile ) ) ; jin = jar . getInputStream ( entry ) ; StreamUtil . copy ( jin , fout ) ; } catch ( Exception e ) { log . warning ( "Failure unpacking" , "jar" , jar , "entry" , efile , "error" , e ) ; failure = true ; } finally { StreamUtil . close ( jin ) ; StreamUtil . close ( fout ) ; } } try { jar . close ( ) ; } catch ( Exception e ) { log . warning ( "Failed to close jar file" , "jar" , jar , "error" , e ) ; } return ! failure ; }
Unpacks the specified jar file intto the specified target directory .
11,442
public void setControlledPanel ( final JComponent panel ) { panel . addHierarchyListener ( new HierarchyListener ( ) { public void hierarchyChanged ( HierarchyEvent e ) { boolean nowShowing = panel . isDisplayable ( ) ; if ( _showing != nowShowing ) { _showing = nowShowing ; if ( _showing ) { wasAdded ( ) ; } else { wasRemoved ( ) ; } } } boolean _showing = false ; } ) ; }
Lets this controller know about the panel that it is controlling .
11,443
public boolean handleAction ( ActionEvent action ) { Object arg = null ; if ( action instanceof CommandEvent ) { arg = ( ( CommandEvent ) action ) . getArgument ( ) ; } return handleAction ( action . getSource ( ) , action . getActionCommand ( ) , arg ) ; }
Instructs this controller to process this action event . When an action is posted by a user interface element it will be posted to the controller in closest scope for that element . If that controller handles the event it should return true from this method to indicate that processing should stop . If it cannot handle the event it can return false to indicate that the event should be propagated to the next controller up the chain .
11,444
protected static void obtainTermSize ( ) { if ( _tdimens == null ) { _tdimens = TermUtil . getTerminalSize ( ) ; if ( _tdimens == null ) { _tdimens = new Dimension ( 132 , 24 ) ; } } }
Attempts to obtain the dimensions of the terminal window in which we re running . This is extremely platform specific but feel free to add code to do the right thing for your platform .
11,445
private void put ( PrintStream p , String s ) { if ( s == null ) { put ( p , " " ) ; return ; } if ( wasPreviousField ) { p . print ( separator ) ; } if ( trim ) { s = s . trim ( ) ; } if ( s . indexOf ( quote ) >= 0 ) { p . print ( quote ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == quote ) { p . print ( quote ) ; p . print ( quote ) ; } else { p . print ( c ) ; } } p . print ( quote ) ; } else if ( quoteLevel == 2 || quoteLevel == 1 && s . indexOf ( ' ' ) >= 0 || s . indexOf ( separator ) >= 0 ) { p . print ( quote ) ; p . print ( s ) ; p . print ( quote ) ; } else { p . print ( s ) ; } wasPreviousField = true ; }
Write one csv field to the file followed by a separator unless it is the last field on the line . Lead and trailing blanks will be removed .
11,446
public static void activate ( ) { if ( _dispatcher == null ) { _dispatcher = new KeyEventDispatcher ( ) { public boolean dispatchKeyEvent ( KeyEvent e ) { return DebugChords . dispatchKeyEvent ( e ) ; } } ; KeyboardFocusManager keymgr = KeyboardFocusManager . getCurrentKeyboardFocusManager ( ) ; keymgr . addKeyEventDispatcher ( _dispatcher ) ; } }
Initializes the debug chords services and wires up the key event listener that will be used to invoke the bound code .
11,447
public static void registerHook ( int modifierMask , int keyCode , Hook hook ) { ArrayList < Tuple < Integer , Hook > > list = _bindings . get ( keyCode ) ; if ( list == null ) { list = new ArrayList < Tuple < Integer , Hook > > ( ) ; _bindings . put ( keyCode , list ) ; } list . add ( new Tuple < Integer , Hook > ( modifierMask , hook ) ) ; }
Registers the supplied debug hook to be invoked when the specified key combination is depressed .
11,448
public V next ( ) throws SQLException { if ( _table == null ) { return null ; } if ( _result == null ) { if ( _qbeObject != null ) { PreparedStatement qbeStmt = _conn . prepareStatement ( _query ) ; _table . bindQueryVariables ( qbeStmt , _qbeObject , _qbeMask ) ; _result = qbeStmt . executeQuery ( ) ; _stmt = qbeStmt ; } else { if ( _stmt == null ) { _stmt = _conn . createStatement ( ) ; } _result = _stmt . executeQuery ( _query ) ; } } if ( _result . next ( ) ) { return _currObject = _table . load ( _result ) ; } _result . close ( ) ; _result = null ; _currObject = null ; _table = null ; if ( _stmt != null ) { _stmt . close ( ) ; } return null ; }
A cursor is initially positioned before its first row ; the first call to next makes the first row the current row ; the second call makes the second row the current row etc .
11,449
public V get ( ) throws SQLException { V result = next ( ) ; if ( result != null ) { int spurious = 0 ; while ( next ( ) != null ) { spurious ++ ; } if ( spurious > 0 ) { log . warning ( "Cursor.get() quietly tossed " + spurious + " spurious additional " + "records." , "query" , _query ) ; } } return result ; }
Returns the first element matched by this cursor or null if no elements were matched . Checks to ensure that no subsequent elements were matched by the query logs a warning if there were spurious additional matches .
11,450
public void close ( ) throws SQLException { if ( _result != null ) { _result . close ( ) ; _result = null ; } if ( _stmt != null ) { _stmt . close ( ) ; _stmt = null ; } }
Close the Cursor even if we haven t read all the possible objects .
11,451
public void setReport ( Report report ) { this . report = report ; if ( this . report . getQuery ( ) != null ) { this . report . getQuery ( ) . setDialect ( dialect ) ; } }
Set next report object
11,452
public void setAlerts ( List < Alert > alerts ) { if ( format == null ) { throw new IllegalStateException ( "You have to use setFormat with a valid output format before using setAlert!" ) ; } if ( ! ALARM_FORMAT . equals ( format ) && ! INDICATOR_FORMAT . equals ( format ) && ! DISPLAY_FORMAT . equals ( format ) ) { throw new IllegalStateException ( "You can use setAlert only for ALARM, INDICATOR or DISPLAY output formats!" ) ; } this . alerts = alerts ; }
Set a list of alert object for report of type alarm
11,453
public QueryResult executeQuery ( ) throws ReportRunnerException , InterruptedException { if ( connection == null ) { throw new ReportRunnerException ( "Connection is null!" ) ; } if ( report == null ) { throw new ReportRunnerException ( "Report is null!" ) ; } String sql = getSql ( ) ; Map < String , QueryParameter > parameters = getReportParameters ( ) ; if ( QueryUtil . restrictQueryExecution ( sql ) ) { throw new ReportRunnerException ( "You are not allowed to execute queries that modify the database!" ) ; } if ( QueryUtil . isProcedureCall ( sql ) ) { if ( ! QueryUtil . isValidProcedureCall ( sql , dialect ) ) { throw new ReportRunnerException ( "Invalid procedure call! Must be of form 'call (${P1}, ?)'" ) ; } } QueryResult queryResult = null ; try { Query query = getQuery ( sql ) ; QueryExecutor executor = new QueryExecutor ( query , parameters , parameterValues , connection , count , true , csv ) ; executor . setMaxRows ( 0 ) ; executor . setTimeout ( queryTimeout ) ; queryResult = executor . execute ( ) ; return queryResult ; } catch ( Exception e ) { throw new ReportRunnerException ( e ) ; } }
Execute query This method is useful in case you are not interested about report layout but only query and you want to make your own business .
11,454
public boolean run ( OutputStream stream ) throws ReportRunnerException , NoDataFoundException { if ( ( stream == null ) && ! TABLE_FORMAT . equals ( format ) && ! ALARM_FORMAT . equals ( format ) && ! INDICATOR_FORMAT . equals ( format ) && ! DISPLAY_FORMAT . equals ( format ) ) { throw new ReportRunnerException ( "OutputStream cannot be null!" ) ; } if ( ( stream != null ) && TABLE_FORMAT . equals ( format ) ) { throw new ReportRunnerException ( "TABLE FORMAT does not need an output stream. Use run() method instead." ) ; } if ( ( stream != null ) && ALARM_FORMAT . equals ( format ) ) { throw new ReportRunnerException ( "ALARM FORMAT does not need an output stream. Use run() method instead." ) ; } if ( ( stream != null ) && INDICATOR_FORMAT . equals ( format ) ) { throw new ReportRunnerException ( "INDICATOR FORMAT does not need an output stream. Use run() method instead." ) ; } if ( ( stream != null ) && DISPLAY_FORMAT . equals ( format ) ) { throw new ReportRunnerException ( "DISPLAY FORMAT does not need an output stream. Use run() method instead." ) ; } if ( ! formatAllowed ( format ) ) { throw new ReportRunnerException ( "Unsupported format : " + format + " !" ) ; } QueryResult queryResult = null ; try { queryResult = executeQuery ( ) ; String sql = getSql ( ) ; ParametersBean bean = new ParametersBean ( getQuery ( sql ) , getReportParameters ( ) , parameterValues ) ; ReportLayout convertedLayout = ReportUtil . getDynamicReportLayout ( connection , report . getLayout ( ) , bean ) ; boolean isProcedure = QueryUtil . isProcedureCall ( sql ) ; ExporterBean eb = new ExporterBean ( connection , queryTimeout , queryResult , stream , convertedLayout , bean , report . getBaseName ( ) , false , alerts , isProcedure ) ; if ( language != null ) { eb . setLanguage ( language ) ; } createExporter ( eb ) ; return exporter . export ( ) ; } catch ( NoDataFoundException e ) { throw e ; } catch ( Exception e ) { throw new ReportRunnerException ( e ) ; } finally { if ( queryResult != null ) { queryResult . close ( ) ; } } }
Export the current report to the specified output format
11,455
public void removeExporterEventListener ( ExporterEventListener listener ) { listenerList . remove ( listener ) ; if ( exporter != null ) { exporter . removeExporterEventListener ( listener ) ; } }
Remove an exporter event listener
11,456
public AlarmData getAlarmData ( ) { if ( ALARM_FORMAT . equals ( format ) ) { AlarmExporter alarmExporter = ( AlarmExporter ) exporter ; return alarmExporter . getData ( ) ; } else { return new AlarmData ( ) ; } }
Get alarm data ALARM exporter
11,457
public IndicatorData getIndicatorData ( ) { if ( INDICATOR_FORMAT . equals ( format ) ) { IndicatorExporter ie = ( IndicatorExporter ) exporter ; return ie . getData ( ) ; } else { return new IndicatorData ( ) ; } }
Get indicator data INDICATOR exporter
11,458
public DisplayData getDisplayData ( ) { if ( DISPLAY_FORMAT . equals ( format ) ) { DisplayExporter de = ( DisplayExporter ) exporter ; return de . getData ( ) ; } else { return new DisplayData ( ) ; } }
Get display data DISPLAY exporter
11,459
protected void flush ( ) { if ( ! _canFlush ) { return ; } if ( _size > _maxSize ) { Iterator < Map . Entry < K , V > > iter = _delegate . entrySet ( ) . iterator ( ) ; for ( int ii = size ( ) ; ( ii > 1 ) && ( _size > _maxSize ) ; ii -- ) { Map . Entry < K , V > entry = iter . next ( ) ; entryRemoved ( entry . getValue ( ) ) ; iter . remove ( ) ; } } }
Flushes entries from the cache until we re back under our desired cache size .
11,460
protected void entryRemoved ( V entry ) { if ( entry != null ) { _size -= _sizer . computeSize ( entry ) ; if ( _remobs != null ) { _remobs . removedFromMap ( this , entry ) ; } } }
Adjust our size to reflect the removal of the specified entry .
11,461
public static < T > ExpiringReference < T > create ( T value , long expireMillis ) { return new ExpiringReference < T > ( value , expireMillis ) ; }
Creates an expiring reference with the supplied value and expiration time .
11,462
public static < T > T get ( ExpiringReference < T > value ) { return ( value == null ) ? null : value . getValue ( ) ; }
Gets the value from an expiring reference but returns null if the supplied reference reference is null .
11,463
public T getValue ( ) { if ( _value != null && System . currentTimeMillis ( ) >= _expires ) { _value = null ; } return _value ; }
Returns the value with which we were created or null if the value has expired .
11,464
public static JMenuItem addMenuItem ( ActionListener l , JMenu menu , String name ) { return addMenuItem ( l , menu , name , null , null ) ; }
Adds a new menu item to the menu with the specified name .
11,465
protected static JMenuItem createItem ( String name , Integer mnem , KeyStroke accel ) { JMenuItem item = new JMenuItem ( name ) ; if ( mnem != null ) { item . setMnemonic ( mnem . intValue ( ) ) ; } if ( accel != null ) { item . setAccelerator ( accel ) ; } return item ; }
Creates and configures a menu item .
11,466
public void setText ( String text ) { if ( _label . setText ( text ) ) { _dirty = true ; if ( _constrain == HORIZONTAL || _constrain == VERTICAL ) { _constrainedSize = 0 ; _label . clearTargetDimens ( ) ; } revalidate ( ) ; repaint ( ) ; } }
Sets the text displayed by this label .
11,467
protected void layoutLabel ( ) { Graphics2D gfx = ( Graphics2D ) getGraphics ( ) ; if ( gfx != null ) { _label . layout ( gfx ) ; gfx . dispose ( ) ; _dirty = false ; } }
Called when the label has changed in some meaningful way and we d accordingly like to re - layout the label update our component s size and repaint everything to suit .
11,468
public static Dialect determineDialect ( String databaseName , String databaseMajorVersion ) throws DialectException { if ( databaseName == null ) { throw new DialectException ( "Dialect must be explicitly set" ) ; } String dialectName ; if ( databaseName . startsWith ( FIREBIRD ) ) { dialectName = FirebirdDialect . class . getName ( ) ; } else if ( databaseName . startsWith ( MSACCESS ) ) { dialectName = MSAccessDialect . class . getName ( ) ; } else { DialectMapper mapper = MAPPERS . get ( databaseName ) ; if ( mapper == null ) { throw new DialectException ( "Dialect must be explicitly set for database: " + databaseName ) ; } dialectName = mapper . getDialectClass ( databaseMajorVersion ) ; } return buildDialect ( dialectName ) ; }
Determine the appropriate Dialect to use given the database product name and major version .
11,469
public static Dialect buildDialect ( String dialectName ) throws DialectException { try { return ( Dialect ) loadDialect ( dialectName ) . newInstance ( ) ; } catch ( ClassNotFoundException e ) { throw new DialectException ( "Dialect class not found: " + dialectName ) ; } catch ( Exception e ) { throw new DialectException ( "Could not instantiate dialect class" , e ) ; } }
Returns a dialect instance given the name of the class to use .
11,470
public static Runnable asRunnable ( Object instance , String methodName ) { Class < ? > clazz = instance . getClass ( ) ; Method method = findMethod ( clazz , methodName ) ; if ( Modifier . isStatic ( method . getModifiers ( ) ) ) { throw new IllegalArgumentException ( clazz . getName ( ) + "." + methodName + "() must not be static" ) ; } return new MethodRunner ( method , instance ) ; }
Creates a runnable that invokes the specified method on the specified instance via reflection .
11,471
public static Runnable asRunnable ( Class < ? > clazz , String methodName ) { Method method = findMethod ( clazz , methodName ) ; if ( ! Modifier . isStatic ( method . getModifiers ( ) ) ) { throw new IllegalArgumentException ( clazz . getName ( ) + "." + methodName + "() must be static" ) ; } return new MethodRunner ( method , null ) ; }
Creates a runnable that invokes the specified static method via reflection .
11,472
public void setConnection ( Connection connection , boolean csv ) { this . connection = connection ; this . csv = csv ; try { dialect = DialectUtil . getDialect ( connection ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } if ( chart != null ) { if ( chart . getReport ( ) . getQuery ( ) != null ) { chart . getReport ( ) . getQuery ( ) . setDialect ( dialect ) ; } } }
Set database connection
11,473
public void setChart ( Chart chart ) { this . chart = chart ; if ( this . chart . getReport ( ) . getQuery ( ) != null ) { this . chart . getReport ( ) . getQuery ( ) . setDialect ( dialect ) ; } }
Set next chart object
11,474
public boolean run ( OutputStream stream ) throws ReportRunnerException , NoDataFoundException , InterruptedException { if ( ( stream == null ) && GRAPHIC_FORMAT . equals ( format ) ) { throw new ReportRunnerException ( "OutputStream cannot be null!" ) ; } if ( ( stream != null ) && TABLE_FORMAT . equals ( format ) ) { throw new ReportRunnerException ( "TABLE FORMAT does not need an output stream. Use run() method instead." ) ; } if ( connection == null ) { throw new ReportRunnerException ( "Connection is null!" ) ; } if ( chart == null ) { throw new ReportRunnerException ( "Chart is null!" ) ; } Report report = chart . getReport ( ) ; String sql = report . getSql ( ) ; if ( sql == null ) { sql = report . getQuery ( ) . toString ( ) ; } if ( sql == null ) { throw new ReportRunnerException ( "Report sql expression not found" ) ; } try { setDynamicColumns ( ) ; } catch ( Exception e1 ) { throw new ReportRunnerException ( e1 ) ; } Map < String , QueryParameter > parameters = new HashMap < String , QueryParameter > ( ) ; List < QueryParameter > parameterList = report . getParameters ( ) ; if ( parameterList != null ) { for ( QueryParameter param : parameterList ) { parameters . put ( param . getName ( ) , param ) ; } } if ( QueryUtil . restrictQueryExecution ( sql ) ) { throw new ReportRunnerException ( "You are not allowed to execute queries that modify the database!" ) ; } if ( QueryUtil . isProcedureCall ( sql ) ) { Dialect dialect = null ; try { dialect = DialectUtil . getDialect ( connection ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } if ( ! QueryUtil . isValidProcedureCall ( sql , dialect ) ) { throw new ReportRunnerException ( "Invalid procedure call! Must be of form 'call (${P1}, ?)'" ) ; } } QueryExecutor executor = null ; try { Query query = new Query ( sql ) ; executor = new QueryExecutor ( query , parameters , parameterValues , connection , true , true , csv ) ; executor . setMaxRows ( 0 ) ; executor . setTimeout ( queryTimeout ) ; QueryResult queryResult = executor . execute ( ) ; createExporter ( query , parameters , parameterValues , queryResult , stream ) ; return exporter . export ( ) ; } catch ( NoDataFoundException e ) { throw e ; } catch ( InterruptedException e ) { throw e ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ReportRunnerException ( e ) ; } finally { resetStaticColumnsAfterRun ( ) ; if ( executor != null ) { executor . close ( ) ; } } }
Export the current chart to the specified output format For IMAGE_FORMAT use withImagePath method .
11,475
public static void configureDefaultHandler ( int maxRepeat ) { Logger logger = LogManager . getLogManager ( ) . getLogger ( "" ) ; Handler [ ] handlers = logger . getHandlers ( ) ; RepeatRecordFilter filter = new RepeatRecordFilter ( maxRepeat ) ; for ( int ii = 0 ; ii < handlers . length ; ii ++ ) { handlers [ ii ] . setFilter ( filter ) ; } }
Configures the default logging handlers to use an instance of this filter .
11,476
public static int levelFromString ( String level ) { if ( level . equalsIgnoreCase ( "debug" ) ) { return DEBUG ; } else if ( level . equalsIgnoreCase ( "info" ) ) { return INFO ; } else if ( level . equalsIgnoreCase ( "warning" ) ) { return WARNING ; } else { return - 1 ; } }
Returns the log level that matches the specified string or - 1 if the string could not be interpretted as a log level .
11,477
protected static Dimension getSizeViaResize ( ) { BufferedReader bin = null ; try { Process proc = Runtime . getRuntime ( ) . exec ( "resize" ) ; InputStream in = proc . getInputStream ( ) ; bin = new BufferedReader ( new InputStreamReader ( in ) ) ; Pattern regex = Pattern . compile ( "([0-9]+)" ) ; String line ; int columns = - 1 , lines = - 1 ; while ( ( line = bin . readLine ( ) ) != null ) { if ( line . indexOf ( "COLUMNS" ) != - 1 ) { Matcher match = regex . matcher ( line ) ; if ( match . find ( ) ) { columns = safeToInt ( match . group ( ) ) ; } } else if ( line . indexOf ( "LINES" ) != - 1 ) { Matcher match = regex . matcher ( line ) ; if ( match . find ( ) ) { lines = safeToInt ( match . group ( ) ) ; } } } if ( columns != - 1 && lines != - 1 ) { return new Dimension ( columns , lines ) ; } return null ; } catch ( PatternSyntaxException pse ) { return null ; } catch ( SecurityException se ) { return null ; } catch ( IOException ioe ) { return null ; } finally { StreamUtil . close ( bin ) ; } }
Tries to obtain the terminal dimensions by running resize .
11,478
protected static int safeToInt ( String intstr ) { if ( ! StringUtil . isBlank ( intstr ) ) { try { return Integer . parseInt ( intstr ) ; } catch ( NumberFormatException nfe ) { } } return - 1 ; }
Converts the string to an integer returning - 1 on any error .
11,479
protected void append0 ( T item , boolean notify ) { if ( _count == _size ) { makeMoreRoom ( ) ; } _items [ _end ] = item ; _end = ( _end + 1 ) % _size ; _count ++ ; if ( notify ) { notify ( ) ; } }
Internal append method . If subclassing queue be sure to call this method from inside a synchronized block .
11,480
public synchronized T getNonBlocking ( ) { if ( _count == 0 ) { return null ; } T retval = _items [ _start ] ; _items [ _start ] = null ; _start = ( _start + 1 ) % _size ; _count -- ; return retval ; }
Returns the next item on the queue or null if the queue is empty . This method will not block waiting for an item to be added to the queue .
11,481
public synchronized T get ( ) { while ( _count == 0 ) { try { wait ( ) ; } catch ( InterruptedException e ) { } } T retval = _items [ _start ] ; _items [ _start ] = null ; _start = ( _start + 1 ) % _size ; _count -- ; if ( ( _size > MIN_SHRINK_SIZE ) && ( _size > _suggestedSize ) && ( _count < ( _size >> 3 ) ) ) shrink ( ) ; return retval ; }
Gets the next item from the queue blocking until an item is added to the queue if the queue is empty at time of invocation .
11,482
private void shrink ( ) { T [ ] items = newArray ( _size / 2 ) ; if ( _start > _end ) { System . arraycopy ( _items , _start , items , 0 , _size - _start ) ; System . arraycopy ( _items , 0 , items , _size - _start , _end + 1 ) ; } else { System . arraycopy ( _items , _start , items , 0 , _end - _start + 1 ) ; } _size = _size / 2 ; _start = 0 ; _end = _count ; _items = items ; }
shrink by half
11,483
@ ReplacedBy ( "com.google.common.collect.Iterators#addAll(Collection, com.google.common.collect.Iterators#forEnumeration(Enumeration))" ) public static < T , C extends Collection < T > > C addAll ( C col , Enumeration < ? extends T > enm ) { while ( enm . hasMoreElements ( ) ) { col . add ( enm . nextElement ( ) ) ; } return col ; }
Adds all items returned by the enumeration to the supplied collection and returns the supplied collection .
11,484
@ ReplacedBy ( "com.google.common.collect.Iterators#addAll()" ) public static < T , C extends Collection < T > > C addAll ( C col , Iterator < ? extends T > iter ) { while ( iter . hasNext ( ) ) { col . add ( iter . next ( ) ) ; } return col ; }
Adds all items returned by the iterator to the supplied collection and returns the supplied collection .
11,485
@ ReplacedBy ( "java.util.Collections#addAll()" ) public static < T , E extends T , C extends Collection < T > > C addAll ( C col , E [ ] values ) { if ( values != null ) { for ( E value : values ) { col . add ( value ) ; } } return col ; }
Adds all items in the given object array to the supplied collection and returns the supplied collection . If the supplied array is null nothing is added to the collection .
11,486
public static < T , C extends Collection < T > > C addAll ( C col , Iterable < ? extends Collection < ? extends T > > values ) { for ( Collection < ? extends T > val : values ) { col . addAll ( val ) ; } return col ; }
Folds all the specified values into the supplied collection and returns it .
11,487
public static < K , V , M extends Map < K , V > > M putAll ( M map , Iterable < ? extends Map < ? extends K , ? extends V > > values ) { for ( Map < ? extends K , ? extends V > val : values ) { map . putAll ( val ) ; } return map ; }
Folds all the specified values into the supplied map and returns it .
11,488
public void parametersAreDefined ( Report report ) throws ParameterNotFoundException { String [ ] paramNames ; String sql = report . getSql ( ) ; if ( sql == null ) { sql = report . getQuery ( ) . toString ( ) ; } Query query = new Query ( sql ) ; paramNames = query . getParameterNames ( ) ; List < QueryParameter > parameters = report . getParameters ( ) ; for ( String paramName : paramNames ) { QueryParameter param = null ; for ( QueryParameter p : parameters ) { if ( paramName . equals ( p . getName ( ) ) ) { param = p ; } } if ( param == null ) { throw new ParameterNotFoundException ( paramName ) ; } } }
Test if all parameters used in the report are defined
11,489
public static List < IdName > getRuntimeParameterValues ( Connection con , QueryParameter qp , Map < String , QueryParameter > map , Map < String , Object > vals ) throws Exception { List < IdName > values = new ArrayList < IdName > ( ) ; if ( qp . isManualSource ( ) ) { QueryExecutor executor = null ; try { Query query = new Query ( qp . getSource ( ) ) ; executor = new QueryExecutor ( query , map , vals , con , false , false , false ) ; executor . setTimeout ( 10000 ) ; executor . setMaxRows ( 0 ) ; QueryResult qr = executor . execute ( ) ; while ( qr . hasNext ( ) ) { IdName in = new IdName ( ) ; in . setId ( ( Serializable ) qr . nextValue ( 0 ) ) ; if ( qr . getColumnCount ( ) == 1 ) { in . setName ( ( Serializable ) qr . nextValue ( 0 ) ) ; } else { in . setName ( ( Serializable ) qr . nextValue ( 1 ) ) ; } values . add ( in ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; throw new Exception ( ex ) ; } finally { if ( executor != null ) { executor . close ( ) ; } } } else { String source = qp . getSource ( ) ; int index = source . indexOf ( "." ) ; int index2 = source . lastIndexOf ( "." ) ; String tableName = source . substring ( 0 , index ) ; String columnName ; String shownColumnName = null ; if ( index == index2 ) { columnName = source . substring ( index + 1 ) ; } else { columnName = source . substring ( index + 1 , index2 ) ; shownColumnName = source . substring ( index2 + 1 ) ; } values = getColumnValues ( con , qp . getSchema ( ) , tableName , columnName , shownColumnName , qp . getOrderBy ( ) ) ; } return values ; }
Get values for a parameter sql at runtime All parent parameters must have the values in the map .
11,490
public static List < IdName > getParameterValues ( Connection con , QueryParameter qp , Map < String , QueryParameter > map , Map < String , Serializable > vals ) throws Exception { Map < String , Object > objVals = new HashMap < String , Object > ( ) ; for ( String key : vals . keySet ( ) ) { Serializable s = vals . get ( key ) ; if ( s instanceof Serializable [ ] ) { Serializable [ ] array = ( Serializable [ ] ) s ; Object [ ] objArray = new Object [ array . length ] ; for ( int i = 0 , size = array . length ; i < size ; i ++ ) { objArray [ i ] = array [ i ] ; } s = objArray ; } objVals . put ( key , s ) ; } QueryExecutor executor = null ; try { List < IdName > values = new ArrayList < IdName > ( ) ; Query query = new Query ( qp . getSource ( ) ) ; executor = new QueryExecutor ( query , map , objVals , con , false , false , false ) ; executor . setTimeout ( 10000 ) ; executor . setMaxRows ( 0 ) ; QueryResult qr = executor . execute ( ) ; while ( qr . hasNext ( ) ) { IdName in = new IdName ( ) ; in . setId ( ( Serializable ) qr . nextValue ( 0 ) ) ; if ( qr . getColumnCount ( ) == 1 ) { in . setName ( ( Serializable ) qr . nextValue ( 0 ) ) ; } else { in . setName ( ( Serializable ) qr . nextValue ( 1 ) ) ; } values . add ( in ) ; } return values ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; throw new Exception ( ex ) ; } finally { if ( executor != null ) { executor . close ( ) ; } } }
Get values for a dependent parameter sql All parent parameters must have the values in the map .
11,491
public static ArrayList < Serializable > getDefaultSourceValues ( Connection con , QueryParameter qp ) throws Exception { ArrayList < Serializable > result = new ArrayList < Serializable > ( ) ; List < IdName > list = getSelectValues ( con , qp . getDefaultSource ( ) , false , QueryParameter . NO_ORDER ) ; if ( QueryParameter . SINGLE_SELECTION . equals ( qp . getSelection ( ) ) ) { for ( IdName in : list ) { result . add ( in . getId ( ) ) ; } } else { for ( IdName in : list ) { result . add ( in ) ; } } return result ; }
Get values for a default source
11,492
public static Map < String , QueryParameter > getUsedNotHiddenParametersMap ( Report report ) { return getUsedParametersMap ( report , false , false ) ; }
Get used parameters map where the key is the parameter name and the value is the parameter Not all the report parameters have to be used some may only be defined for further usage . The result will not contain the hidden parameters .
11,493
public static Map < String , QueryParameter > getUsedHiddenParametersMap ( Report report ) { return getUsedParametersMap ( report , false , true ) ; }
Get used hidden parameters map where the key is the parameter name and the value is the parameter Not all the report parameters have to be used some may only be defined for further usage . The result will contain only the hidden parameters .
11,494
public static Map < String , QueryParameter > getUsedParametersMap ( Query query , Map < String , QueryParameter > allParameters ) { Set < String > paramNames = new HashSet < String > ( Arrays . asList ( query . getParameterNames ( ) ) ) ; for ( QueryParameter p : allParameters . values ( ) ) { paramNames . addAll ( p . getDependentParameterNames ( ) ) ; } LinkedHashMap < String , QueryParameter > params = new LinkedHashMap < String , QueryParameter > ( ) ; for ( String name : allParameters . keySet ( ) ) { boolean found = false ; for ( String pName : paramNames ) { if ( pName . equals ( name ) ) { found = true ; break ; } } QueryParameter qp = allParameters . get ( name ) ; if ( found || qp . isHidden ( ) ) { params . put ( name , qp ) ; } } return params ; }
Get used parameters map where the key is the parameter name and the value is the parameter Not all the report parameters have to be used some may only be defined for further usage . The result will contain also the hidden parameters and all parameters used just inside other parameters .
11,495
public static Map < String , QueryParameter > getUsedParametersMap ( String sql , Map < String , QueryParameter > allParameters ) { Query query = new Query ( sql ) ; return getUsedParametersMap ( query , allParameters ) ; }
Get used parameters map where the key is the parameter name and the value is the parameter Not all the report parameters have to be used some may only be defined for further usage . The result will contain also the hidden parameters .
11,496
public static boolean allParametersAreHidden ( Map < String , QueryParameter > map ) { for ( QueryParameter qp : map . values ( ) ) { if ( ! qp . isHidden ( ) ) { return false ; } } return true ; }
See if all parameters are hidden
11,497
public static boolean allParametersHaveDefaults ( Map < String , QueryParameter > map ) { for ( QueryParameter qp : map . values ( ) ) { if ( ( qp . getDefaultValues ( ) == null ) || ( qp . getDefaultValues ( ) . size ( ) == 0 ) ) { if ( ( qp . getDefaultSource ( ) == null ) || "" . equals ( qp . getDefaultSource ( ) . trim ( ) ) ) { return false ; } } } return true ; }
See if all parameters have default values
11,498
public static void initAllRuntimeParameterValues ( QueryParameter param , List < IdName > values , Map < String , Object > parameterValues ) throws QueryException { if ( param . getSelection ( ) . equals ( QueryParameter . SINGLE_SELECTION ) ) { parameterValues . put ( param . getName ( ) , values . get ( 0 ) ) ; } else { Object [ ] val = new Object [ values . size ( ) ] ; for ( int k = 0 , size = values . size ( ) ; k < size ; k ++ ) { val [ k ] = values . get ( k ) ; } parameterValues . put ( param . getName ( ) , val ) ; } }
Init parameter values map with all the values
11,499
public static void initDefaultParameterValues ( QueryParameter param , List < Serializable > defValues , Map < String , Object > parameterValues ) throws QueryException { if ( param . getSelection ( ) . equals ( QueryParameter . SINGLE_SELECTION ) ) { parameterValues . put ( param . getName ( ) , defValues . get ( 0 ) ) ; } else { Object [ ] val = new Object [ defValues . size ( ) ] ; for ( int k = 0 , size = defValues . size ( ) ; k < size ; k ++ ) { val [ k ] = defValues . get ( k ) ; } parameterValues . put ( param . getName ( ) , val ) ; } }
Init parameter values map with the default values