idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
156,100
private Rectangle2D getBounds ( ServletRequest pReq , BufferedImage pImage , double pAng ) { // Get dimensions of original image int width = pImage . getWidth ( ) ; // loads the image int height = pImage . getHeight ( ) ; // Test if we want to crop image (default) // if true // - find the largest bounding box INSIDE th...
Get the bounding rectangle of the rotated image .
263
10
156,101
void initIRGB ( int [ ] pTemp ) { final int x = ( 1 << TRUNCBITS ) ; // 8 the size of 1 Dimension of each quantized cell final int xsqr = 1 << ( TRUNCBITS * 2 ) ; // 64 - twice the smallest step size vale of quantized colors final int xsqr2 = xsqr + xsqr ; for ( int i = 0 ; i < numColors ; ++ i ) { if ( i == transparen...
Simple inverse color table creation method .
608
7
156,102
public static Class unwrapType ( Class pType ) { if ( pType == Boolean . class ) { return Boolean . TYPE ; } else if ( pType == Byte . class ) { return Byte . TYPE ; } else if ( pType == Character . class ) { return Character . TYPE ; } else if ( pType == Double . class ) { return Double . TYPE ; } else if ( pType == F...
Returns the primitive type for the given wrapper type .
167
10
156,103
private static boolean canRead ( final DataInput pInput , final boolean pReset ) { long pos = FREE_SID ; if ( pReset ) { try { if ( pInput instanceof InputStream && ( ( InputStream ) pInput ) . markSupported ( ) ) { ( ( InputStream ) pInput ) . mark ( 8 ) ; } else if ( pInput instanceof ImageInputStream ) { ( ( ImageIn...
It s probably safer to create one version for InputStream and one for File
420
15
156,104
private SIdChain getSIdChain ( final int pSId , final long pStreamSize ) throws IOException { SIdChain chain = new SIdChain ( ) ; int [ ] sat = isShortStream ( pStreamSize ) ? shortSAT : SAT ; int sid = pSId ; while ( sid != END_OF_CHAIN_SID && sid != FREE_SID ) { chain . addSID ( sid ) ; sid = sat [ sid ] ; } return c...
Gets the SIdChain for the given stream Id
107
11
156,105
private void seekToSId ( final int pSId , final long pStreamSize ) throws IOException { long pos ; if ( isShortStream ( pStreamSize ) ) { // The short stream is not continuous... Entry root = getRootEntry ( ) ; if ( shortStreamSIdChain == null ) { shortStreamSIdChain = getSIdChain ( root . startSId , root . streamSize ...
Seeks to the start pos for the given stream Id
377
11
156,106
protected Object initPropertyValue ( String pValue , String pType , String pFormat ) throws ClassNotFoundException { // System.out.println("pValue=" + pValue + " pType=" + pType // + " pFormat=" + pFormat); // No value to convert if ( pValue == null ) { return null ; } // No conversion needed for Strings if ( ( pType =...
Initializes the value of a property .
459
8
156,107
private Object createInstance ( Class pClass , Object pParam ) { Object value ; try { // Create param and argument arrays Class [ ] param = { pParam . getClass ( ) } ; Object [ ] arg = { pParam } ; // Get constructor Constructor constructor = pClass . getDeclaredConstructor ( param ) ; // Invoke and create instance val...
Creates an object from the given class single argument constructor .
100
12
156,108
private Object invokeStaticMethod ( Class pClass , String pMethod , Object pParam ) { Object value = null ; try { // Create param and argument arrays Class [ ] param = { pParam . getClass ( ) } ; Object [ ] arg = { pParam } ; // Get method // *** If more than one such method is found in the class, and one // of these m...
Creates an object from any given static method given the parameter
227
12
156,109
public synchronized String setPropertyFormat ( String pKey , String pFormat ) { // Insert format return StringUtil . valueOf ( mFormats . put ( pKey , pFormat ) ) ; }
Sets the format of a property . This value is used for formatting the value before it is stored as xml .
42
23
156,110
private static void insertElement ( Document pDocument , String pName , Object pValue , String pFormat ) { // Get names of all elements we need String [ ] names = StringUtil . toStringArray ( pName , "." ) ; // Get value formatted as string String value = null ; if ( pValue != null ) { // --- if ( pValue instanceof Dat...
Inserts elements to the given document one by one and creates all its parents if needed .
797
18
156,111
public int doEndTag ( ) throws JspException { // Get body content (trim is CRUCIAL, as some XML parsers are picky...) String body = bodyContent . getString ( ) . trim ( ) ; // Do transformation transform ( new StreamSource ( new ByteArrayInputStream ( body . getBytes ( ) ) ) ) ; return super . doEndTag ( ) ; }
doEndTag implementation that will perform XML Transformation on the body content .
83
14
156,112
public void transform ( Source pIn ) throws JspException { try { // Create transformer Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( getSource ( mStylesheetURI ) ) ; // Store temporary output in a bytearray, as the transformer will // usually try to flush the stream (illegal operatio...
Performs the transformation and writes the result to the JSP writer .
240
14
156,113
private StreamSource getSource ( String pURI ) throws IOException , MalformedURLException { if ( pURI != null && pURI . indexOf ( "://" ) < 0 ) { // If local, get as stream return new StreamSource ( getResourceAsStream ( pURI ) ) ; } // ...else, create from URI string return new StreamSource ( pURI ) ; }
Returns a StreamSource object for the given URI
83
9
156,114
private static BufferedImage createSolid ( BufferedImage pOriginal , Color pBackground ) { // Create a temporary image of same dimension and type BufferedImage solid = new BufferedImage ( pOriginal . getColorModel ( ) , pOriginal . copyData ( null ) , pOriginal . isAlphaPremultiplied ( ) , null ) ; Graphics2D g = solid...
Creates a copy of the given image with a solid background
163
12
156,115
private static void applyAlpha ( BufferedImage pImage , BufferedImage pAlpha ) { // Apply alpha as transparency, using threshold of 25% for ( int y = 0 ; y < pAlpha . getHeight ( ) ; y ++ ) { for ( int x = 0 ; x < pAlpha . getWidth ( ) ; x ++ ) { // Get alpha component of pixel, if less than 25% opaque // (0x40 = 64 =>...
Applies the alpha - component of the alpha image to the given image . The given image is modified in place .
156
23
156,116
@ Override public byte [ ] toByteArray ( ) { byte newBuf [ ] = new byte [ count ] ; System . arraycopy ( buf , 0 , newBuf , 0 , count ) ; return newBuf ; }
Non - synchronized version of toByteArray
50
8
156,117
public void writeHeadersTo ( final CacheResponse pResponse ) { String [ ] headers = getHeaderNames ( ) ; for ( String header : headers ) { // HACK... // Strip away internal headers if ( HTTPCache . HEADER_CACHED_TIME . equals ( header ) ) { continue ; } // TODO: Replace Last-Modified with X-Cached-At? See CachedEntityI...
Writes the cached headers to the response
168
8
156,118
public void writeContentsTo ( final OutputStream pStream ) throws IOException { if ( content == null ) { throw new IOException ( "Cache is null, no content to write." ) ; } content . writeTo ( pStream ) ; }
Writes the cached content to the response
51
8
156,119
public String [ ] getHeaderNames ( ) { Set < String > headers = this . headers . keySet ( ) ; return headers . toArray ( new String [ headers . size ( ) ] ) ; }
Gets the header names of all headers set in this response .
43
13
156,120
public Path2D path ( ) throws IOException { List < List < AdobePathSegment >> subPaths = new ArrayList < List < AdobePathSegment > > ( ) ; List < AdobePathSegment > currentPath = null ; int currentPathLength = 0 ; AdobePathSegment segment ; while ( ( segment = nextSegment ( ) ) != null ) { if ( DEBUG ) { System . out ....
Builds the path .
530
5
156,121
private int getFontStyle ( String pStyle ) { if ( pStyle == null || StringUtil . containsIgnoreCase ( pStyle , FONT_STYLE_PLAIN ) ) { return Font . PLAIN ; } // Try to find bold/italic int style = Font . PLAIN ; if ( StringUtil . containsIgnoreCase ( pStyle , FONT_STYLE_BOLD ) ) { style |= Font . BOLD ; } if ( StringUt...
Returns the font style constant .
140
6
156,122
private double getAngle ( ServletRequest pRequest ) { // Get angle double angle = ServletUtil . getDoubleParameter ( pRequest , PARAM_TEXT_ROTATION , 0.0 ) ; // Convert to radians, if needed String units = pRequest . getParameter ( PARAM_TEXT_ROTATION_UNITS ) ; if ( ! StringUtil . isEmpty ( units ) && ROTATION_DEGREES ...
Gets the angle of rotation from the request .
122
10
156,123
public final String getName ( ) { switch ( type ) { case ServletConfig : return servletConfig . getServletName ( ) ; case FilterConfig : return filterConfig . getFilterName ( ) ; case ServletContext : return servletContext . getServletContextName ( ) ; default : throw new IllegalStateException ( ) ; } }
Gets the servlet or filter name from the config .
74
12
156,124
public final ServletContext getServletContext ( ) { switch ( type ) { case ServletConfig : return servletConfig . getServletContext ( ) ; case FilterConfig : return filterConfig . getServletContext ( ) ; case ServletContext : return servletContext ; default : throw new IllegalStateException ( ) ; } }
Gets the servlet context from the config .
71
10
156,125
protected int fill ( ) throws IOException { buffer . clear ( ) ; int read = decoder . decode ( in , buffer ) ; // TODO: Enforce this in test case, leave here to aid debugging if ( read > buffer . capacity ( ) ) { throw new AssertionError ( String . format ( "Decode beyond buffer (%d): %d (using %s decoder)" , buffer . ...
Fills the buffer by decoding data from the underlying input stream .
130
13
156,126
public void logDebug ( String message , Exception exception ) { if ( ! ( logDebug || globalLog . logDebug ) ) return ; if ( debugLog != null ) log ( debugLog , "DEBUG" , owner , message , exception ) ; else log ( globalLog . debugLog , "DEBUG" , owner , message , exception ) ; }
Prints debug info to the current debugLog
72
9
156,127
public void logWarning ( String message , Exception exception ) { if ( ! ( logWarning || globalLog . logWarning ) ) return ; if ( warningLog != null ) log ( warningLog , "WARNING" , owner , message , exception ) ; else log ( globalLog . warningLog , "WARNING" , owner , message , exception ) ; }
Prints warning info to the current warningLog
72
9
156,128
public void logError ( String message , Exception exception ) { if ( ! ( logError || globalLog . logError ) ) return ; if ( errorLog != null ) log ( errorLog , "ERROR" , owner , message , exception ) ; else log ( globalLog . errorLog , "ERROR" , owner , message , exception ) ; }
Prints error info to the current errorLog
72
9
156,129
public void logInfo ( String message , Exception exception ) { if ( ! ( logInfo || globalLog . logInfo ) ) return ; if ( infoLog != null ) log ( infoLog , "INFO" , owner , message , exception ) ; else log ( globalLog . infoLog , "INFO" , owner , message , exception ) ; }
Prints info info to the current infoLog
72
9
156,130
private static OutputStream getStream ( String name ) throws IOException { OutputStream os = null ; synchronized ( streamCache ) { if ( ( os = ( OutputStream ) streamCache . get ( name ) ) != null ) return os ; os = new FileOutputStream ( name , true ) ; streamCache . put ( name , os ) ; } return os ; }
Internal method to get a named stream
76
7
156,131
private static void log ( PrintStream ps , String header , String owner , String message , Exception ex ) { // Only allow one instance to print to the given stream. synchronized ( ps ) { // Create output stream for logging LogStream logStream = new LogStream ( ps ) ; logStream . time = new Date ( System . currentTimeMi...
Internal log method
137
3
156,132
public final Point getHotSpot ( final int pImageIndex ) throws IOException { DirectoryEntry . CUREntry entry = ( DirectoryEntry . CUREntry ) getEntry ( pImageIndex ) ; return entry . getHotspot ( ) ; }
Returns the hot spot location for the cursor .
54
9
156,133
public Object toObject ( String pString , Class pType , String pFormat ) throws ConversionException { if ( StringUtil . isEmpty ( pString ) ) return null ; TimeFormat format ; try { if ( pFormat == null ) { // Use system default format format = TimeFormat . getInstance ( ) ; } else { // Get format from cache format = g...
Converts the string to a time using the given format for parsing .
114
14
156,134
static Entry readEntry ( final DataInput pInput ) throws IOException { Entry p = new Entry ( ) ; p . read ( pInput ) ; return p ; }
Reads an entry from the input .
35
8
156,135
private void read ( final DataInput pInput ) throws IOException { byte [ ] bytes = new byte [ 64 ] ; pInput . readFully ( bytes ) ; // NOTE: Length is in bytes, including the null-terminator... int nameLength = pInput . readShort ( ) ; name = new String ( bytes , 0 , nameLength - 2 , Charset . forName ( "UTF-16LE" ) ) ...
Reads this entry
394
4
156,136
public static Path2D readPath ( final ImageInputStream stream ) throws IOException { notNull ( stream , "stream" ) ; int magic = readMagic ( stream ) ; if ( magic == PSD . RESOURCE_TYPE ) { // This is a PSD Image Resource Block, we can parse directly return buildPathFromPhotoshopResources ( stream ) ; } else if ( magic...
Reads the clipping path from the given input stream if any . Supports PSD JPEG and TIFF as container formats for Photoshop resources or a bare PSD Image Resource Block .
567
35
156,137
public static BufferedImage applyClippingPath ( final Shape clip , final BufferedImage image ) { return applyClippingPath ( clip , notNull ( image , "image" ) , new BufferedImage ( image . getWidth ( ) , image . getHeight ( ) , BufferedImage . TYPE_INT_ARGB ) ) ; }
Applies the clipping path to the given image . All pixels outside the path will be transparent .
72
19
156,138
public static BufferedImage readClipped ( final ImageInputStream stream ) throws IOException { Shape clip = readPath ( stream ) ; stream . seek ( 0 ) ; BufferedImage image = ImageIO . read ( stream ) ; if ( clip == null ) { return image ; } return applyClippingPath ( clip , image ) ; }
Reads the clipping path from the given input stream if any and applies it to the first image in the stream . If no path was found the image is returned without any clipping . Supports PSD JPEG and TIFF as container formats for Photoshop resources .
71
50
156,139
protected void service ( HttpServletRequest pRequest , HttpServletResponse pResponse ) throws ServletException , IOException { // Sanity check configuration if ( remoteServer == null ) { log ( MESSAGE_REMOTE_SERVER_NOT_CONFIGURED ) ; pResponse . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , MESSAGE_REMOT...
Services a single request . Supports HTTP and HTTPS .
547
10
156,140
private String createRemoteRequestURI ( HttpServletRequest pRequest ) { StringBuilder requestURI = new StringBuilder ( remotePath ) ; requestURI . append ( pRequest . getPathInfo ( ) ) ; if ( ! StringUtil . isEmpty ( pRequest . getQueryString ( ) ) ) { requestURI . append ( "?" ) ; requestURI . append ( pRequest . getQ...
Creates the remote request URI based on the incoming request . The URI will include any query strings etc .
100
21
156,141
public void setExpiryTime ( long pExpiryTime ) { long oldEexpiryTime = expiryTime ; expiryTime = pExpiryTime ; if ( expiryTime < oldEexpiryTime ) { // Expire now nextExpiryTime = 0 ; removeExpiredEntries ( ) ; } }
Sets the maximum time any value will be kept in the map before it expires . Removes any items that are older than the specified time .
74
29
156,142
private synchronized void removeExpiredEntriesSynced ( long pTime ) { if ( pTime > nextExpiryTime ) { //// long next = Long . MAX_VALUE ; nextExpiryTime = next ; // Avoid multiple runs... for ( Iterator < Entry < K , V > > iterator = new EntryIterator ( ) ; iterator . hasNext ( ) ; ) { TimedEntry < K , V > entry = ( Ti...
Okay I guess this do resemble DCL ...
145
9
156,143
static void bitRotateCW ( final byte [ ] pSrc , int pSrcPos , int pSrcStep , final byte [ ] pDst , int pDstPos , int pDstStep ) { int idx = pSrcPos ; int lonyb ; int hinyb ; long lo = 0 ; long hi = 0 ; for ( int i = 0 ; i < 8 ; i ++ ) { lonyb = pSrc [ idx ] & 0xF ; hinyb = ( pSrc [ idx ] >> 4 ) & 0xF ; lo |= RTABLE [ i...
Rotate bits clockwise . The IFFImageReader uses this to convert pixel bits from planar to chunky . Bits from the source are rotated 90 degrees clockwise written to the destination .
497
39
156,144
public static void readPixels ( DataInput in , float [ ] data , int numpixels ) throws IOException { byte [ ] rgbe = new byte [ 4 ] ; float [ ] rgb = new float [ 3 ] ; int offset = 0 ; while ( numpixels -- > 0 ) { in . readFully ( rgbe ) ; rgbe2float ( rgb , rgbe , 0 ) ; data [ offset ++ ] = rgb [ 0 ] ; data [ offset +...
Simple read routine . Will not correctly handle run length encoding .
121
12
156,145
public static void float2rgbe ( byte [ ] rgbe , float red , float green , float blue ) { float v ; int e ; v = red ; if ( green > v ) { v = green ; } if ( blue > v ) { v = blue ; } if ( v < 1e-32f ) { rgbe [ 0 ] = rgbe [ 1 ] = rgbe [ 2 ] = rgbe [ 3 ] = 0 ; } else { FracExp fe = frexp ( v ) ; v = ( float ) ( fe . getFra...
Standard conversion from float pixels to rgbe pixels .
198
10
156,146
protected RenderedImage doFilter ( BufferedImage pImage , ServletRequest pRequest , ImageServletResponse pResponse ) { // Get crop coordinates int x = ServletUtil . getIntParameter ( pRequest , PARAM_CROP_X , - 1 ) ; int y = ServletUtil . getIntParameter ( pRequest , PARAM_CROP_Y , - 1 ) ; int width = ServletUtil . get...
Reads the image from the requested URL scales it crops it and returns it in the Servlet stream . See above for details on parameters .
301
28
156,147
private static String hashFile ( final File file , final int pieceSize ) throws InterruptedException , IOException { return hashFiles ( Collections . singletonList ( file ) , pieceSize ) ; }
Return the concatenation of the SHA - 1 hashes of a file s pieces .
41
17
156,148
public static PeerMessage parse ( ByteBuffer buffer , TorrentInfo torrent ) throws ParseException { int length = buffer . getInt ( ) ; if ( length == 0 ) { return KeepAliveMessage . parse ( buffer , torrent ) ; } else if ( length != buffer . remaining ( ) ) { throw new ParseException ( "Message size did not match annou...
Parse the given buffer into a peer protocol message .
341
11
156,149
private void serveError ( Status status , String error , RequestHandler requestHandler ) throws IOException { this . serveError ( status , HTTPTrackerErrorMessage . craft ( error ) , requestHandler ) ; }
Write an error message to the response with the given HTTP status code .
42
14
156,150
private void serveError ( Status status , ErrorMessage . FailureReason reason , RequestHandler requestHandler ) throws IOException { this . serveError ( status , reason . getMessage ( ) , requestHandler ) ; }
Write a tracker failure reason code to the response with the given HTTP status code .
43
16
156,151
protected String formatAnnounceEvent ( AnnounceRequestMessage . RequestEvent event ) { return AnnounceRequestMessage . RequestEvent . NONE . equals ( event ) ? "" : String . format ( " %s" , event . name ( ) ) ; }
Formats an announce event into a usable string .
51
10
156,152
protected void handleTrackerAnnounceResponse ( TrackerMessage message , boolean inhibitEvents , String hexInfoHash ) throws AnnounceException { if ( message instanceof ErrorMessage ) { ErrorMessage error = ( ErrorMessage ) message ; throw new AnnounceException ( error . getReason ( ) ) ; } if ( ! ( message instanceof A...
Handle the announce response from the tracker .
180
8
156,153
protected void fireAnnounceResponseEvent ( int complete , int incomplete , int interval , String hexInfoHash ) { for ( AnnounceResponseListener listener : this . listeners ) { listener . handleAnnounceResponse ( interval , complete , incomplete , hexInfoHash ) ; } }
Fire the announce response event to all listeners .
55
9
156,154
protected void fireDiscoveredPeersEvent ( List < Peer > peers , String hexInfoHash ) { for ( AnnounceResponseListener listener : this . listeners ) { listener . handleDiscoveredPeers ( peers , hexInfoHash ) ; } }
Fire the new peer discovery event to all listeners .
50
10
156,155
@ Override public void finish ( ) throws IOException { try { myLock . writeLock ( ) . lock ( ) ; logger . debug ( "Closing file channel to " + this . current . getName ( ) + " (download complete)." ) ; if ( this . channel . isOpen ( ) ) { this . channel . force ( true ) ; } // Nothing more to do if we're already on the...
Move the partial file to its final location .
306
9
156,156
public static HTTPAnnounceResponseMessage craft ( int interval , int complete , int incomplete , List < Peer > peers , String hexInfoHash ) throws IOException , UnsupportedEncodingException { Map < String , BEValue > response = new HashMap < String , BEValue > ( ) ; response . put ( "interval" , new BEValue ( interval ...
Craft a compact announce response message with a torrent identifier .
287
11
156,157
private List < FileOffset > select ( long offset , long length ) { if ( offset + length > this . size ) { throw new IllegalArgumentException ( "Buffer overrun (" + offset + " + " + length + " > " + this . size + ") !" ) ; } List < FileOffset > selected = new LinkedList < FileOffset > ( ) ; long bytes = 0 ; for ( FileSt...
Select the group of files impacted by an operation .
247
10
156,158
@ Override protected void handleTrackerAnnounceResponse ( TrackerMessage message , boolean inhibitEvents , String hexInfoHash ) throws AnnounceException { this . validateTrackerResponse ( message ) ; super . handleTrackerAnnounceResponse ( message , inhibitEvents , hexInfoHash ) ; }
Handles the tracker announce response message .
56
8
156,159
@ Override protected void close ( ) { this . stop = true ; // Close the socket to force blocking operations to return. if ( this . socket != null && ! this . socket . isClosed ( ) ) { this . socket . close ( ) ; } }
Close this announce connection .
56
5
156,160
private void validateTrackerResponse ( TrackerMessage message ) throws AnnounceException { if ( message instanceof ErrorMessage ) { throw new AnnounceException ( ( ( ErrorMessage ) message ) . getReason ( ) ) ; } if ( message instanceof UDPTrackerMessage && ( ( ( UDPTrackerMessage ) message ) . getTransactionId ( ) != ...
Validates an incoming tracker message .
89
7
156,161
private void handleTrackerConnectResponse ( TrackerMessage message ) throws AnnounceException { this . validateTrackerResponse ( message ) ; if ( ! ( message instanceof ConnectionResponseMessage ) ) { throw new AnnounceException ( "Unexpected tracker message type " + message . getType ( ) . name ( ) + "!" ) ; } UDPConn...
Handles the tracker connect response message .
131
8
156,162
private void send ( ByteBuffer data ) { try { this . socket . send ( new DatagramPacket ( data . array ( ) , data . capacity ( ) , this . address ) ) ; } catch ( IOException ioe ) { logger . info ( "Error sending datagram packet to tracker at {}: {}." , this . address , ioe . getMessage ( ) ) ; } }
Send a UDP packet to the tracker .
83
8
156,163
private ByteBuffer recv ( int attempt ) throws IOException , SocketException , SocketTimeoutException { int timeout = UDP_BASE_TIMEOUT_SECONDS * ( int ) Math . pow ( 2 , attempt ) ; logger . trace ( "Setting receive timeout to {}s for attempt {}..." , timeout , attempt ) ; this . socket . setSoTimeout ( timeout * 1000 ...
Receive a UDP packet from the tracker .
164
9
156,164
public String getString ( String encoding ) throws InvalidBEncodingException { try { return new String ( this . getBytes ( ) , encoding ) ; } catch ( ClassCastException cce ) { throw new InvalidBEncodingException ( cce . toString ( ) ) ; } catch ( UnsupportedEncodingException uee ) { throw new InternalError ( uee . toS...
Returns this BEValue as a String interpreted with the specified encoding .
86
13
156,165
public Number getNumber ( ) throws InvalidBEncodingException { try { return ( Number ) this . value ; } catch ( ClassCastException cce ) { throw new InvalidBEncodingException ( cce . toString ( ) ) ; } }
Returns this BEValue as a Number .
52
8
156,166
@ SuppressWarnings ( "unchecked" ) public List < BEValue > getList ( ) throws InvalidBEncodingException { if ( this . value instanceof ArrayList ) { return ( ArrayList < BEValue > ) this . value ; } else { throw new InvalidBEncodingException ( "Excepted List<BEvalue> !" ) ; } }
Returns this BEValue as a List of BEValues .
78
11
156,167
@ SuppressWarnings ( "unchecked" ) public Map < String , BEValue > getMap ( ) throws InvalidBEncodingException { if ( this . value instanceof HashMap ) { return ( Map < String , BEValue > ) this . value ; } else { throw new InvalidBEncodingException ( "Expected Map<String, BEValue> !" ) ; } }
Returns this BEValue as a Map of String keys and BEValue values .
83
15
156,168
public void start ( final boolean startPeerCleaningThread ) throws IOException { logger . info ( "Starting BitTorrent tracker on {}..." , getAnnounceUrl ( ) ) ; connection = new SocketConnection ( new ContainerServer ( myTrackerServiceContainer ) ) ; List < SocketAddress > tries = new ArrayList < SocketAddress > ( ) { ...
Start the tracker thread .
442
5
156,169
public void announce ( final AnnounceRequestMessage . RequestEvent event , boolean inhibitEvents , final AnnounceableInformation torrentInfo , final List < Peer > adresses ) throws AnnounceException { logAnnounceRequest ( event , torrentInfo ) ; final List < HTTPTrackerMessage > trackerResponses = new ArrayList < HTTPT...
Build send and process a tracker announce request .
282
9
156,170
private HTTPAnnounceRequestMessage buildAnnounceRequest ( AnnounceRequestMessage . RequestEvent event , AnnounceableInformation torrentInfo , Peer peer ) throws IOException , MessageValidationException { // Build announce request message final long uploaded = torrentInfo . getUploaded ( ) ; final long downloaded = torr...
Build the announce request tracker message .
149
7
156,171
public URL buildAnnounceURL ( URL trackerAnnounceURL ) throws UnsupportedEncodingException , MalformedURLException { String base = trackerAnnounceURL . toString ( ) ; StringBuilder url = new StringBuilder ( base ) ; url . append ( base . contains ( "?" ) ? "&" : "?" ) . append ( "info_hash=" ) . append ( URLEncoder . e...
Build the announce request URL for the given tracker announce URL .
411
12
156,172
public synchronized void add ( long count ) { this . bytes += count ; if ( this . reset == 0 ) { this . reset = System . currentTimeMillis ( ) ; } this . last = System . currentTimeMillis ( ) ; }
Add a byte count to the current measurement .
52
9
156,173
public byte [ ] getRawIp ( ) { final InetAddress address = this . address . getAddress ( ) ; if ( address == null ) return null ; return address . getAddress ( ) ; }
Returns a binary representation of the peer s IP .
44
10
156,174
public static void main ( String [ ] args ) { BasicConfigurator . configure ( new ConsoleAppender ( new PatternLayout ( "%d [%-25t] %-5p: %m%n" ) ) ) ; CmdLineParser parser = new CmdLineParser ( ) ; CmdLineParser . Option help = parser . addBooleanOption ( ' ' , "help" ) ; CmdLineParser . Option port = parser . addInte...
Main function to start a tracker .
488
7
156,175
public static void main ( String [ ] args ) { BasicConfigurator . configure ( new ConsoleAppender ( new PatternLayout ( "%d [%-25t] %-5p: %m%n" ) ) ) ; CmdLineParser parser = new CmdLineParser ( ) ; CmdLineParser . Option help = parser . addBooleanOption ( ' ' , "help" ) ; CmdLineParser . Option output = parser . addSt...
Main client entry point for stand - alone operation .
563
10
156,176
public Piece getPiece ( int index ) { if ( this . pieces == null ) { throw new IllegalStateException ( "Torrent not initialized yet." ) ; } if ( index >= this . pieces . length ) { throw new IllegalArgumentException ( "Invalid piece index!" ) ; } return this . pieces [ index ] ; }
Retrieve a piece object by index .
69
8
156,177
public synchronized void markCompleted ( Piece piece ) { if ( this . completedPieces . get ( piece . getIndex ( ) ) ) { return ; } // A completed piece means that's that much data left to download for // this torrent. myTorrentStatistic . addLeft ( - piece . size ( ) ) ; this . completedPieces . set ( piece . getIndex ...
Mark a piece as completed decrementing the piece size in bytes from our left bytes to download counter .
123
21
156,178
public void start ( final URI defaultTrackerURI , final AnnounceResponseListener listener , final Peer [ ] peers , final int announceInterval ) { myAnnounceInterval = announceInterval ; myPeers . addAll ( Arrays . asList ( peers ) ) ; if ( defaultTrackerURI != null ) { try { myDefaultTracker = myTrackerClientFactory . ...
Start the announce request thread .
205
6
156,179
public void setAnnounceInterval ( int announceInterval ) { if ( announceInterval <= 0 ) { this . stop ( true ) ; return ; } if ( this . myAnnounceInterval == announceInterval ) { return ; } logger . trace ( "Setting announce interval to {}s per tracker request." , announceInterval ) ; this . myAnnounceInterval = announ...
Set the announce interval .
85
5
156,180
public TrackerClient getCurrentTrackerClient ( AnnounceableInformation torrent ) { final URI uri = getURIForTorrent ( torrent ) ; if ( uri == null ) return null ; return this . clients . get ( uri . toString ( ) ) ; }
Returns the current tracker client used for announces .
54
9
156,181
public static BEValue bdecode ( ByteBuffer data ) throws IOException { return BDecoder . bdecode ( new ByteArrayInputStream ( data . array ( ) ) ) ; }
Decode a B - encoded byte buffer .
40
9
156,182
public BEValue bdecode ( ) throws IOException { if ( this . getNextIndicator ( ) == - 1 ) return null ; if ( this . indicator >= ' ' && this . indicator <= ' ' ) return this . bdecodeBytes ( ) ; else if ( this . indicator == ' ' ) return this . bdecodeNumber ( ) ; else if ( this . indicator == ' ' ) return this . bdeco...
Gets the next indicator and returns either null when the stream has ended or b - decodes the rest of the stream and returns the appropriate BEValue encoded object .
139
33
156,183
public BEValue bdecodeBytes ( ) throws IOException { int c = this . getNextIndicator ( ) ; int num = c - ' ' ; if ( num < 0 || num > 9 ) throw new InvalidBEncodingException ( "Number expected, not '" + ( char ) c + "'" ) ; this . indicator = 0 ; c = this . read ( ) ; int i = c - ' ' ; while ( i >= 0 && i <= 9 ) { // Th...
Returns the next b - encoded value on the stream and makes sure it is a byte array .
177
19
156,184
public BEValue bdecodeNumber ( ) throws IOException { int c = this . getNextIndicator ( ) ; if ( c != ' ' ) { throw new InvalidBEncodingException ( "Expected 'i', not '" + ( char ) c + "'" ) ; } this . indicator = 0 ; c = this . read ( ) ; if ( c == ' ' ) { c = this . read ( ) ; if ( c == ' ' ) return new BEValue ( Big...
Returns the next b - encoded value on the stream and makes sure it is a number .
376
18
156,185
public BEValue bdecodeList ( ) throws IOException { int c = this . getNextIndicator ( ) ; if ( c != ' ' ) { throw new InvalidBEncodingException ( "Expected 'l', not '" + ( char ) c + "'" ) ; } this . indicator = 0 ; List < BEValue > result = new ArrayList < BEValue > ( ) ; c = this . getNextIndicator ( ) ; while ( c !=...
Returns the next b - encoded value on the stream and makes sure it is a list .
143
18
156,186
public boolean validate ( SharedTorrent torrent , Piece piece ) throws IOException { logger . trace ( "Validating {}..." , this ) ; // TODO: remove cast to int when large ByteBuffer support is // implemented in Java. byte [ ] pieceBytes = data . array ( ) ; final byte [ ] calculatedHash = TorrentUtils . calculateSha1Ha...
Validates this piece .
130
5
156,187
private ByteBuffer _read ( long offset , long length , ByteBuffer buffer ) throws IOException { if ( offset + length > this . length ) { throw new IllegalArgumentException ( "Piece#" + this . index + " overrun (" + offset + " + " + length + " > " + this . length + ") !" ) ; } // TODO: remove cast to int when large Byte...
Internal piece data read function .
162
6
156,188
public ByteBuffer read ( long offset , int length , ByteBuffer block ) throws IllegalArgumentException , IllegalStateException , IOException { if ( ! this . valid ) { throw new IllegalStateException ( "Attempting to read an " + "known-to-be invalid piece!" ) ; } return this . _read ( offset , length , block ) ; }
Read a piece block from the underlying byte storage .
76
10
156,189
public void record ( ByteBuffer block , int offset ) { if ( this . data == null ) { // TODO: remove cast to int when large ByteBuffer support is // implemented in Java. this . data = ByteBuffer . allocate ( ( int ) this . length ) ; } int pos = block . position ( ) ; this . data . position ( offset ) ; this . data . pu...
Record the given block at the given offset in this piece .
93
12
156,190
public int compareTo ( Piece other ) { // return true for the same pieces, otherwise sort by time seen, then by index; if ( this . equals ( other ) ) { return 0 ; } else if ( this . seen == other . seen ) { return new Integer ( this . index ) . compareTo ( other . index ) ; } else if ( this . seen < other . seen ) { re...
Piece comparison function for ordering pieces based on their availability .
95
12
156,191
public void addPeer ( TrackedPeer peer ) { this . peers . put ( new PeerUID ( peer . getAddress ( ) , this . getHexInfoHash ( ) ) , peer ) ; }
Add a peer exchanging on this torrent .
45
8
156,192
public List < Peer > getSomePeers ( Peer peer ) { List < Peer > peers = new LinkedList < Peer > ( ) ; // Extract answerPeers random peers List < TrackedPeer > candidates = new LinkedList < TrackedPeer > ( this . peers . values ( ) ) ; Collections . shuffle ( candidates ) ; int count = 0 ; for ( TrackedPeer candidate : ...
Get a list of peers we can return in an announce response for this torrent .
159
16
156,193
public static TrackedTorrent load ( File torrent ) throws IOException { TorrentMetadata torrentMetadata = new TorrentParser ( ) . parseFromFile ( torrent ) ; return new TrackedTorrent ( torrentMetadata . getInfoHash ( ) ) ; }
Load a tracked torrent from the given torrent file .
52
10
156,194
public TorrentManager addTorrent ( String dotTorrentFilePath , String downloadDirPath ) throws IOException { return addTorrent ( dotTorrentFilePath , downloadDirPath , FairPieceStorageFactory . INSTANCE ) ; }
Adds torrent to storage validate downloaded files and start seeding and leeching the torrent
45
17
156,195
public TorrentManager addTorrent ( String dotTorrentFilePath , String downloadDirPath , List < TorrentListener > listeners ) throws IOException { return addTorrent ( dotTorrentFilePath , downloadDirPath , FairPieceStorageFactory . INSTANCE , listeners ) ; }
Adds torrent to storage with specified listeners validate downloaded files and start seeding and leeching the torrent
54
20
156,196
public TorrentManager addTorrent ( TorrentMetadataProvider metadataProvider , PieceStorage pieceStorage ) throws IOException { return addTorrent ( metadataProvider , pieceStorage , Collections . < TorrentListener > emptyList ( ) ) ; }
Adds torrent to storage with any storage and metadata source
45
10
156,197
public TorrentManager addTorrent ( TorrentMetadataProvider metadataProvider , PieceStorage pieceStorage , List < TorrentListener > listeners ) throws IOException { TorrentMetadata torrentMetadata = metadataProvider . getTorrentMetadata ( ) ; EventDispatcher eventDispatcher = new EventDispatcher ( ) ; for ( TorrentListe...
Adds torrent to storage with any storage metadata source and specified listeners
338
12
156,198
public void removeTorrent ( String torrentHash ) { logger . debug ( "Stopping seeding " + torrentHash ) ; final Pair < SharedTorrent , LoadedTorrent > torrents = torrentsStorage . remove ( torrentHash ) ; SharedTorrent torrent = torrents . first ( ) ; if ( torrent != null ) { torrent . setClientState ( ClientState . DO...
Removes specified torrent from storage .
140
7
156,199
public boolean isSeed ( String hexInfoHash ) { SharedTorrent t = this . torrentsStorage . getTorrent ( hexInfoHash ) ; return t != null && t . isComplete ( ) ; }
Tells whether we are a seed for the torrent we re sharing .
43
14