idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
14,900
public void moveAndFadeOut ( Path path , long pathDuration , float fadePortion ) { move ( path ) ; setAlpha ( 1.0f ) ; _fadeStamp = 0 ; _pathDuration = pathDuration ; _fadeOutDuration = ( long ) ( pathDuration * fadePortion ) ; _fadeDelay = _pathDuration - _fadeOutDuration ; }
Puts this sprite on the specified path and fades it out over the specified duration .
14,901
public void moveAndFadeInAndOut ( Path path , long pathDuration , float fadePortion ) { move ( path ) ; setAlpha ( 0.0f ) ; _pathDuration = pathDuration ; _fadeInDuration = _fadeOutDuration = ( long ) ( pathDuration * fadePortion ) ; }
Puts this sprite on the specified path fading it in over the specified duration at the beginning and fading it out at the end .
14,902
public void setAlpha ( float alpha ) { if ( alpha < 0.0f ) { alpha = 0.0f ; } else if ( alpha > 1.0f ) { alpha = 1.0f ; } if ( alpha != _alphaComposite . getAlpha ( ) ) { _alphaComposite = AlphaComposite . getInstance ( AlphaComposite . SRC_OVER , alpha ) ; if ( _mgr != null ) { _mgr . getRegionManager ( ) . invalidateRegion ( _bounds ) ; } } }
Sets the alpha value of this sprite .
14,903
public static void register ( PerformanceObserver obs , String name , long delta ) { Map < String , PerformanceAction > actions = _observers . get ( obs ) ; if ( actions == null ) { _observers . put ( obs , actions = Maps . newHashMap ( ) ) ; } actions . put ( name , new PerformanceAction ( obs , name , delta ) ) ; }
Register a new action with an observer the action name and the milliseconds to wait between checkpointing the action s performance .
14,904
public static void unregister ( PerformanceObserver obs , String name ) { Map < String , PerformanceAction > actions = _observers . get ( obs ) ; if ( actions == null ) { log . warning ( "Attempt to unregister by unknown observer " + "[observer=" + obs + ", name=" + name + "]." ) ; return ; } PerformanceAction action = actions . remove ( name ) ; if ( action == null ) { log . warning ( "Attempt to unregister unknown action " + "[observer=" + obs + ", name=" + name + "]." ) ; return ; } if ( actions . size ( ) == 0 ) { _observers . remove ( obs ) ; } }
Un - register the named action associated with the given observer .
14,905
public static void tick ( PerformanceObserver obs , String name ) { Map < String , PerformanceAction > actions = _observers . get ( obs ) ; if ( actions == null ) { log . warning ( "Attempt to tick by unknown observer " + "[observer=" + obs + ", name=" + name + "]." ) ; return ; } PerformanceAction action = actions . get ( name ) ; if ( action == null ) { log . warning ( "Attempt to tick unknown value " + "[observer=" + obs + ", name=" + name + "]." ) ; return ; } action . tick ( ) ; }
Tick the named action associated with the given observer .
14,906
private URI _getSpecURI ( String spec ) { URI specURI = URI . create ( spec ) ; if ( _scheme . indexOf ( ':' ) == - 1 ) { return specURI ; } String schemeSpecificPart = specURI . getSchemeSpecificPart ( ) ; return URI . create ( schemeSpecificPart ) ; }
the appropriate URI that can be used to retrieve the needed parts .
14,907
protected boolean checkTileIndex ( int tileIndex ) { int tcount = getTileCount ( ) ; if ( tileIndex >= 0 && tileIndex < tcount ) { return true ; } else { log . warning ( "Requested invalid tile [tset=" + this + ", index=" + tileIndex + "]." , new Exception ( ) ) ; return false ; } }
Used to ensure that the specified tile index is valid .
14,908
public TagInfo getTag ( String shortname ) { TagInfo tags [ ] = getTags ( ) ; if ( tags == null || tags . length == 0 ) { return null ; } for ( int i = 0 ; i < tags . length ; i ++ ) { if ( tags [ i ] . getTagName ( ) . equals ( shortname ) ) { return tags [ i ] ; } } return null ; }
Get the TagInfo for a given tag name looking through all the tags in this tag library .
14,909
public TagFileInfo getTagFile ( String shortname ) { TagFileInfo tagFiles [ ] = getTagFiles ( ) ; if ( tagFiles == null || tagFiles . length == 0 ) { return null ; } for ( int i = 0 ; i < tagFiles . length ; i ++ ) { if ( tagFiles [ i ] . getName ( ) . equals ( shortname ) ) { return tagFiles [ i ] ; } } return null ; }
Get the TagFileInfo for a given tag name looking through all the tag files in this tag library .
14,910
public FunctionInfo getFunction ( String name ) { if ( functions == null || functions . length == 0 ) { System . err . println ( "No functions" ) ; return null ; } for ( int i = 0 ; i < functions . length ; i ++ ) { if ( functions [ i ] . getName ( ) . equals ( name ) ) { return functions [ i ] ; } } return null ; }
Get the FunctionInfo for a given function name looking through all the functions in this tag library .
14,911
protected int readSamples ( ) throws IOException { int samples ; while ( ( samples = _dsp . synthesis_pcmout ( _pcm , _offsets ) ) <= 0 ) { if ( samples == 0 && ! readPacket ( ) ) { return 0 ; } if ( _block . synthesis ( _packet ) == 0 ) { _dsp . synthesis_blockin ( _block ) ; } } return samples ; }
Reads a buffer s worth of samples .
14,912
protected boolean readPacket ( ) throws IOException { int result ; while ( ( result = _stream . packetout ( _packet ) ) != 1 ) { if ( result == 0 && ! readPage ( ) ) { return false ; } } return true ; }
Reads a packet .
14,913
protected boolean readPage ( ) throws IOException { int result ; while ( ( result = _sync . pageout ( _page ) ) != 1 ) { if ( result == 0 && ! readChunk ( ) ) { return false ; } } _stream . pagein ( _page ) ; return true ; }
Reads in a page .
14,914
protected boolean readChunk ( ) throws IOException { int offset = _sync . buffer ( BUFFER_SIZE ) ; int bytes = _in . read ( _sync . data , offset , BUFFER_SIZE ) ; if ( bytes > 0 ) { _sync . wrote ( bytes ) ; return true ; } return false ; }
Reads in a chunk of data from the underlying input stream .
14,915
public static TrimmedTileSet trimTileSet ( TileSet source , OutputStream destImage ) throws IOException { return trimTileSet ( source , destImage , FastImageIO . FILE_SUFFIX ) ; }
Convenience function to trim the tile set and save it using FastImageIO .
14,916
public boolean sourceIsReady ( ) { _sourceLastMod = _source . lastModified ( ) ; if ( _unpacked != null && _unpacked . lastModified ( ) != _sourceLastMod ) { try { resolveJarFile ( ) ; } catch ( IOException ioe ) { log . warning ( "Failure resolving jar file" , "source" , _source , ioe ) ; wipeBundle ( true ) ; return false ; } log . info ( "Unpacking into " + _cache + "..." ) ; if ( ! _cache . exists ( ) ) { if ( ! _cache . mkdir ( ) ) { log . warning ( "Failed to create bundle cache directory" , "dir" , _cache ) ; closeJar ( ) ; return false ; } } else { FileUtil . recursiveClean ( _cache ) ; } if ( ! FileUtil . unpackJar ( _jarSource , _cache ) ) { wipeBundle ( true ) ; return false ; } try { _unpacked . createNewFile ( ) ; if ( ! _unpacked . setLastModified ( _sourceLastMod ) ) { log . warning ( "Failed to set last mod on stamp file" , "file" , _unpacked ) ; } } catch ( IOException ioe ) { log . warning ( "Failure creating stamp file" , "file" , _unpacked , ioe ) ; } } return true ; }
Called by the resource manager once it has ensured that our resource jar file is up to date and ready for reading .
14,917
public void wipeBundle ( boolean deleteJar ) { if ( _cache != null ) { FileUtil . recursiveClean ( _cache ) ; } if ( _unpacked != null ) { _unpacked . delete ( ) ; } File vfile = new File ( FileUtil . resuffix ( _source , ".jar" , ".jarv" ) ) ; if ( vfile . exists ( ) && ! vfile . delete ( ) ) { log . warning ( "Failed to delete vfile" , "file" , vfile ) ; } if ( deleteJar && _source != null ) { closeJar ( ) ; if ( ! _source . delete ( ) ) { log . warning ( "Failed to delete source" , "source" , _source , "exists" , _source . exists ( ) ) ; } } }
Clears out everything associated with this resource bundle in the hopes that we can download it afresh and everything will work the next time around .
14,918
public File getResourceFile ( String path ) throws IOException { if ( resolveJarFile ( ) ) { return null ; } if ( _cache != null ) { File cfile = new File ( _cache , path ) ; if ( cfile . exists ( ) ) { return cfile ; } else { return null ; } } String tpath = StringUtil . md5hex ( _source . getPath ( ) + "%" + path ) ; File tfile = new File ( getCacheDir ( ) , tpath ) ; if ( tfile . exists ( ) && ( tfile . lastModified ( ) > _sourceLastMod ) ) { return tfile ; } JarEntry entry = _jarSource . getJarEntry ( path ) ; if ( entry == null ) { return null ; } BufferedOutputStream fout = new BufferedOutputStream ( new FileOutputStream ( tfile ) ) ; InputStream jin = _jarSource . getInputStream ( entry ) ; StreamUtil . copy ( jin , fout ) ; jin . close ( ) ; fout . close ( ) ; return tfile ; }
Returns a file from which the specified resource can be loaded . This method will unpack the resource into a temporary directory and return a reference to that file .
14,919
public boolean containsResource ( String path ) { try { if ( resolveJarFile ( ) ) { return false ; } return ( _jarSource . getJarEntry ( path ) != null ) ; } catch ( IOException ioe ) { return false ; } }
Returns true if this resource bundle contains the resource with the specified path . This avoids actually loading the resource in the event that the caller only cares to know that the resource exists .
14,920
protected boolean resolveJarFile ( ) throws IOException { if ( _sourceLastMod == - 1 ) { return true ; } if ( ! _source . exists ( ) ) { throw new IOException ( "Missing jar file for resource bundle: " + _source + "." ) ; } try { if ( _jarSource == null ) { _jarSource = new JarFile ( _source ) ; } return false ; } catch ( IOException ioe ) { String msg = "Failed to resolve resource bundle jar file '" + _source + "'" ; log . warning ( msg + "." , ioe ) ; throw ( IOException ) new IOException ( msg ) . initCause ( ioe ) ; } }
Creates the internal jar file reference if we ve not already got it ; we do this lazily so as to avoid any jar - or zip - file - related antics until and unless doing so is required and because the resource manager would like to be able to create bundles before the associated files have been fully downloaded .
14,921
public static File getCacheDir ( ) { if ( _tmpdir == null ) { String tmpdir = System . getProperty ( "java.io.tmpdir" ) ; if ( tmpdir == null ) { log . info ( "No system defined temp directory. Faking it." ) ; tmpdir = System . getProperty ( "user.home" ) ; } setCacheDir ( new File ( tmpdir ) ) ; } return _tmpdir ; }
Returns the cache directory used for unpacked resources .
14,922
public static void setCacheDir ( File tmpdir ) { String rando = Long . toHexString ( ( long ) ( Math . random ( ) * Long . MAX_VALUE ) ) ; _tmpdir = new File ( tmpdir , "narcache_" + rando ) ; if ( ! _tmpdir . exists ( ) ) { if ( _tmpdir . mkdirs ( ) ) { log . debug ( "Created narya temp cache directory '" + _tmpdir + "'." ) ; } else { log . warning ( "Failed to create temp cache directory '" + _tmpdir + "'." ) ; } } Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { log . info ( "Clearing narya temp cache '" + _tmpdir + "'." ) ; FileUtil . recursiveDelete ( _tmpdir ) ; } } ) ; }
Specifies the directory in which our temporary resource files should be stored .
14,923
protected static String stripSuffix ( String path ) { if ( path . endsWith ( ".jar" ) ) { return path . substring ( 0 , path . length ( ) - 4 ) ; } else { return path + "-cache" ; } }
Strips the . jar off of jar file paths .
14,924
public static < T > CloseableIterator < T > distinct ( final CloseableIterator < T > iterator ) { return wrap ( Iterators2 . distinct ( iterator ) , iterator ) ; }
If we can assume the closeable iterator is sorted return the distinct elements . This only works if the data provided is sorted .
14,925
public Stream < RangeWithCount > stream ( ) { return buckets_ . stream ( ) . map ( bucket -> new RangeWithCount ( bucket . getRange ( ) , bucket . getEvents ( ) ) ) ; }
Returns a map of range - &gt ; event count . The elements of the stream are a mutable copy of the internal data .
14,926
public Optional < Double > avg ( ) { if ( isEmpty ( ) ) return Optional . empty ( ) ; return Optional . of ( sum ( ) / getEventCount ( ) ) ; }
Return the average of the histogram .
14,927
public double sum ( ) { return buckets_ . stream ( ) . mapToDouble ( b -> b . getRange ( ) . getMidPoint ( ) * b . getEvents ( ) ) . sum ( ) ; }
Return the sum of the histogram .
14,928
public double get ( double index ) { ListIterator < Bucket > b = buckets_ . listIterator ( 0 ) ; ListIterator < Bucket > e = buckets_ . listIterator ( buckets_ . size ( ) ) ; while ( b . nextIndex ( ) < e . previousIndex ( ) ) { final ListIterator < Bucket > mid = buckets_ . listIterator ( b . nextIndex ( ) / 2 + e . nextIndex ( ) / 2 ) ; final Bucket mid_bucket = mid . next ( ) ; mid . previous ( ) ; if ( mid_bucket . getRunningEventsCount ( ) == index && mid . nextIndex ( ) >= e . previousIndex ( ) ) { return mid_bucket . getRange ( ) . getCeil ( ) ; } else if ( mid_bucket . getRunningEventsCount ( ) <= index ) { b = mid ; b . next ( ) ; } else if ( mid_bucket . getRunningEventsCount ( ) - mid_bucket . getEvents ( ) > index ) { e = mid ; } else { b = mid ; break ; } } final Bucket bucket = b . next ( ) ; b . previous ( ) ; final double low = bucket . getRunningEventsCount ( ) - bucket . getEvents ( ) ; final double off = index - low ; final double left_fraction = off / bucket . getEvents ( ) ; final double right_fraction = 1 - left_fraction ; return bucket . getRange ( ) . getCeil ( ) * left_fraction + bucket . getRange ( ) . getFloor ( ) * right_fraction ; }
Get the value at a given position .
14,929
public Histogram modifyEventCounters ( BiFunction < Range , Double , Double > fn ) { return new Histogram ( stream ( ) . map ( entry -> { entry . setCount ( fn . apply ( entry . getRange ( ) , entry . getCount ( ) ) ) ; return entry ; } ) ) ; }
Create a new histogram after applying the function on each of the event counters .
14,930
public static Histogram add ( Histogram x , Histogram y ) { return new Histogram ( Stream . concat ( x . stream ( ) , y . stream ( ) ) ) ; }
Add two histograms together .
14,931
public static Histogram subtract ( Histogram x , Histogram y ) { return new Histogram ( Stream . concat ( x . stream ( ) , y . stream ( ) . map ( rwc -> { rwc . setCount ( - rwc . getCount ( ) ) ; return rwc ; } ) ) ) ; }
Subtracts two histograms .
14,932
public static Histogram multiply ( Histogram x , double y ) { return x . modifyEventCounters ( ( r , d ) -> d * y ) ; }
Multiply histogram by scalar .
14,933
public static Histogram divide ( Histogram x , double y ) { return x . modifyEventCounters ( ( r , d ) -> d / y ) ; }
Divide histogram by scalar .
14,934
public int compareTo ( Histogram o ) { int cmp = 0 ; final Iterator < Bucket > iter = buckets_ . iterator ( ) , o_iter = o . buckets_ . iterator ( ) ; while ( cmp == 0 && iter . hasNext ( ) && o_iter . hasNext ( ) ) { final Bucket next = iter . next ( ) , o_next = o_iter . next ( ) ; cmp = Double . compare ( next . getRange ( ) . getFloor ( ) , o_next . getRange ( ) . getFloor ( ) ) ; if ( cmp == 0 ) cmp = Double . compare ( next . getRange ( ) . getCeil ( ) , o_next . getRange ( ) . getCeil ( ) ) ; if ( cmp == 0 ) cmp = Double . compare ( next . getEvents ( ) , o_next . getEvents ( ) ) ; } if ( cmp == 0 ) cmp = ( iter . hasNext ( ) ? 1 : ( o_iter . hasNext ( ) ? - 1 : 0 ) ) ; return cmp ; }
Compare two histograms .
14,935
protected final Object convertToObject ( final String text ) throws Exception { Map map = CollectionUtil . toMap ( text , keyEditor , valueEditor ) ; if ( map == null ) { return null ; } return createMap ( map ) ; }
Treats the text value of this property as an input stream that is converted into a Property bundle .
14,936
public NodeGraphicDefinition getGroupGraphics ( Object group , Set < String > groupElements ) { return null ; }
we have no groups in this example
14,937
public static final String name ( SimpleGroupPath group , MetricName metric ) { return name ( Stream . concat ( group . getPath ( ) . stream ( ) , metric . getPath ( ) . stream ( ) ) . collect ( Collectors . joining ( "." ) ) ) ; }
Convert a group + metric to a wavefront name .
14,938
private static Optional < Map . Entry < String , String > > createTagEntry ( Map . Entry < String , MetricValue > tag_entry ) { final Optional < String > opt_tag_value = tag_entry . getValue ( ) . asString ( ) ; return opt_tag_value . map ( tag_value -> SimpleMapEntry . create ( name ( tag_entry . getKey ( ) ) , escapeTagValue ( tag_value ) ) ) ; }
Transform a tag entry into a wavefront tag .
14,939
private static Map . Entry < String , String > maybeTruncateTagEntry ( Map . Entry < String , String > tag_entry ) { String k = tag_entry . getKey ( ) ; String v = tag_entry . getValue ( ) ; if ( k . length ( ) + v . length ( ) <= MAX_TAG_KEY_VAL_CHARS - 2 ) return tag_entry ; if ( k . length ( ) > TRUNCATE_TAG_NAME ) k = k . substring ( 0 , TRUNCATE_TAG_NAME ) ; if ( k . length ( ) + v . length ( ) > MAX_TAG_KEY_VAL_CHARS - 2 ) v = v . substring ( 0 , MAX_TAG_KEY_VAL_CHARS - 2 - k . length ( ) ) ; return SimpleMapEntry . create ( k , v ) ; }
Truncate tag keys and values to prevent them from exceeding the max length of a tag entry .
14,940
public static Map < String , String > tags ( Tags tags ) { return tags . stream ( ) . map ( WavefrontStrings :: createTagEntry ) . flatMap ( opt -> opt . map ( Stream :: of ) . orElseGet ( Stream :: empty ) ) . map ( WavefrontStrings :: maybeTruncateTagEntry ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; }
Create a map of tags for wavefront .
14,941
public static Optional < String > wavefrontValue ( MetricValue mv ) { if ( mv . isInfiniteOrNaN ( ) ) return Optional . empty ( ) ; return mv . value ( ) . map ( Number :: toString ) ; }
Create a wavefront compatible string representation of the metric value .
14,942
private static String extractTagSource ( Map < String , String > tag_map ) { return Optional . ofNullable ( tag_map . remove ( "source" ) ) . orElseGet ( ( ) -> { return Optional . ofNullable ( tag_map . get ( "cluster" ) ) . map ( WavefrontStrings :: escapeTagValue ) . orElseGet ( ( ) -> tag_map . getOrDefault ( "moncluster" , "monsoon" ) ) ; } ) ; }
Extract the source tag from the tag_map .
14,943
private static String wavefrontLine ( DateTime ts , SimpleGroupPath group , MetricName metric , String value , String source , Map < String , String > tag_map ) { return new StringBuilder ( ) . append ( name ( group , metric ) ) . append ( ' ' ) . append ( value ) . append ( ' ' ) . append ( timestamp ( ts ) ) . append ( ' ' ) . append ( "source=" ) . append ( source ) . append ( ' ' ) . append ( tag_map . entrySet ( ) . stream ( ) . map ( entry -> entry . getKey ( ) + "=\"" + entry . getValue ( ) + '\"' ) . collect ( Collectors . joining ( " " ) ) ) . toString ( ) ; }
Build the wavefront line from its parts .
14,944
public static Optional < String > wavefrontLine ( DateTime ts , GroupName group , MetricName metric , MetricValue metric_value ) { return wavefrontValue ( metric_value ) . map ( value -> { final Map < String , String > tag_map = tags ( group . getTags ( ) ) ; final String source = extractTagSource ( tag_map ) ; return wavefrontLine ( ts , group . getPath ( ) , metric , value , source , tag_map ) ; } ) ; }
Convert a metric to a wavefront string .
14,945
public static Stream < String > wavefrontLine ( DateTime ts , TimeSeriesValue tsv ) { final GroupName group = tsv . getGroup ( ) ; return tsv . getMetrics ( ) . entrySet ( ) . stream ( ) . flatMap ( metricEntry -> wavefrontLineForMetric ( ts , group , metricEntry ) ) ; }
Convert a time series value into the string entries for wavefront .
14,946
public Point getEndPos ( ) { return new Point ( ( int ) ( _center . x + Math . round ( Math . cos ( _sangle + _delta ) * _xradius ) ) , ( int ) ( _center . y + Math . round ( Math . sin ( _sangle + _delta ) * _yradius ) ) ) ; }
Returns the position of the end of the path .
14,947
public static Serializable loadConfig ( InputStream source ) throws IOException { try { ObjectInputStream oin = new ObjectInputStream ( source ) ; return ( Serializable ) oin . readObject ( ) ; } catch ( ClassNotFoundException cnfe ) { String errmsg = "Unknown config class" ; throw ( IOException ) new IOException ( errmsg ) . initCause ( cnfe ) ; } }
Unserializes a configuration object from the supplied input stream .
14,948
public static void saveConfig ( File target , Serializable config ) throws IOException { FileOutputStream fout = new FileOutputStream ( target ) ; ObjectOutputStream oout = new ObjectOutputStream ( fout ) ; oout . writeObject ( config ) ; oout . close ( ) ; }
Serializes the supplied configuration object to the specified file path .
14,949
public void historyUpdated ( int adjustment ) { if ( adjustment != 0 ) { for ( int ii = 0 , nn = _showingHistory . size ( ) ; ii < nn ; ii ++ ) { ChatGlyph cg = _showingHistory . get ( ii ) ; cg . histIndex -= adjustment ; } resetHistoryOffset ( ) ; } if ( isLaidOut ( ) && isHistoryMode ( ) ) { int val = _historyModel . getValue ( ) ; updateHistBar ( val - adjustment ) ; if ( ( val != _historyModel . getValue ( ) ) || ( adjustment != 0 ) || ! _histOffsetFinal ) { figureCurrentHistory ( ) ; } } }
from interface HistoryList . Observer
14,950
public boolean displayMessage ( ChatMessage message , boolean alreadyDisplayed ) { if ( ! isLaidOut ( ) ) { return false ; } Graphics2D gfx = getTargetGraphics ( ) ; if ( gfx != null ) { displayMessage ( message , gfx ) ; gfx . dispose ( ) ; return true ; } return false ; }
documentation inherited from superinterface ChatDisplay
14,951
protected void updateDimmed ( List < ? extends ChatGlyph > glyphs ) { for ( ChatGlyph glyph : glyphs ) { glyph . setDim ( _dimmed ) ; } }
Update the chat glyphs in the specified list to be set to the current dimmed setting .
14,952
protected void setHistoryEnabled ( boolean historyEnabled ) { if ( historyEnabled && _historyModel == null ) { _historyModel = _scrollbar . getModel ( ) ; _historyModel . addChangeListener ( this ) ; resetHistoryOffset ( ) ; clearGlyphs ( _subtitles ) ; updateHistBar ( _history . size ( ) - 1 ) ; figureCurrentHistory ( ) ; } else if ( ! historyEnabled && _historyModel != null ) { _historyModel . removeChangeListener ( this ) ; _historyModel = null ; clearGlyphs ( _showingHistory ) ; } }
Configures us for display of chat history or not .
14,953
protected void viewDidScroll ( List < ? extends ChatGlyph > glyphs , int dx , int dy ) { for ( ChatGlyph glyph : glyphs ) { glyph . viewDidScroll ( dx , dy ) ; } }
Helper function for informing glyphs of the scrolled view .
14,954
protected void updateHistBar ( int val ) { if ( ! _histOffsetFinal && _history . size ( ) > _histOffset ) { Graphics2D gfx = getTargetGraphics ( ) ; if ( gfx != null ) { figureHistoryOffset ( gfx ) ; gfx . dispose ( ) ; } } int oldval = Math . max ( _histOffset , val ) ; int newmaxval = Math . max ( 0 , _history . size ( ) - 1 ) ; int newval = ( oldval >= newmaxval - 1 ) ? newmaxval : oldval ; _settingBar = true ; _historyModel . setRangeProperties ( newval , _historyExtent , _histOffset , newmaxval + _historyExtent , _historyModel . getValueIsAdjusting ( ) ) ; _settingBar = false ; }
Update the history scrollbar with the specified value .
14,955
protected void figureHistoryOffset ( Graphics2D gfx ) { if ( ! isLaidOut ( ) ) { return ; } int hei = _subtitleYSpacing ; int hsize = _history . size ( ) ; for ( int ii = 0 ; ii < hsize ; ii ++ ) { ChatGlyph rec = getHistorySubtitle ( ii , gfx ) ; Rectangle r = rec . getBounds ( ) ; hei += r . height ; if ( hei >= _subtitleHeight ) { _histOffset = Math . max ( 0 , ii - 1 ) ; _histOffsetFinal = true ; return ; } hei += getHistorySubtitleSpacing ( ii ) ; } _histOffset = hsize - 1 ; }
Figure out how many of the first history elements fit in our bounds such that we can set the bounds on the scrollbar correctly such that the scrolling to the smallest value just barely puts the first element onscreen .
14,956
protected void figureCurrentHistory ( ) { int first = _historyModel . getValue ( ) ; int count = 0 ; Graphics2D gfx = null ; if ( isLaidOut ( ) && ! _history . isEmpty ( ) ) { gfx = getTargetGraphics ( ) ; if ( gfx == null ) { log . warning ( "Can't figure current history, no graphics." ) ; return ; } Rectangle vbounds = _target . getViewBounds ( ) ; int ypos = vbounds . height - _subtitleYSpacing ; for ( int ii = first ; ii >= 0 ; ii -- , count ++ ) { ChatGlyph rec = getHistorySubtitle ( ii , gfx ) ; Rectangle r = rec . getBounds ( ) ; ypos -= r . height ; if ( ( count != 0 ) && ypos <= ( vbounds . height - _subtitleHeight ) ) { break ; } rec . setLocation ( vbounds . x + _subtitleXSpacing , vbounds . y + ypos ) ; ypos -= getHistorySubtitleSpacing ( ii ) ; } } for ( Iterator < ChatGlyph > itr = _showingHistory . iterator ( ) ; itr . hasNext ( ) ; ) { ChatGlyph cg = itr . next ( ) ; boolean managed = ( _target != null ) && _target . isManaged ( cg ) ; if ( cg . histIndex <= first && cg . histIndex > ( first - count ) ) { if ( ! managed ) { _target . addAnimation ( cg ) ; } } else { if ( managed ) { _target . abortAnimation ( cg ) ; } itr . remove ( ) ; } } if ( gfx != null ) { gfx . dispose ( ) ; } }
Figure out which ChatMessages in the history should currently appear in the showing history .
14,957
protected ChatGlyph getHistorySubtitle ( int index , Graphics2D layoutGfx ) { for ( int ii = 0 , nn = _showingHistory . size ( ) ; ii < nn ; ii ++ ) { ChatGlyph cg = _showingHistory . get ( ii ) ; if ( cg . histIndex == index ) { return cg ; } } ChatGlyph cg = createHistorySubtitle ( index , layoutGfx ) ; cg . histIndex = index ; cg . setDim ( _dimmed ) ; _showingHistory . add ( cg ) ; return cg ; }
Get the glyph for the specified history index creating if necessary .
14,958
protected ChatGlyph createHistorySubtitle ( int index , Graphics2D layoutGfx ) { ChatMessage message = _history . get ( index ) ; int type = getType ( message , true ) ; return createSubtitle ( message , type , layoutGfx , false ) ; }
Creates a subtitle for display in the history panel .
14,959
protected int getHistorySubtitleSpacing ( int index ) { ChatMessage message = _history . get ( index ) ; return _logic . getSubtitleSpacing ( getType ( message , true ) ) ; }
Determines the amount of spacing to put after a history subtitle .
14,960
protected void clearGlyphs ( List < ChatGlyph > glyphs ) { if ( _target != null ) { for ( int ii = 0 , nn = glyphs . size ( ) ; ii < nn ; ii ++ ) { ChatGlyph rec = glyphs . get ( ii ) ; _target . abortAnimation ( rec ) ; } } else if ( ! glyphs . isEmpty ( ) ) { log . warning ( "No target to abort chat animations" ) ; } glyphs . clear ( ) ; }
Clears out the supplied list of chat glyphs .
14,961
protected void displayMessage ( ChatMessage message , Graphics2D gfx ) { int type = getType ( message , false ) ; if ( type != ChatLogic . IGNORECHAT ) { displayMessage ( message , type , gfx ) ; } }
Display the specified message now unless we are to ignore it .
14,962
protected void displayMessage ( ChatMessage message , int type , Graphics2D layoutGfx ) { if ( isHistoryMode ( ) ) { return ; } addSubtitle ( createSubtitle ( message , type , layoutGfx , true ) ) ; }
Display the message after we ve decided which type it is .
14,963
protected void addSubtitle ( ChatGlyph rec ) { Rectangle r = rec . getBounds ( ) ; scrollUpSubtitles ( - r . height - _logic . getSubtitleSpacing ( rec . getType ( ) ) ) ; Rectangle vbounds = _target . getViewBounds ( ) ; rec . setLocation ( vbounds . x + _subtitleXSpacing , vbounds . y + vbounds . height - _subtitleYSpacing - r . height ) ; rec . setDim ( _dimmed ) ; _subtitles . add ( rec ) ; _target . addAnimation ( rec ) ; }
Add a subtitle for display now .
14,964
protected ChatGlyph createSubtitle ( ChatMessage message , int type , Graphics2D layoutGfx , boolean expires ) { String text = message . message ; Tuple < String , Boolean > finfo = _logic . decodeFormat ( type , message . getFormat ( ) ) ; String format = finfo . left ; boolean quotes = finfo . right ; if ( format != null ) { if ( quotes ) { text = "\"" + text + "\"" ; } text = " " + text ; text = xlate ( MessageBundle . tcompose ( format , ( ( UserMessage ) message ) . getSpeakerDisplayName ( ) ) ) + text ; } return createSubtitle ( layoutGfx , type , message . timestamp , null , 0 , text , expires ) ; }
Create a subtitle but don t do anything funny with it .
14,965
protected ChatGlyph createSubtitle ( Graphics2D gfx , int type , long timestamp , Icon icon , int indent , String text , boolean expires ) { Dimension is = new Dimension ( ) ; if ( icon != null ) { is . setSize ( icon . getIconWidth ( ) , icon . getIconHeight ( ) ) ; } Rectangle vbounds = _target . getViewBounds ( ) ; Label label = _logic . createLabel ( text ) ; label . setFont ( _logic . getFont ( type ) ) ; int paddedIconWidth = ( icon == null ) ? 0 : is . width + ICON_PADDING ; label . setTargetWidth ( vbounds . width - indent - paddedIconWidth - 2 * ( _subtitleXSpacing + Math . max ( UIManager . getInt ( "ScrollBar.width" ) , PAD ) ) ) ; label . layout ( gfx ) ; gfx . dispose ( ) ; Dimension ls = label . getSize ( ) ; Rectangle r = new Rectangle ( 0 , 0 , ls . width + indent + paddedIconWidth , Math . max ( is . height , ls . height ) ) ; r . grow ( 0 , 1 ) ; Point iconpos = r . getLocation ( ) ; iconpos . translate ( indent , r . height - is . height - 1 ) ; Point labelpos = r . getLocation ( ) ; labelpos . translate ( indent + paddedIconWidth , 1 ) ; Rectangle lr = new Rectangle ( r . x + indent + paddedIconWidth , r . y , r . width - indent - paddedIconWidth , ls . height + 2 ) ; long lifetime = Integer . MAX_VALUE ; if ( expires ) { lifetime = getChatExpire ( timestamp , label . getText ( ) ) - timestamp ; } Shape shape = _logic . getSubtitleShape ( type , lr , r ) ; return new ChatGlyph ( this , type , lifetime , r . union ( shape . getBounds ( ) ) , shape , icon , iconpos , label , labelpos , _logic . getOutlineColor ( type ) ) ; }
Create a subtitle - a line of text that goes on the bottom .
14,966
protected long getChatExpire ( long timestamp , String text ) { long [ ] durations = _logic . getDisplayDurations ( getDisplayDurationOffset ( ) ) ; long start = Math . max ( timestamp , _lastExpire ) ; _lastExpire = start + Math . min ( text . length ( ) * durations [ 0 ] , durations [ 2 ] ) ; _lastExpire = Math . min ( timestamp + durations [ 2 ] , _lastExpire ) ; return Math . max ( timestamp + durations [ 1 ] , _lastExpire ) ; }
Get the expire time for the specified chat .
14,967
protected void scrollUpSubtitles ( int dy ) { Rectangle vbounds = _target . getViewBounds ( ) ; int miny = vbounds . y + vbounds . height - _subtitleHeight ; for ( Iterator < ChatGlyph > iter = _subtitles . iterator ( ) ; iter . hasNext ( ) ; ) { ChatGlyph sub = iter . next ( ) ; sub . translate ( 0 , dy ) ; if ( sub . getBounds ( ) . y <= miny ) { iter . remove ( ) ; _target . abortAnimation ( sub ) ; } } }
Scroll all the subtitles up by the specified amount .
14,968
private static ParsedLine extractCommandArguments ( final ParsedLine line ) { LinkedList < String > words = Lists . newLinkedList ( line . words ( ) ) ; String remove = words . pop ( ) ; String rawLine = line . line ( ) ; if ( remove . length ( ) > rawLine . length ( ) ) { return new DefaultParser . ArgumentList ( rawLine . substring ( remove . length ( ) + 1 , rawLine . length ( ) ) , words , line . wordIndex ( ) - 1 , line . wordCursor ( ) , line . cursor ( ) - remove . length ( ) + 1 ) ; } else { return new DefaultParser . ArgumentList ( "" , Collections . emptyList ( ) , 0 , 0 , 0 ) ; } }
Extract the command specific portions of the given line .
14,969
protected void convert ( ) { if ( _image == null ) { return ; } try { BufferedImage image ; if ( _tabs . getSelectedIndex ( ) == 0 ) { image = getAllRecolors ( _labelColors . isSelected ( ) ) ; if ( image == null ) { return ; } } else if ( _tabs . getSelectedIndex ( ) == 1 ) { ArrayList < Colorization > zations = Lists . newArrayList ( ) ; if ( _classList1 . getSelectedItem ( ) != NONE ) { zations . add ( _colRepo . getColorization ( ( String ) _classList1 . getSelectedItem ( ) , ( String ) _colorList1 . getSelectedItem ( ) ) ) ; } if ( _classList2 . getSelectedItem ( ) != NONE ) { zations . add ( _colRepo . getColorization ( ( String ) _classList2 . getSelectedItem ( ) , ( String ) _colorList2 . getSelectedItem ( ) ) ) ; } if ( _classList3 . getSelectedItem ( ) != NONE ) { zations . add ( _colRepo . getColorization ( ( String ) _classList3 . getSelectedItem ( ) , ( String ) _colorList3 . getSelectedItem ( ) ) ) ; } if ( _classList4 . getSelectedItem ( ) != NONE ) { zations . add ( _colRepo . getColorization ( ( String ) _classList4 . getSelectedItem ( ) , ( String ) _colorList4 . getSelectedItem ( ) ) ) ; } image = ImageUtil . recolorImage ( _image , zations . toArray ( new Colorization [ zations . size ( ) ] ) ) ; } else { int color = Integer . parseInt ( _source . getText ( ) , 16 ) ; float hueD = _hueD . getValue ( ) ; float satD = _saturationD . getValue ( ) ; float valD = _valueD . getValue ( ) ; float [ ] dists = new float [ ] { hueD , satD , valD } ; float hueO = _hueO . getValue ( ) ; float satO = _saturationO . getValue ( ) ; float valO = _valueO . getValue ( ) ; float [ ] offsets = new float [ ] { hueO , satO , valO } ; image = ImageUtil . recolorImage ( _image , new Color ( color ) , dists , offsets ) ; } _newImage . setIcon ( new ImageIcon ( image ) ) ; _status . setText ( "Recolored image." ) ; repaint ( ) ; } catch ( NumberFormatException nfe ) { _status . setText ( "Invalid value: " + nfe . getMessage ( ) ) ; } }
Performs colorizations .
14,970
public BufferedImage getAllRecolors ( boolean label ) { if ( _colRepo == null ) { return null ; } ColorPository . ClassRecord colClass = _colRepo . getClassRecord ( ( String ) _classList . getSelectedItem ( ) ) ; int classId = colClass . classId ; BufferedImage img = new BufferedImage ( _image . getWidth ( ) , _image . getHeight ( ) * colClass . colors . size ( ) , BufferedImage . TYPE_INT_ARGB ) ; Graphics gfx = img . getGraphics ( ) ; gfx . setColor ( Color . BLACK ) ; int y = 0 ; Integer [ ] sortedKeys = colClass . colors . keySet ( ) . toArray ( new Integer [ colClass . colors . size ( ) ] ) ; Arrays . sort ( sortedKeys ) ; for ( int key : sortedKeys ) { Colorization coloriz = _colRepo . getColorization ( classId , key ) ; BufferedImage subImg = ImageUtil . recolorImage ( _image , coloriz . rootColor , coloriz . range , coloriz . offsets ) ; gfx . drawImage ( subImg , 0 , y , null , null ) ; if ( label ) { ColorRecord crec = _colRepo . getColorRecord ( classId , key ) ; gfx . drawString ( crec . name , 2 , y + gfx . getFontMetrics ( ) . getHeight ( ) + 2 ) ; gfx . drawRect ( 0 , y , _image . getWidth ( ) - 1 , _image . getHeight ( ) ) ; } y += subImg . getHeight ( ) ; } return img ; }
Gets an image with all recolorings of the selection colorization class .
14,971
public void setColorizeFile ( File path ) { try { if ( path . getName ( ) . endsWith ( "xml" ) ) { ColorPositoryParser parser = new ColorPositoryParser ( ) ; _colRepo = ( ColorPository ) ( parser . parseConfig ( path ) ) ; } else { _colRepo = ColorPository . loadColorPository ( new FileInputStream ( path ) ) ; } _classList . removeAllItems ( ) ; _classList1 . removeAllItems ( ) ; _classList1 . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent event ) { setupColors ( _colorList1 , ( String ) _classList1 . getSelectedItem ( ) ) ; } } ) ; _classList2 . removeAllItems ( ) ; _classList2 . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent event ) { setupColors ( _colorList2 , ( String ) _classList2 . getSelectedItem ( ) ) ; } } ) ; _classList3 . removeAllItems ( ) ; _classList3 . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent event ) { setupColors ( _colorList3 , ( String ) _classList3 . getSelectedItem ( ) ) ; } } ) ; _classList4 . removeAllItems ( ) ; _classList4 . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent event ) { setupColors ( _colorList4 , ( String ) _classList4 . getSelectedItem ( ) ) ; } } ) ; Iterator < ColorPository . ClassRecord > iter = _colRepo . enumerateClasses ( ) ; ArrayList < String > names = Lists . newArrayList ( ) ; while ( iter . hasNext ( ) ) { String str = iter . next ( ) . name ; names . add ( str ) ; } _classList1 . addItem ( NONE ) ; _classList2 . addItem ( NONE ) ; _classList3 . addItem ( NONE ) ; _classList4 . addItem ( NONE ) ; Collections . sort ( names ) ; for ( String name : names ) { _classList . addItem ( name ) ; _classList1 . addItem ( name ) ; _classList2 . addItem ( name ) ; _classList3 . addItem ( name ) ; _classList4 . addItem ( name ) ; } _classList . setSelectedIndex ( 0 ) ; _classList1 . setSelectedIndex ( 0 ) ; _classList2 . setSelectedIndex ( 0 ) ; _classList3 . setSelectedIndex ( 0 ) ; _classList4 . setSelectedIndex ( 0 ) ; _colFilePath . setText ( path . getPath ( ) ) ; CONFIG . setValue ( LAST_COLORIZATION_KEY , path . getAbsolutePath ( ) ) ; } catch ( Exception ex ) { _status . setText ( "Error opening colorization file: " + ex ) ; } }
Loads up the colorization classes from the specified file .
14,972
public static String stripControlCharacters ( String rawValue ) { if ( rawValue == null ) { return null ; } String value = replaceEntities ( rawValue ) ; boolean hasControlChars = false ; for ( int i = value . length ( ) - 1 ; i >= 0 ; i -- ) { if ( Character . isISOControl ( value . charAt ( i ) ) ) { hasControlChars = true ; break ; } } if ( ! hasControlChars ) { return value ; } StringBuilder buf = new StringBuilder ( value . length ( ) ) ; int i = 0 ; for ( ; i < value . length ( ) ; i ++ ) { if ( ! Character . isISOControl ( value . charAt ( i ) ) ) { break ; } } boolean suppressingControlChars = false ; for ( ; i < value . length ( ) ; i ++ ) { if ( Character . isISOControl ( value . charAt ( i ) ) ) { suppressingControlChars = true ; continue ; } else { if ( suppressingControlChars ) { suppressingControlChars = false ; buf . append ( ' ' ) ; } buf . append ( value . charAt ( i ) ) ; } } return buf . toString ( ) ; }
Strip a String of it s ISO control characters .
14,973
public static void write ( BufferedImage image , OutputStream out ) throws IOException { DataOutputStream dout = new DataOutputStream ( out ) ; int width = image . getWidth ( ) , height = image . getHeight ( ) ; dout . writeInt ( width ) ; dout . writeInt ( height ) ; IndexColorModel cmodel = ( IndexColorModel ) image . getColorModel ( ) ; int tpixel = cmodel . getTransparentPixel ( ) ; dout . writeInt ( tpixel ) ; int msize = cmodel . getMapSize ( ) ; int [ ] map = new int [ msize ] ; cmodel . getRGBs ( map ) ; dout . writeInt ( msize ) ; for ( int element : map ) { dout . writeInt ( element ) ; } DataBufferByte dbuf = ( DataBufferByte ) image . getRaster ( ) . getDataBuffer ( ) ; byte [ ] data = dbuf . getData ( ) ; if ( data . length != width * height ) { String errmsg = "Raster data not same size as image! [" + width + "x" + height + " != " + data . length + "]" ; throw new IllegalStateException ( errmsg ) ; } dout . write ( data ) ; dout . flush ( ) ; }
Writes the supplied image to the supplied output stream .
14,974
public List < AmqpTableEntry > getEntries ( String key ) { if ( ( key == null ) || ( tableEntryArray == null ) ) { return null ; } List < AmqpTableEntry > entries = new ArrayList < AmqpTableEntry > ( ) ; for ( AmqpTableEntry entry : tableEntryArray ) { if ( entry . key . equals ( key ) ) { entries . add ( entry ) ; } } return entries ; }
Returns a list of AmqpTableEntry objects that matches the specified key . If a null key is passed in then a null is returned . Also if the internal structure is null then a null is returned .
14,975
public void update ( long numProcessedDuringStep ) { if ( this . closed ) { throw new ETAPrinterException ( "You cannot update a closed ETAPrinter!" ) ; } DateTime now = DateTime . now ( ) ; ItemsDuration itemsDuration = null ; if ( numProcessedDuringStep > 0 ) { long stepDuration = new Duration ( this . lastStep , now ) . getMillis ( ) ; int numItems = 1 ; do { long duration = stepDuration / ( numProcessedDuringStep / numItems ) ; itemsDuration = new ItemsDuration ( numItems , duration ) ; numItems ++ ; } while ( itemsDuration . durationMillis == 0 ) ; } this . lastStep = now ; this . numProcessed += numProcessedDuringStep ; if ( this . numProcessed == this . totalElementsToProcess ) { this . close ( ) ; } else { this . print ( itemsDuration ) ; } }
Updates and prints the progress bar with the new values .
14,976
public static TagAttributeInfo getIdAttribute ( TagAttributeInfo a [ ] ) { for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] . getName ( ) . equals ( ID ) ) { return a [ i ] ; } } return null ; }
Convenience static method that goes through an array of TagAttributeInfo objects and looks for id .
14,977
protected static < T > Class < T > firstKnownType ( T ... objects ) { for ( T obj : objects ) if ( obj != null ) return ( Class < T > ) obj . getClass ( ) ; return null ; }
Utility method to allow subclasses to extract type from known variables .
14,978
public ColorRecord [ ] enumerateColors ( String className ) { ClassRecord record = getClassRecord ( className ) ; if ( record == null ) { return null ; } ColorRecord [ ] crecs = new ColorRecord [ record . colors . size ( ) ] ; Iterator < ColorRecord > iter = record . colors . values ( ) . iterator ( ) ; for ( int ii = 0 ; iter . hasNext ( ) ; ii ++ ) { crecs [ ii ] = iter . next ( ) ; } return crecs ; }
Returns an array containing the records for the colors in the specified class .
14,979
public int [ ] enumerateColorIds ( String className ) { ClassRecord record = getClassRecord ( className ) ; if ( record == null ) { return null ; } int [ ] cids = new int [ record . colors . size ( ) ] ; Iterator < ColorRecord > crecs = record . colors . values ( ) . iterator ( ) ; for ( int ii = 0 ; crecs . hasNext ( ) ; ii ++ ) { cids [ ii ] = crecs . next ( ) . colorId ; } return cids ; }
Returns an array containing the ids of the colors in the specified class .
14,980
public ColorRecord getRandomStartingColor ( String className , Random rand ) { ClassRecord record = getClassRecord ( className ) ; return ( record == null ) ? null : record . randomStartingColor ( rand ) ; }
Returns a random starting color from the specified color class .
14,981
public Colorization getColorization ( int classId , int colorId ) { ColorRecord color = getColorRecord ( classId , colorId ) ; return ( color == null ) ? null : color . getColorization ( ) ; }
Looks up a colorization by id .
14,982
public Colorization getColorization ( String className , int colorId ) { ClassRecord crec = getClassRecord ( className ) ; if ( crec != null ) { ColorRecord color = crec . colors . get ( colorId ) ; if ( color != null ) { return color . getColorization ( ) ; } } return null ; }
Looks up a colorization by name .
14,983
public Colorization getColorization ( String className , String colorName ) { ClassRecord crec = getClassRecord ( className ) ; if ( crec != null ) { int colorId = 0 ; try { colorId = crec . getColorId ( colorName ) ; } catch ( ParseException pe ) { log . info ( "Error getting colorization by name" , "error" , pe ) ; return null ; } ColorRecord color = crec . colors . get ( colorId ) ; if ( color != null ) { return color . getColorization ( ) ; } } return null ; }
Looks up a colorization by class and color names .
14,984
public ClassRecord getClassRecord ( String className ) { Iterator < ClassRecord > iter = _classes . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { ClassRecord crec = iter . next ( ) ; if ( crec . name . equals ( className ) ) { return crec ; } } log . warning ( "No such color class" , "class" , className , new Exception ( ) ) ; return null ; }
Loads up a colorization class by name and logs a warning if it doesn t exist .
14,985
public ColorRecord getColorRecord ( int classId , int colorId ) { ClassRecord record = getClassRecord ( classId ) ; if ( record == null ) { if ( classId != 0 ) { log . warning ( "Requested unknown color class" , "classId" , classId , "colorId" , colorId , new Exception ( ) ) ; } return null ; } return record . colors . get ( colorId ) ; }
Looks up the requested color record .
14,986
public ColorRecord getColorRecord ( String className , String colorName ) { ClassRecord record = getClassRecord ( className ) ; if ( record == null ) { log . warning ( "Requested unknown color class" , "className" , className , "colorName" , colorName , new Exception ( ) ) ; return null ; } int colorId = 0 ; try { colorId = record . getColorId ( colorName ) ; } catch ( ParseException pe ) { log . info ( "Error getting color record by name" , "error" , pe ) ; return null ; } return record . colors . get ( colorId ) ; }
Looks up the requested color record by class and color names .
14,987
public void addClass ( ClassRecord record ) { if ( record . classId > 255 ) { log . warning ( "Refusing to add class; classId > 255 " + record + "." ) ; } else { _classes . put ( record . classId , record ) ; } }
Adds a fully configured color class record to the pository . This is only called by the XML parsing code so pay it no mind .
14,988
public static void saveColorPository ( ColorPository posit , File root ) { File path = new File ( root , CONFIG_PATH ) ; try { CompiledConfig . saveConfig ( path , posit ) ; } catch ( IOException ioe ) { log . warning ( "Failure saving color pository" , "path" , path , "error" , ioe ) ; } }
Serializes and saves color pository to the supplied file .
14,989
public void init ( CharacterDescriptor descrip , CharacterManager charmgr ) { _descrip = descrip ; _charmgr = charmgr ; sanityCheckDescrip ( ) ; _orient = SOUTHWEST ; didInit ( ) ; }
Initializes this character sprite with the specified character descriptor and character manager . It will obtain animation data from the supplied character manager .
14,990
public void setActionSequence ( String action ) { if ( action == null ) { log . warning ( "Refusing to set null action sequence " + this + "." , new Exception ( ) ) ; return ; } if ( action . equals ( _action ) ) { return ; } _action = action ; updateActionFrames ( ) ; }
Sets the action sequence used when rendering the character from the set of available sequences .
14,991
protected void updateActionFrames ( ) { ActionSequence actseq = _charmgr . getActionSequence ( _action ) ; if ( actseq == null ) { String errmsg = "No such action '" + _action + "'." ; throw new IllegalArgumentException ( errmsg ) ; } try { _aframes = _charmgr . getActionFrames ( _descrip , _action ) ; _frames = null ; setFrameRate ( actseq . framesPerSecond ) ; } catch ( NoSuchComponentException nsce ) { log . warning ( "Character sprite references non-existent component" , "sprite" , this , "err" , nsce ) ; } catch ( Exception e ) { log . warning ( "Failed to obtain action frames" , "sprite" , this , "descrip" , _descrip , "action" , _action , e ) ; } }
Rebuilds our action frames given our current character descriptor and action sequence . This is called when either of those two things changes .
14,992
protected void sanityCheckDescrip ( ) { if ( _descrip . getComponentIds ( ) == null || _descrip . getComponentIds ( ) . length == 0 ) { log . warning ( "Invalid character descriptor [sprite=" + this + ", descrip=" + _descrip + "]." , new Exception ( ) ) ; } }
Makes it easier to track down problems with bogus character descriptors .
14,993
protected void halt ( ) { if ( _animMode != NO_ANIMATION ) { setAnimationMode ( NO_ANIMATION ) ; String rest = getRestingAction ( ) ; if ( rest != null ) { setActionSequence ( rest ) ; } } }
Updates the sprite animation frame to reflect the cessation of movement and disables any further animation .
14,994
public static void unmask ( WrappedByteBuffer buf , int mask ) { byte b ; int remainder = buf . remaining ( ) % 4 ; int remaining = buf . remaining ( ) - remainder ; int end = remaining + buf . position ( ) ; while ( buf . position ( ) < end ) { int plaintext = buf . getIntAt ( buf . position ( ) ) ^ mask ; buf . putInt ( plaintext ) ; } switch ( remainder ) { case 3 : b = ( byte ) ( buf . getAt ( buf . position ( ) ) ^ ( ( mask >> 24 ) & 0xff ) ) ; buf . put ( b ) ; b = ( byte ) ( buf . getAt ( buf . position ( ) ) ^ ( ( mask >> 16 ) & 0xff ) ) ; buf . put ( b ) ; b = ( byte ) ( buf . getAt ( buf . position ( ) ) ^ ( ( mask >> 8 ) & 0xff ) ) ; buf . put ( b ) ; break ; case 2 : b = ( byte ) ( buf . getAt ( buf . position ( ) ) ^ ( ( mask >> 24 ) & 0xff ) ) ; buf . put ( b ) ; b = ( byte ) ( buf . getAt ( buf . position ( ) ) ^ ( ( mask >> 16 ) & 0xff ) ) ; buf . put ( b ) ; break ; case 1 : b = ( byte ) ( buf . getAt ( buf . position ( ) ) ^ ( mask >> 24 ) ) ; buf . put ( b ) ; break ; case 0 : default : break ; } }
Performs an in - situ unmasking of the readable buf bytes . Preserves the position of the buffer whilst unmasking all the readable bytes such that the unmasked bytes will be readable after this invocation .
14,995
private static stream_response newTscStream ( Stream < TimeSeriesCollection > tsc , int fetch ) { final BufferedIterator < TimeSeriesCollection > iter = new BufferedIterator ( tsc . iterator ( ) , TSC_QUEUE_SIZE ) ; final long idx = TSC_ITERS_ALLOC . getAndIncrement ( ) ; final IteratorAndCookie < TimeSeriesCollection > iterAndCookie = new IteratorAndCookie < > ( iter ) ; TSC_ITERS . put ( idx , iterAndCookie ) ; final List < TimeSeriesCollection > result = fetchFromIter ( iter , fetch , MAX_TSC_FETCH ) ; EncDec . NewIterResponse < TimeSeriesCollection > responseObj = new EncDec . NewIterResponse < > ( idx , result , iter . atEnd ( ) , iterAndCookie . getCookie ( ) ) ; LOG . log ( Level . FINE , "responseObj = {0}" , responseObj ) ; return EncDec . encodeStreamResponse ( responseObj ) ; }
Create a new TimeSeriesCollection iterator from the given stream .
14,996
private static evaluate_response newEvalStream ( Stream < Collection < CollectHistory . NamedEvaluation > > tsc , int fetch ) { final BufferedIterator < Collection < CollectHistory . NamedEvaluation > > iter = new BufferedIterator ( tsc . iterator ( ) , EVAL_QUEUE_SIZE ) ; final long idx = EVAL_ITERS_ALLOC . getAndIncrement ( ) ; final IteratorAndCookie < Collection < CollectHistory . NamedEvaluation > > iterAndCookie = new IteratorAndCookie < > ( iter ) ; EVAL_ITERS . put ( idx , iterAndCookie ) ; final List < Collection < CollectHistory . NamedEvaluation > > result = fetchFromIter ( iter , fetch , MAX_EVAL_FETCH ) ; EncDec . NewIterResponse < Collection < CollectHistory . NamedEvaluation > > responseObj = new EncDec . NewIterResponse < > ( idx , result , iter . atEnd ( ) , iterAndCookie . getCookie ( ) ) ; LOG . log ( Level . FINE , "responseObj = {0}" , responseObj ) ; return EncDec . encodeEvaluateResponse ( responseObj ) ; }
Create a new evaluation iterator from the given stream .
14,997
private static group_stream_response newGroupStream ( Stream < Map . Entry < DateTime , TimeSeriesValue > > tsc , int fetch ) { final BufferedIterator < Map . Entry < DateTime , TimeSeriesValue > > iter = new BufferedIterator < > ( tsc . iterator ( ) , GROUP_STREAM_QUEUE_SIZE ) ; final long idx = GROUP_STREAM_ITERS_ALLOC . getAndIncrement ( ) ; final IteratorAndCookie < Map . Entry < DateTime , TimeSeriesValue > > iterAndCookie = new IteratorAndCookie < > ( iter ) ; GROUP_STREAM_ITERS . put ( idx , iterAndCookie ) ; final List < Map . Entry < DateTime , TimeSeriesValue > > result = fetchFromIter ( iter , fetch , MAX_GROUP_STREAM_FETCH ) ; EncDec . NewIterResponse < Map . Entry < DateTime , TimeSeriesValue > > responseObj = new EncDec . NewIterResponse < > ( idx , result , iter . atEnd ( ) , iterAndCookie . getCookie ( ) ) ; LOG . log ( Level . FINE , "responseObj = {0}" , responseObj ) ; return EncDec . encodeStreamGroupResponse ( responseObj ) ; }
Create a new group iterator from the given stream .
14,998
private static < T > List < T > fetchFromIter ( BufferedIterator < T > iter , int fetch , int max_fetch ) { final long t0 = System . currentTimeMillis ( ) ; assert ( max_fetch >= 1 ) ; if ( fetch < 0 || fetch > max_fetch ) fetch = max_fetch ; final List < T > result = new ArrayList < > ( fetch ) ; for ( int i = 0 ; i < fetch && ! iter . atEnd ( ) ; ++ i ) { if ( iter . nextAvail ( ) ) result . add ( iter . next ( ) ) ; final long tCur = System . currentTimeMillis ( ) ; if ( ! result . isEmpty ( ) && tCur - t0 >= MIN_REQUEST_DURATION . getMillis ( ) ) break ; else if ( tCur - t0 >= MAX_REQUEST_DURATION . getMillis ( ) ) break ; else if ( ! iter . nextAvail ( ) ) { try { iter . waitAvail ( ( t0 + MAX_REQUEST_DURATION . getMillis ( ) - tCur ) , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException ex ) { } } } return result ; }
Fetch up to a given amount of items from the iterator .
14,999
public static Object loadObject ( ResourceBundle bundle , String path , boolean wipeOnFailure ) throws IOException , ClassNotFoundException { InputStream bin = null ; try { bin = bundle . getResource ( path ) ; if ( bin == null ) { return null ; } return new ObjectInputStream ( bin ) . readObject ( ) ; } catch ( InvalidClassException ice ) { log . warning ( "Aiya! Serialized object is hosed [bundle=" + bundle + ", element=" + path + ", error=" + ice . getMessage ( ) + "]." ) ; return null ; } catch ( IOException ioe ) { log . warning ( "Error reading resource from bundle [bundle=" + bundle + ", path=" + path + ", wiping?=" + wipeOnFailure + "]." ) ; if ( wipeOnFailure ) { StreamUtil . close ( bin ) ; bin = null ; if ( bundle instanceof FileResourceBundle ) { ( ( FileResourceBundle ) bundle ) . wipeBundle ( false ) ; } } throw ioe ; } finally { StreamUtil . close ( bin ) ; } }
Attempts to load an object from the supplied resource bundle with the specified path .