idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
11,600 | protected < T > int update ( final Table < T > table , final T object , final FieldMask mask ) throws PersistenceException { return executeUpdate ( new Operation < Integer > ( ) { public Integer invoke ( Connection conn , DatabaseLiaison liaison ) throws SQLException , PersistenceException { return table . update ( conn , object , mask ) ; } } ) ; } | Updates fields specified by the supplied field mask in the supplied object in the specified table . |
11,601 | protected < T > ArrayList < T > loadAll ( final Table < T > table , final String query ) throws PersistenceException { return execute ( new Operation < ArrayList < T > > ( ) { public ArrayList < T > invoke ( Connection conn , DatabaseLiaison liaison ) throws SQLException , PersistenceException { return table . select ( conn , query ) . toArrayList ( ) ; } } ) ; } | Loads all objects from the specified table that match the supplied query . |
11,602 | protected < T > ArrayList < T > loadAllByExample ( final Table < T > table , final T example ) throws PersistenceException { return execute ( new Operation < ArrayList < T > > ( ) { public ArrayList < T > invoke ( Connection conn , DatabaseLiaison liaison ) throws SQLException , PersistenceException { return table . queryByExample ( conn , example ) . toArrayList ( ) ; } } ) ; } | Loads all objects from the specified table that match the supplied example . |
11,603 | protected < T > int store ( final Table < T > table , final T object ) throws PersistenceException { return executeUpdate ( new Operation < Integer > ( ) { public Integer invoke ( Connection conn , DatabaseLiaison liaison ) throws SQLException , PersistenceException { if ( table . update ( conn , object ) == 0 ) { table . insert ( conn , object ) ; return liaison . lastInsertedId ( conn , null , table . getName ( ) , "TODO" ) ; } return - 1 ; } } ) ; } | First attempts to update the supplied object and if that modifies zero rows inserts the object into the specified table . The table must be configured to store items of the supplied type . |
11,604 | public String fixedText ( String name , String extra , Object value ) { return fixedInput ( "text" , name , value , extra ) ; } | Creates a text input field with the specified name and the specified extra arguments and the specified value . |
11,605 | public String submitExtra ( String name , String text , String extra ) { return fixedInput ( "submit" , name , text , extra ) ; } | Constructs a submit element with the specified parameter name and the specified button text with the specified extra text . |
11,606 | public String imageSubmit ( String name , String value , String imagePath ) { return fixedInput ( "image" , name , value , "src=\"" + imagePath + "\"" ) ; } | Constructs a image submit element with the specified parameter name and image path . |
11,607 | public String button ( String name , String text , String extra ) { return fixedInput ( "button" , name , text , extra ) ; } | Constructs a button input element with the specified parameter name the specified button text and the specified extra text . |
11,608 | public String hidden ( String name , Object defaultValue ) { return fixedHidden ( name , getValue ( name , defaultValue ) ) ; } | Constructs a hidden element with the specified parameter name where the value is extracted from the appropriate request parameter unless there is no value in which case the supplied default value is used . |
11,609 | public String checkbox ( String name , boolean defaultValue ) { String value = getParameter ( name ) ; return fixedCheckbox ( name , ( value == null ) ? defaultValue : ! value . equals ( "" ) ) ; } | Constructs a checkbox input field with the specified name and default value . |
11,610 | public String fixedCheckbox ( String name , boolean value ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "<input type=\"checkbox\"" ) ; buf . append ( " name=\"" ) . append ( name ) . append ( "\"" ) ; if ( value ) { buf . append ( _useXHTML ? " checked=\"checked\"" : " checked" ) ; } buf . append ( getCloseBrace ( ) ) ; return buf . toString ( ) ; } | Constructs a checkbox input field with the specified name and value . |
11,611 | public String option ( String name , String value , String item , Object defaultValue ) { String selectedValue = getValue ( name , defaultValue ) ; return fixedOption ( name , value , item , selectedValue ) ; } | Constructs an option entry for a select menu with the specified name value item and default selected value . |
11,612 | public String fixedOption ( String name , String value , String item , Object selectedValue ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "<option value=\"" ) . append ( value ) . append ( "\"" ) ; if ( selectedValue . equals ( value ) ) { buf . append ( " selected" ) ; } buf . append ( ">" ) . append ( item ) . append ( "</option>" ) ; return buf . toString ( ) ; } | Constructs an option entry for a select menu with the specified name value item and selected value . |
11,613 | public String textarea ( String name , String extra , Object defaultValue ) { return fixedTextarea ( name , extra , getValue ( name , defaultValue ) ) ; } | Constructs a text area with the specified name optional extra parameters and default text . |
11,614 | public String fixedTextarea ( String name , String extra , Object value ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "<textarea name=\"" ) . append ( name ) . append ( "\"" ) ; if ( ! StringUtil . isBlank ( extra ) ) { buf . append ( " " ) . append ( extra ) ; } buf . append ( ">" ) ; if ( value != null ) { buf . append ( value ) ; } buf . append ( "</textarea>" ) ; return buf . toString ( ) ; } | Construct a text area with the specified name optional extra parameters and the specified text . |
11,615 | protected String input ( String type , String name , String extra , Object defaultValue ) { return fixedInput ( type , name , getValue ( name , defaultValue ) , extra ) ; } | Generates an input form field with the specified type name defaultValue and extra attributes . |
11,616 | protected String fixedInput ( String type , String name , Object value , String extra ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "<input type=\"" ) . append ( type ) . append ( "\"" ) ; buf . append ( " name=\"" ) . append ( name ) . append ( "\"" ) ; buf . append ( " value=\"" ) . append ( value ) . append ( "\"" ) ; if ( ! StringUtil . isBlank ( extra ) ) { buf . append ( " " ) . append ( extra ) ; } buf . append ( getCloseBrace ( ) ) ; return buf . toString ( ) ; } | Generates an input form field with the specified type name value and extra attributes . The value is not fetched from the request parameters but is always the value supplied . |
11,617 | protected String getValue ( String name , Object defaultValue ) { String value = getParameter ( name ) ; if ( StringUtil . isBlank ( value ) ) { if ( defaultValue == null ) { value = "" ; } else { value = String . valueOf ( defaultValue ) ; } } return HTMLUtil . entify ( value ) ; } | Fetches the requested value from the servlet request and entifies it appropriately . |
11,618 | public Site insertNewSite ( String siteString ) throws PersistenceException { if ( _sitesByString . containsKey ( siteString ) ) { return null ; } Site site = new Site ( ) ; site . siteString = siteString ; _repo . insertNewSite ( site ) ; @ SuppressWarnings ( "unchecked" ) HashMap < String , Site > newStrings = ( HashMap < String , Site > ) _sitesByString . clone ( ) ; HashIntMap < Site > newIds = _sitesById . clone ( ) ; newIds . put ( site . siteId , site ) ; newStrings . put ( site . siteString , site ) ; _sitesByString = newStrings ; _sitesById = newIds ; return site ; } | Insert a new site into the site table and into this mapping . |
11,619 | protected void checkReloadSites ( ) { long now = System . currentTimeMillis ( ) ; boolean reload = false ; synchronized ( this ) { reload = ( now - _lastReload > RELOAD_INTERVAL ) ; if ( reload ) { _lastReload = now ; } } if ( reload ) { try { _repo . refreshSiteData ( ) ; } catch ( PersistenceException pe ) { log . warning ( "Error refreshing site data." , pe ) ; } } } | Checks to see if we should reload our sites information from the sites table . |
11,620 | public V setValue ( V value ) { V oldValue = _value ; _value = value ; return oldValue ; } | from interface Map . Entry |
11,621 | @ ReplacedBy ( "com.google.common.collect.Ordering.natural().nullsLast()" ) public static final < T extends Comparable < ? > > Comparator < T > comparable ( ) { @ SuppressWarnings ( "unchecked" ) Comparator < T > comp = ( Comparator < T > ) COMPARABLE ; return comp ; } | code to freak out ; I don t entirely understand why |
11,622 | protected boolean checkedApply ( ObserverOp < T > obop , T obs ) { try { return obop . apply ( obs ) ; } catch ( Throwable thrown ) { log . warning ( "ObserverOp choked during notification" , "op" , obop , "obs" , observerForLog ( obs ) , thrown ) ; return true ; } } | Applies the operation to the observer catching and logging any exceptions thrown in the process . |
11,623 | public Object get ( int key ) { int size = _keys . length , start = key % size ; for ( int ii = 0 ; ii < size ; ii ++ ) { int idx = ( ii + start ) % size ; if ( _keys [ idx ] == key ) { return _values [ idx ] ; } } return null ; } | Returns the object with the specified key null if no object exists in the table with that key . |
11,624 | public Object remove ( int key ) { int size = _keys . length , start = key % size ; for ( int ii = 0 ; ii < size ; ii ++ ) { int idx = ( ii + start ) % size ; if ( _keys [ idx ] == key ) { Object value = _values [ idx ] ; _keys [ idx ] = - 1 ; _values [ idx ] = null ; return value ; } } return null ; } | Removes the mapping associated with the specified key . The previous value of the mapping will be returned . |
11,625 | public int size ( ) { int size = 0 ; for ( int ii = 0 , ll = _keys . length ; ii < ll ; ii ++ ) { if ( _keys [ ii ] != - 1 ) { size ++ ; } } return size ; } | Returns the number of mappings in this table . |
11,626 | public static Iterable < String > getParameterNames ( HttpServletRequest req ) { List < String > params = new ArrayList < String > ( ) ; Enumeration < ? > iter = req . getParameterNames ( ) ; while ( iter . hasMoreElements ( ) ) { params . add ( ( String ) iter . nextElement ( ) ) ; } return params ; } | Returns the names of the parameters of the supplied request in a civilized format . |
11,627 | public static float requireFloatParameter ( HttpServletRequest req , String name , String invalidDataMessage ) throws DataValidationException { return parseFloatParameter ( getParameter ( req , name , false ) , invalidDataMessage ) ; } | Fetches the supplied parameter from the request and converts it to a float . If the parameter does not exist or is not a well - formed float a data validation exception is thrown with the supplied message . |
11,628 | public static IntSet getIntParameters ( HttpServletRequest req , String name , String invalidDataMessage ) throws DataValidationException { IntSet ints = new ArrayIntSet ( ) ; String [ ] values = req . getParameterValues ( name ) ; if ( values != null ) { for ( int ii = 0 ; ii < values . length ; ii ++ ) { if ( ! StringUtil . isBlank ( values [ ii ] ) ) { ints . add ( parseIntParameter ( values [ ii ] , invalidDataMessage ) ) ; } } } return ints ; } | Fetches all the values from the request with the specified name and converts them to an IntSet . If the parameter does not exist or is not a well - formed integer a data validation exception is thrown with the supplied message . |
11,629 | public static Set < String > getParameters ( HttpServletRequest req , String name ) { Set < String > set = new HashSet < String > ( ) ; String [ ] values = req . getParameterValues ( name ) ; if ( values != null ) { for ( int ii = 0 ; ii < values . length ; ii ++ ) { if ( ! StringUtil . isBlank ( values [ ii ] ) ) { set . add ( values [ ii ] ) ; } } } return set ; } | Fetches all the values from the request with the specified name and converts them to a Set . |
11,630 | public static String requireParameter ( HttpServletRequest req , String name , String missingDataMessage ) throws DataValidationException { String value = getParameter ( req , name , true ) ; if ( StringUtil . isBlank ( value ) ) { throw new DataValidationException ( missingDataMessage ) ; } return value ; } | Fetches the supplied parameter from the request . If the parameter does not exist a data validation exception is thrown with the supplied message . |
11,631 | public static String requireParameter ( HttpServletRequest req , String name , String missingDataMessage , int maxLength ) throws DataValidationException { return StringUtil . truncate ( requireParameter ( req , name , missingDataMessage ) , maxLength ) ; } | Fetches the supplied parameter from the request and ensures that it is no longer than maxLength . |
11,632 | public static boolean parameterEquals ( HttpServletRequest req , String name , String value ) { return value . equals ( getParameter ( req , name , false ) ) ; } | Returns true if the specified parameter is equal to the supplied value . If the parameter is not set in the request false is returned . |
11,633 | protected static int parseIntParameter ( String value , String invalidDataMessage ) throws DataValidationException { try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException nfe ) { throw new DataValidationException ( invalidDataMessage ) ; } } | Internal method to parse integer values . |
11,634 | protected static long parseLongParameter ( String value , String invalidDataMessage ) throws DataValidationException { try { return Long . parseLong ( value ) ; } catch ( NumberFormatException nfe ) { throw new DataValidationException ( invalidDataMessage ) ; } } | Internal method to parse long values . |
11,635 | protected static float parseFloatParameter ( String value , String invalidDataMessage ) throws DataValidationException { try { return Float . parseFloat ( value ) ; } catch ( NumberFormatException nfe ) { throw new DataValidationException ( invalidDataMessage ) ; } } | Internal method to parse a float value . |
11,636 | protected static Date parseDateParameter ( String value , String invalidDataMessage ) throws DataValidationException { try { synchronized ( _dparser ) { return _dparser . parse ( value ) ; } } catch ( ParseException pe ) { throw new DataValidationException ( invalidDataMessage ) ; } } | Internal method to parse a date . |
11,637 | public static < T > T pickRandom ( T [ ] values ) { return ( values == null || values . length == 0 ) ? null : values [ getInt ( values . length ) ] ; } | Picks a random object from the supplied array of values . Even weight is given to all elements of the array . |
11,638 | public static < T > T pickRandom ( List < T > values ) { int size = values . size ( ) ; if ( size == 0 ) { throw new IllegalArgumentException ( "Must have at least one element [size=" + size + "]" ) ; } return values . get ( getInt ( size ) ) ; } | Picks a random object from the supplied List |
11,639 | public void requestCompleted ( final T result ) { apply ( new ObserverOp < ResultListener < T > > ( ) { public boolean apply ( ResultListener < T > observer ) { observer . requestCompleted ( result ) ; return true ; } } ) ; } | Multiplex a requestCompleted response to all the ResultListeners in this list . |
11,640 | public void requestFailed ( final Exception cause ) { apply ( new ObserverOp < ResultListener < T > > ( ) { public boolean apply ( ResultListener < T > observer ) { observer . requestFailed ( cause ) ; return true ; } } ) ; } | Multiplex a requestFailed response to all the ResultListeners in this list . |
11,641 | public static String filterColors ( String txt ) { if ( txt == null ) return null ; return COLOR_PATTERN . matcher ( txt ) . replaceAll ( "" ) ; } | Filter out any color tags from the specified text . |
11,642 | public static String escapeColors ( String txt ) { if ( txt == null ) return null ; return COLOR_PATTERN . matcher ( txt ) . replaceAll ( "#''$1" ) ; } | Escape any special tags so that they won t be interpreted by the label . |
11,643 | private static String unescapeColors ( String txt , boolean restore ) { if ( txt == null ) return null ; String prefix = restore ? "#" : "%" ; return ESCAPED_PATTERN . matcher ( txt ) . replaceAll ( prefix + "$1" ) ; } | Un - escape escaped tags so that they look as the users intended . |
11,644 | public boolean setText ( String text ) { if ( StringUtil . isBlank ( text ) ) { text = " " ; } if ( text . equals ( ( _rawText == null ) ? _text : _rawText ) ) { return false ; } _text = filterColors ( text ) ; _rawText = text . equals ( _text ) ? null : text ; _text = unescapeColors ( _text , true ) ; if ( _rawText != null ) { _rawText = unescapeColors ( _rawText , false ) ; } invalidate ( "setText" ) ; return true ; } | Sets the text to be displayed by this label . |
11,645 | public void setTargetWidth ( int targetWidth ) { if ( targetWidth <= 0 ) { throw new IllegalArgumentException ( "Invalid target width '" + targetWidth + "'" ) ; } _constraints . width = targetWidth ; _constraints . height = 0 ; invalidate ( "setTargetWidth" ) ; } | Sets the target width for this label . Text will be wrapped to fit into this width forcibly breaking words on character boundaries if a single word is too long to fit into the target width . Calling this method will annul any previously established target height as we must have one degree of freedom in which to maneuver . |
11,646 | public void setTargetHeight ( int targetHeight ) { if ( targetHeight <= 0 ) { throw new IllegalArgumentException ( "Invalid target height '" + targetHeight + "'" ) ; } _constraints . width = 0 ; _constraints . height = targetHeight ; invalidate ( "setTargetHeight" ) ; } | Sets the target height for this label . A simple algorithm will be used to balance the width of the text in order that there are only as many lines of text as fit into the target height . If rendering the label as a single line of text causes it to be taller than the target height we simply render ourselves anyway . Calling this method will annul any previously established target width as we must have one degree of freedom in which to maneuver . |
11,647 | protected AttributedCharacterIterator textIterator ( Graphics2D gfx ) { Font font = ( _font == null ) ? gfx . getFont ( ) : _font ; HashMap < TextAttribute , Object > map = new HashMap < TextAttribute , Object > ( ) ; map . put ( TextAttribute . FONT , font ) ; if ( ( _style & UNDERLINE ) != 0 ) { map . put ( TextAttribute . UNDERLINE , TextAttribute . UNDERLINE_LOW_ONE_PIXEL ) ; } AttributedString text = new AttributedString ( _text , map ) ; addAttributes ( text ) ; return text . getIterator ( ) ; } | Constructs an attributed character iterator with our text and the appropriate font . |
11,648 | protected void addAttributes ( AttributedString text ) { if ( _rawText != null ) { Matcher m = COLOR_PATTERN . matcher ( _rawText ) ; int startSeg = 0 , endSeg = 0 ; Color lastColor = null ; while ( m . find ( ) ) { endSeg += m . start ( ) ; if ( lastColor != null ) { text . addAttribute ( TextAttribute . FOREGROUND , lastColor , startSeg , endSeg ) ; } String group = m . group ( 1 ) ; if ( "x" . equalsIgnoreCase ( group ) ) { lastColor = null ; } else { lastColor = new Color ( Integer . parseInt ( group , 16 ) ) ; } startSeg = endSeg ; endSeg -= m . end ( ) ; } if ( lastColor != null ) { text . addAttribute ( TextAttribute . FOREGROUND , lastColor , startSeg , _text . length ( ) ) ; } } } | Add any attributes to the text . |
11,649 | protected Rectangle2D getBounds ( TextLayout layout ) { if ( RunAnywhere . isMacOS ( ) ) { return layout . getOutline ( null ) . getBounds ( ) ; } else { return layout . getBounds ( ) ; } } | Gets the bounds of the supplied text layout in a way that works around the various befuckeries that currently happen on the Mac . |
11,650 | static void overwrite ( StringBuffer sb , int pos , String s ) { int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { sb . setCharAt ( pos + i , s . charAt ( i ) ) ; } } | This utility method is used when printing the table of results . |
11,651 | public static void parse ( DefaultHandler handler , InputStream in ) throws IOException , ParserConfigurationException , SAXException { XMLReader xr = _pfactory . newSAXParser ( ) . getXMLReader ( ) ; xr . setContentHandler ( handler ) ; xr . setErrorHandler ( handler ) ; xr . parse ( new InputSource ( in ) ) ; } | Parse the XML data in the given input stream using the specified handler object as both the content and error handler . |
11,652 | public LogBuilder append ( Object ... args ) { if ( args != null && args . length > 1 ) { for ( int ii = 0 , nn = args . length - ( args . length % 2 ) ; ii < nn ; ii += 2 ) { if ( _hasArgs ) { _log . append ( ", " ) ; } else { if ( _log . length ( ) > 0 ) { _log . append ( ' ' ) ; } _log . append ( '[' ) ; _hasArgs = true ; } _log . append ( args [ ii ] ) . append ( '=' ) ; try { _log . append ( StringUtil . toString ( args [ ii + 1 ] ) ) ; } catch ( Throwable t ) { _log . append ( "<toString() failure: " ) . append ( t ) . append ( '>' ) ; } } } return this ; } | Adds the given key value pairs to the log . |
11,653 | protected void openLog ( boolean freakout ) { try { FileOutputStream fout = new FileOutputStream ( _logPath , true ) ; OutputStreamWriter writer = new OutputStreamWriter ( fout , "UTF8" ) ; _logWriter = new PrintWriter ( new BufferedWriter ( writer ) , true ) ; log ( "log_opened " + _logPath ) ; } catch ( IOException ioe ) { String errmsg = "Unable to open audit log '" + _logPath + "'" ; if ( freakout ) { throw new RuntimeException ( errmsg , ioe ) ; } else { log . warning ( errmsg , "ioe" , ioe ) ; } } } | Opens our log file sets up our print writer and writes a message to it indicating that it was opened . |
11,654 | protected synchronized void checkRollOver ( ) { String newDayStamp = _dayFormat . format ( new Date ( ) ) ; if ( ! newDayStamp . equals ( _dayStamp ) ) { log ( "log_closed" ) ; _logWriter . close ( ) ; _logWriter = null ; String npath = _logPath . getPath ( ) + "." + _dayStamp ; if ( ! _logPath . renameTo ( new File ( npath ) ) ) { log . warning ( "Failed to rename audit log file" , "path" , _logPath , "npath" , npath ) ; } openLog ( false ) ; _dayStamp = newDayStamp ; } scheduleNextRolloverCheck ( ) ; } | Check to see if it s time to roll over the log file . |
11,655 | protected void scheduleNextRolloverCheck ( ) { Calendar cal = Calendar . getInstance ( ) ; long nextCheck = ( 1000L - cal . get ( Calendar . MILLISECOND ) ) + ( 59L - cal . get ( Calendar . SECOND ) ) * 1000L + ( 59L - cal . get ( Calendar . MINUTE ) ) * ( 1000L * 60L ) ; _rollover . schedule ( nextCheck ) ; } | Schedule the next check to see if we should roll the logs over . |
11,656 | public void init ( ExtendedProperties config ) { _sctx = ( ServletContext ) rsvc . getApplicationAttribute ( "ServletContext" ) ; if ( _sctx == null ) { rsvc . getLog ( ) . warn ( "ServletContextResourceLoader: servlet context was not supplied " + "as application context. A user of the servlet context resource " + "loader must call Velocity.setApplicationAttribute(" + "\"ServletContext\", getServletContext())." ) ; } } | Called by Velocity to initialize this resource loader . |
11,657 | public < V > FailureListener < V > retype ( Class < V > klass ) { @ SuppressWarnings ( "unchecked" ) FailureListener < V > casted = ( FailureListener < V > ) this ; return casted ; } | Recasts us to look like we re of a different type . We can safely do this because we know that requestCompleted never actually looks at the value passed in . |
11,658 | public void transition ( Class < ? > clazz , String name , Transition trans ) throws PersistenceException { if ( ! isTransitionApplied ( clazz , name ) && noteTransition ( clazz , name ) ) { try { trans . run ( ) ; } catch ( PersistenceException e ) { try { clearTransition ( clazz , name ) ; } catch ( PersistenceException pe ) { log . warning ( "Failed to clear failed transition" , "class" , clazz , "name" , name , pe ) ; } throw e ; } catch ( RuntimeException rte ) { try { clearTransition ( clazz , name ) ; } catch ( PersistenceException pe ) { log . warning ( "Failed to clear failed transition" , "class" , clazz , "name" , name , pe ) ; } throw rte ; } } } | Perform a transition if it has not already been applied and record that it was applied . |
11,659 | public boolean isTransitionApplied ( Class < ? > clazz , final String name ) throws PersistenceException { final String cname = clazz . getName ( ) ; return execute ( new Operation < Boolean > ( ) { public Boolean invoke ( Connection conn , DatabaseLiaison liaison ) throws SQLException , PersistenceException { PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( " select " + liaison . columnSQL ( "NAME" ) + " from " + liaison . tableSQL ( "TRANSITIONS" ) + " where " + liaison . columnSQL ( "CLASS" ) + "=?" + " and " + liaison . columnSQL ( "NAME" ) + "=?" ) ; stmt . setString ( 1 , cname ) ; stmt . setString ( 2 , name ) ; ResultSet rs = stmt . executeQuery ( ) ; if ( rs . next ( ) ) { return true ; } } finally { JDBCUtil . close ( stmt ) ; } return false ; } } ) ; } | Returns whether the specified name transition been applied . |
11,660 | public boolean noteTransition ( Class < ? > clazz , final String name ) throws PersistenceException { final String cname = clazz . getName ( ) ; return executeUpdate ( new Operation < Boolean > ( ) { public Boolean invoke ( Connection conn , DatabaseLiaison liaison ) throws SQLException , PersistenceException { PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( "insert into " + liaison . tableSQL ( "TRANSITIONS" ) + " (" + liaison . columnSQL ( "CLASS" ) + ", " + liaison . columnSQL ( "NAME" ) + ", " + liaison . columnSQL ( "APPLIED" ) + ") values (?, ?, ?)" ) ; stmt . setString ( 1 , cname ) ; stmt . setString ( 2 , name ) ; stmt . setTimestamp ( 3 , new Timestamp ( System . currentTimeMillis ( ) ) ) ; JDBCUtil . checkedUpdate ( stmt , 1 ) ; return true ; } catch ( SQLException sqe ) { if ( liaison . isDuplicateRowException ( sqe ) ) { return false ; } else { throw sqe ; } } finally { JDBCUtil . close ( stmt ) ; } } } ) ; } | Note in the database that a particular transition has been applied . |
11,661 | public void clearTransition ( Class < ? > clazz , final String name ) throws PersistenceException { final String cname = clazz . getName ( ) ; executeUpdate ( new Operation < Void > ( ) { public Void invoke ( Connection conn , DatabaseLiaison liaison ) throws SQLException , PersistenceException { PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( " delete from " + liaison . tableSQL ( "TRANSITIONS" ) + " where " + liaison . columnSQL ( "CLASS" ) + "=? " + " and " + liaison . columnSQL ( "NAME" ) + "=?" ) ; stmt . setString ( 1 , cname ) ; stmt . setString ( 2 , name ) ; stmt . executeUpdate ( ) ; } finally { JDBCUtil . close ( stmt ) ; } return null ; } } ) ; } | Clear the transition . |
11,662 | protected void registerColumnType ( String columnType , int jdbcType ) { columnTypeMatchers . add ( new ColumnTypeMatcher ( columnType ) ) ; jdbcTypes . put ( columnType , jdbcType ) ; } | Subclasses register a typename for the given type code . |
11,663 | public void setLabel ( String label ) { _label . setText ( label ) ; _label . setVisible ( ! StringUtil . isBlank ( label ) ) ; } | Updates the label displayed to the left of the slider . |
11,664 | public void setValue ( int value ) { _slider . setValue ( value ) ; _value . setText ( Integer . toString ( value ) ) ; } | Sets the slider s current value . |
11,665 | public String penniesToDollars ( int pennies ) { float decimal = pennies / 100f ; if ( pennies % 100 == 0 ) { return String . format ( "%.0f" , decimal ) ; } return String . format ( "%#.2f" , decimal ) ; } | Velocity currently doesn t support floats so we have to provide our own support to convert pennies to a dollar amount . |
11,666 | public String quote ( Date date ) { return ( date == null ) ? null : escape ( String . valueOf ( date ) ) ; } | Converts the date to a string and surrounds it in single - quotes via the escape method . If the date is null returns null . |
11,667 | public static String jigger ( String text ) { if ( text == null ) { return null ; } try { return new String ( text . getBytes ( "UTF8" ) , "8859_1" ) ; } catch ( UnsupportedEncodingException uee ) { log . warning ( "Jigger failed" , uee ) ; return text ; } } | Many databases simply fail to handle Unicode text properly and this routine provides a common workaround which is to represent a UTF - 8 string as an ISO - 8859 - 1 string . If you don t need to use the database s collation routines this allows you to do pretty much exactly what you want at the expense of having to jigger and dejigger every goddamned string that might contain multibyte characters every time you access the database . Three cheers for progress! |
11,668 | public static boolean createTableIfMissing ( Connection conn , String table , String [ ] definition , String postamble ) throws SQLException { if ( tableExists ( conn , table ) ) { return false ; } Statement stmt = conn . createStatement ( ) ; try { stmt . executeUpdate ( "create table " + table + "(" + StringUtil . join ( definition , ", " ) + ") " + postamble ) ; } finally { close ( stmt ) ; } log . info ( "Database table '" + table + "' created." ) ; return true ; } | Used to programatically create a database table . Does nothing if the table already exists . |
11,669 | public static String getIndexName ( Connection conn , String table , String column ) throws SQLException { ResultSet rs = conn . getMetaData ( ) . getIndexInfo ( "" , "" , table , false , true ) ; while ( rs . next ( ) ) { String tname = rs . getString ( "TABLE_NAME" ) ; String cname = rs . getString ( "COLUMN_NAME" ) ; String iname = rs . getString ( "INDEX_NAME" ) ; if ( tname . equals ( table ) && cname . equals ( column ) ) { return iname ; } } return null ; } | Returns the name of the index for the specified column in the specified table . |
11,670 | public static boolean isColumnNullable ( Connection conn , String table , String column ) throws SQLException { ResultSet rs = getColumnMetaData ( conn , table , column ) ; try { return rs . getString ( "IS_NULLABLE" ) . equals ( "YES" ) ; } finally { rs . close ( ) ; } } | Determines whether or not the specified column accepts null values . |
11,671 | public static String getColumnDefaultValue ( Connection conn , String table , String column ) throws SQLException { ResultSet rs = getColumnMetaData ( conn , table , column ) ; try { return rs . getString ( "COLUMN_DEF" ) ; } finally { rs . close ( ) ; } } | Returns a string representation of the default value for the specified column in the specified table . This may be null . |
11,672 | public static boolean dropIndex ( Connection conn , String table , String cname , String iname ) throws SQLException { if ( ! tableContainsIndex ( conn , table , cname , iname ) ) { return false ; } String update = "ALTER TABLE " + table + " DROP INDEX " + iname ; PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( update ) ; if ( stmt . executeUpdate ( ) == 1 ) { log . info ( "Database index '" + iname + "' removed from table '" + table + "'." ) ; } } finally { close ( stmt ) ; } return true ; } | Removes a named index from the specified table . |
11,673 | public static void dropPrimaryKey ( Connection conn , String table ) throws SQLException { String update = "ALTER TABLE " + table + " DROP PRIMARY KEY" ; PreparedStatement stmt = null ; try { stmt = conn . prepareStatement ( update ) ; if ( stmt . executeUpdate ( ) == 1 ) { log . info ( "Database primary key removed from '" + table + "'." ) ; } } finally { close ( stmt ) ; } } | Removes the primary key from the specified table . |
11,674 | public static String genAuthCode ( User user ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( user . password ) ; buf . append ( System . currentTimeMillis ( ) ) ; buf . append ( Math . random ( ) ) ; return StringUtil . md5hex ( buf . toString ( ) ) ; } | Generates a new random session identifier for the supplied user . |
11,675 | public static String legacyEncrypt ( String username , String password , boolean ignoreUserCase ) { if ( ignoreUserCase ) { username = username . toLowerCase ( ) ; } return Crypt . crypt ( StringUtil . truncate ( username , 2 ) , password ) ; } | Encrypts passwords the way we used to . |
11,676 | public static < A , B , C > Triple < A , B , C > newTriple ( A a , B b , C c ) { return new Triple < A , B , C > ( a , b , c ) ; } | Creates a triple with the specified values . |
11,677 | protected void paintBackground ( Graphics g ) { g . setColor ( getBackground ( ) ) ; g . fillRect ( 0 , 0 , getWidth ( ) , getHeight ( ) ) ; } | Paint the background . |
11,678 | protected void paintBox ( Graphics g , Rectangle box ) { g . setColor ( getForeground ( ) ) ; g . drawRect ( box . x , box . y , box . width , box . height ) ; } | Paint the box that represents the visible area of the two - dimensional scrolling area . |
11,679 | protected void updateBox ( ) { int hmin = _horz . getMinimum ( ) ; int vmin = _vert . getMinimum ( ) ; _hFactor = ( _active . width ) / ( float ) ( _horz . getMaximum ( ) - hmin ) ; _vFactor = ( _active . height ) / ( float ) ( _vert . getMaximum ( ) - vmin ) ; _box . x = _active . x + Math . round ( ( _horz . getValue ( ) - hmin ) * _hFactor ) ; _box . width = Math . round ( _horz . getExtent ( ) * _hFactor ) ; _box . y = _active . y + Math . round ( ( _vert . getValue ( ) - vmin ) * _vFactor ) ; _box . height = Math . round ( _vert . getExtent ( ) * _vFactor ) ; } | Recalculate the size of the box . You shouldn t need to override this to provide custom functionality . Use the above three methods instead . |
11,680 | public int [ ] toIntArray ( int [ ] target , int offset ) { System . arraycopy ( _values , 0 , target , offset , _size ) ; return target ; } | Serializes this int set into an array at the specified offset . The array must be large enough to hold all the integers in our set at the offset specified . |
11,681 | public short [ ] toShortArray ( ) { short [ ] values = new short [ _size ] ; for ( int ii = 0 ; ii < _size ; ii ++ ) { values [ ii ] = ( short ) _values [ ii ] ; } return values ; } | Creates an array of shorts from the contents of this set . Any values outside the range of a short will be truncated by way of a cast . |
11,682 | public Interator interator ( ) { return new AbstractInterator ( ) { public boolean hasNext ( ) { return ( _pos < _size ) ; } public int nextInt ( ) { if ( _pos >= _size ) { throw new NoSuchElementException ( ) ; } _canRemove = true ; return _values [ _pos ++ ] ; } public void remove ( ) { if ( ! _canRemove ) { throw new IllegalStateException ( ) ; } System . arraycopy ( _values , _pos , _values , _pos - 1 , _size - _pos ) ; _pos -- ; _size -- ; _canRemove = false ; } protected int _pos ; protected boolean _canRemove ; } ; } | from interface IntSet |
11,683 | protected void removeDuplicates ( ) { if ( _size > 1 ) { int last = _values [ 0 ] ; for ( int ii = 1 ; ii < _size ; ) { if ( _values [ ii ] == last ) { _size -- ; System . arraycopy ( _values , ii + 1 , _values , ii , _size - ii ) ; } else { last = _values [ ii ++ ] ; } } } } | Removes duplicates from our internal array . Only used by our constructors when initializing from a potentially duplicate - containing source array or collection . |
11,684 | public void add ( Object value ) { _list [ _lastPos ++ % _list . length ] = value ; if ( _lastPos == 2 * _list . length ) { _lastPos = _list . length ; } } | Adds the specified value to the list . |
11,685 | public static String getMessage ( Throwable ex ) { String msg = DEFAULT_ERROR_MSG ; for ( int i = 0 ; i < _keys . size ( ) ; i ++ ) { Class < ? > cl = _keys . get ( i ) ; if ( cl . isInstance ( ex ) ) { msg = _values . get ( i ) ; break ; } } return msg . replace ( MESSAGE_MARKER , ex . getMessage ( ) ) ; } | Looks up the supplied exception in the map and returns the most specific error message available for exceptions of that class . |
11,686 | public static void close ( Reader in ) { if ( in != null ) { try { in . close ( ) ; } catch ( IOException ioe ) { log . warning ( "Error closing reader" , "reader" , in , "cause" , ioe ) ; } } } | Convenient close for a Reader . Use in a finally clause and love life . |
11,687 | public static void close ( Writer out ) { if ( out != null ) { try { out . close ( ) ; } catch ( IOException ioe ) { log . warning ( "Error closing writer" , "writer" , out , "cause" , ioe ) ; } } } | Convenient close for a Writer . Use in a finally clause and love life . |
11,688 | protected void newPage ( ) { if ( ! bean . isSubreport ( ) ) { try { stream . print ( "</table>\n" ) ; stream . println ( "<p style=\"page-break-before: always\"></p>\n" ) ; if ( bean . getReportLayout ( ) . isUseSize ( ) ) { stream . print ( "<table>" ) ; } else { stream . print ( "<table style='width:100%'>" ) ; } if ( bean . getReportLayout ( ) . isHeaderOnEveryPage ( ) ) { printHeaderBand ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } | tables need to be broken in order to force a page break . |
11,689 | public boolean checkCall ( String warning ) { if ( _firstCall == null ) { _firstCall = new Exception ( "---- First call (at " + _format . format ( new Date ( ) ) + ") ----" ) ; return false ; } log . warning ( warning , new Exception ( ) ) ; log . warning ( "First call:" , _firstCall ) ; return true ; } | This method should be called when the code passes through the code path that should be called only once . The first time through this path the method will return false and record the stack trace . Subsquent calls will log an error and report the current and first - time - through stack traces . |
11,690 | protected Properties loadConfiguration ( ServletConfig config ) throws IOException { Properties props = loadVelocityProps ( config ) ; if ( _app == null ) { return props ; } _app . configureVelocity ( config , props ) ; configureResourceManager ( config , props ) ; props . setProperty ( "userdirective" , ImportDirective . class . getName ( ) ) ; props . put ( RuntimeSingleton . RUNTIME_LOG_LOGSYSTEM_CLASS , ServletContextLogger . class . getName ( ) ) ; return props ; } | We load our velocity properties from the classpath rather than from a file . |
11,691 | @ SuppressWarnings ( "rawtypes" ) public Object methodException ( Class clazz , String method , Exception e ) throws Exception { log . warning ( "Exception" , "class" , clazz . getName ( ) , "method" , method , e ) ; return "" ; } | Called when a method throws an exception during template evaluation . |
11,692 | protected Template selectTemplate ( int siteId , InvocationContext ctx ) throws ResourceNotFoundException , ParseErrorException , Exception { String path = ctx . getRequest ( ) . getServletPath ( ) ; if ( _usingSiteLoading ) { path = siteId + ":" + path ; } return RuntimeSingleton . getTemplate ( path ) ; } | This method is called to select the appropriate template for this request . The default implementation simply loads the template using Velocity s default template loading services based on the URI provided in the request . |
11,693 | protected void mergeTemplate ( Template template , InvocationContext context ) throws ResourceNotFoundException , ParseErrorException , MethodInvocationException , UnsupportedEncodingException , IOException , Exception { HttpServletResponse response = context . getResponse ( ) ; ServletOutputStream output = response . getOutputStream ( ) ; String encoding = response . getCharacterEncoding ( ) ; VelocityWriter vw = null ; try { vw = ( VelocityWriter ) _writerPool . get ( ) ; if ( vw == null ) { vw = new VelocityWriter ( new OutputStreamWriter ( output , encoding ) , 4 * 1024 , true ) ; } else { vw . recycle ( new OutputStreamWriter ( output , encoding ) ) ; } template . merge ( context , vw ) ; } catch ( IOException ioe ) { log . info ( "Failed to write response" , "uri" , context . getRequest ( ) . getRequestURI ( ) , "error" , ioe ) ; } finally { if ( vw != null ) { try { vw . flush ( ) ; } catch ( IOException e ) { } vw . recycle ( null ) ; _writerPool . put ( vw ) ; } } } | Merges the template with the context . |
11,694 | protected Logic resolveLogic ( String path ) { String lclass = _app . generateClass ( path ) ; Logic logic = _logic . get ( lclass ) ; if ( logic == null ) { logic = instantiateLogic ( path , lclass ) ; if ( logic == null ) { logic = new DummyLogic ( ) ; } _logic . put ( lclass , logic ) ; } return logic ; } | This method is called to select the appropriate logic for this request URI . |
11,695 | protected Logic instantiateLogic ( String path , String lclass ) { try { Class < ? > pcl = Class . forName ( lclass ) ; return ( Logic ) pcl . newInstance ( ) ; } catch ( ClassNotFoundException cnfe ) { } catch ( Throwable t ) { log . warning ( "Unable to instantiate logic for application" , "path" , path , "lclass" , lclass , t ) ; } return null ; } | Instantiates a logic instance with the supplied class name . May return null if no such class exists . |
11,696 | public void addTask ( ExecutorTask task ) { for ( int ii = 0 , nn = _queue . size ( ) ; ii < nn ; ii ++ ) { ExecutorTask taskOnQueue = _queue . get ( ii ) ; if ( taskOnQueue . merge ( task ) ) { return ; } } _queue . add ( task ) ; if ( ! _executingNow ) { checkNext ( ) ; } } | Add a task to the executor it is expected that this method is called on the ResultReceiver thread . |
11,697 | protected void checkNext ( ) { _executingNow = ! _queue . isEmpty ( ) ; if ( _executingNow ) { ExecutorTask task = _queue . remove ( 0 ) ; final ExecutorThread thread = new ExecutorThread ( task ) ; thread . start ( ) ; new Interval ( Interval . RUN_DIRECT ) { public void expired ( ) { thread . abort ( ) ; } } . schedule ( task . getTimeout ( ) ) ; } } | Execute the next task if applicable . |
11,698 | public static String [ ] getMACAddresses ( ) { String [ ] cmds ; if ( RunAnywhere . isWindows ( ) ) { cmds = WINDOWS_CMDS ; } else { cmds = UNIX_CMDS ; } return parseMACs ( tryCommands ( cmds ) ) ; } | Get all the MAC addresses of the hardware we are running on that we can find . |
11,699 | protected static String [ ] parseMACs ( String text ) { if ( text == null ) { return new String [ 0 ] ; } Matcher m = MACRegex . matcher ( text ) ; ArrayList < String > list = new ArrayList < String > ( ) ; while ( m . find ( ) ) { String mac = m . group ( 1 ) . toUpperCase ( ) ; mac = mac . replace ( ':' , '-' ) ; if ( mac . startsWith ( "44-45-53" ) ) { continue ; } else if ( mac . startsWith ( "00-53-45-00" ) ) { continue ; } else if ( mac . startsWith ( "00-E0-06-09-55-66" ) ) { continue ; } else if ( mac . startsWith ( "00-04-4B-80-80-03" ) ) { continue ; } else if ( mac . startsWith ( "00-03-8A" ) ) { continue ; } else if ( mac . startsWith ( "02-03-8A-00-00-11" ) ) { continue ; } else if ( mac . startsWith ( "FF-FF-FF-FF-FF-FF" ) ) { continue ; } else if ( mac . startsWith ( "02-00-4C-4F-4F-50" ) ) { continue ; } else if ( mac . startsWith ( "00-00-00-00-00-00" ) ) { continue ; } list . add ( mac ) ; } return list . toArray ( new String [ 0 ] ) ; } | Look through the text for all the MAC addresses we can find . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.