idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
32,700
protected int getQuality ( String pQualityStr ) { if ( ! StringUtil . isEmpty ( pQualityStr ) ) { try { Class cl = Image . class ; Field field = cl . getField ( pQualityStr . toUpperCase ( ) ) ; return field . getInt ( null ) ; } catch ( IllegalAccessException ia ) { log ( "Unable to get quality." , ia ) ; } catch ( NoSuchFieldException nsf ) { log ( "Unable to get quality." , nsf ) ; } } return defaultScaleQuality ; }
Gets the quality constant for the scaling from the string argument .
32,701
protected int getUnits ( String pUnitStr ) { if ( StringUtil . isEmpty ( pUnitStr ) || pUnitStr . equalsIgnoreCase ( "PIXELS" ) ) { return UNITS_PIXELS ; } else if ( pUnitStr . equalsIgnoreCase ( "PERCENT" ) ) { return UNITS_PERCENT ; } else { return UNITS_UNKNOWN ; } }
Gets the units constant for the width and height arguments from the given string argument .
32,702
private int getHuffmanValue ( final int table [ ] , final int temp [ ] , final int index [ ] ) throws IOException { int code , input ; final int mask = 0xFFFF ; if ( index [ 0 ] < 8 ) { temp [ 0 ] <<= 8 ; input = this . input . readUnsignedByte ( ) ; if ( input == 0xFF ) { marker = this . input . readUnsignedByte ( ) ; if ( marker != 0 ) { markerIndex = 9 ; } } temp [ 0 ] |= input ; } else { index [ 0 ] -= 8 ; } code = table [ temp [ 0 ] >> index [ 0 ] ] ; if ( ( code & MSB ) != 0 ) { if ( markerIndex != 0 ) { markerIndex = 0 ; return 0xFF00 | marker ; } temp [ 0 ] &= ( mask >> ( 16 - index [ 0 ] ) ) ; temp [ 0 ] <<= 8 ; input = this . input . readUnsignedByte ( ) ; if ( input == 0xFF ) { marker = this . input . readUnsignedByte ( ) ; if ( marker != 0 ) { markerIndex = 9 ; } } temp [ 0 ] |= input ; code = table [ ( ( code & 0xFF ) * 256 ) + ( temp [ 0 ] >> index [ 0 ] ) ] ; index [ 0 ] += 8 ; } index [ 0 ] += 8 - ( code >> 8 ) ; if ( index [ 0 ] < 0 ) { throw new IIOException ( "index=" + index [ 0 ] + " temp=" + temp [ 0 ] + " code=" + code + " in HuffmanValue()" ) ; } if ( index [ 0 ] < markerIndex ) { markerIndex = 0 ; return 0xFF00 | marker ; } temp [ 0 ] &= ( mask >> ( 16 - index [ 0 ] ) ) ; return code & 0xFF ; }
will not be called
32,703
public void write ( final byte [ ] pBytes , final int pOffset , final int pLength ) throws IOException { if ( ! flushOnWrite && pLength < buffer . remaining ( ) ) { buffer . put ( pBytes , pOffset , pLength ) ; } else { encodeBuffer ( ) ; encoder . encode ( out , ByteBuffer . wrap ( pBytes , pOffset , pLength ) ) ; } }
tell the EncoderStream how large buffer it prefers ...
32,704
private static URL getURLAndSetAuthorization ( final String pURL , final Properties pProperties ) throws MalformedURLException { String url = pURL ; String userPass = null ; String protocolPrefix = HTTP ; int httpIdx = url . indexOf ( HTTPS ) ; if ( httpIdx >= 0 ) { protocolPrefix = HTTPS ; url = url . substring ( httpIdx + HTTPS . length ( ) ) ; } else { httpIdx = url . indexOf ( HTTP ) ; if ( httpIdx >= 0 ) { url = url . substring ( httpIdx + HTTP . length ( ) ) ; } } int atIdx = url . indexOf ( "@" ) ; if ( atIdx >= 0 ) { userPass = url . substring ( 0 , atIdx ) ; url = url . substring ( atIdx + 1 ) ; } if ( userPass != null ) { pProperties . setProperty ( "Authorization" , "Basic " + BASE64 . encode ( userPass . getBytes ( ) ) ) ; } return new URL ( protocolPrefix + url ) ; }
Registers the password from the URL string and returns the URL object .
32,705
public static HttpURLConnection createHttpURLConnection ( URL pURL , Properties pProperties , boolean pFollowRedirects , int pTimeout ) throws IOException { HttpURLConnection conn ; if ( pTimeout > 0 ) { conn = new com . twelvemonkeys . net . HttpURLConnection ( pURL , pTimeout ) ; } else { conn = ( HttpURLConnection ) pURL . openConnection ( ) ; } if ( ( pProperties == null ) || ! pProperties . containsKey ( "User-Agent" ) ) { conn . setRequestProperty ( "User-Agent" , VERSION_ID + " (" + System . getProperty ( "os.name" ) + "/" + System . getProperty ( "os.version" ) + "; " + System . getProperty ( "os.arch" ) + "; " + System . getProperty ( "java.vm.name" ) + "/" + System . getProperty ( "java.vm.version" ) + ")" ) ; } if ( pProperties != null ) { for ( Map . Entry < Object , Object > entry : pProperties . entrySet ( ) ) { conn . setRequestProperty ( ( String ) entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ; } } try { conn . setInstanceFollowRedirects ( pFollowRedirects ) ; } catch ( LinkageError le ) { HttpURLConnection . setFollowRedirects ( pFollowRedirects ) ; System . err . println ( "You are using an old Java Spec, consider upgrading." ) ; System . err . println ( "java.net.HttpURLConnection.setInstanceFollowRedirects(" + pFollowRedirects + ") failed." ) ; } conn . setDoInput ( true ) ; conn . setDoOutput ( true ) ; return conn ; }
Creates a HTTP connection to the given URL .
32,706
public static String encode ( byte [ ] pData ) { int offset = 0 ; int len ; StringBuilder buf = new StringBuilder ( ) ; while ( ( pData . length - offset ) > 0 ) { byte a , b , c ; if ( ( pData . length - offset ) > 2 ) { len = 3 ; } else { len = pData . length - offset ; } switch ( len ) { case 1 : a = pData [ offset ] ; b = 0 ; buf . append ( PEM_ARRAY [ ( a >>> 2 ) & 0x3F ] ) ; buf . append ( PEM_ARRAY [ ( ( a << 4 ) & 0x30 ) + ( ( b >>> 4 ) & 0xf ) ] ) ; buf . append ( '=' ) ; buf . append ( '=' ) ; offset ++ ; break ; case 2 : a = pData [ offset ] ; b = pData [ offset + 1 ] ; c = 0 ; buf . append ( PEM_ARRAY [ ( a >>> 2 ) & 0x3F ] ) ; buf . append ( PEM_ARRAY [ ( ( a << 4 ) & 0x30 ) + ( ( b >>> 4 ) & 0xf ) ] ) ; buf . append ( PEM_ARRAY [ ( ( b << 2 ) & 0x3c ) + ( ( c >>> 6 ) & 0x3 ) ] ) ; buf . append ( '=' ) ; offset += offset + 2 ; break ; default : a = pData [ offset ] ; b = pData [ offset + 1 ] ; c = pData [ offset + 2 ] ; buf . append ( PEM_ARRAY [ ( a >>> 2 ) & 0x3F ] ) ; buf . append ( PEM_ARRAY [ ( ( a << 4 ) & 0x30 ) + ( ( b >>> 4 ) & 0xf ) ] ) ; buf . append ( PEM_ARRAY [ ( ( b << 2 ) & 0x3c ) + ( ( c >>> 6 ) & 0x3 ) ] ) ; buf . append ( PEM_ARRAY [ c & 0x3F ] ) ; offset = offset + 3 ; break ; } } return buf . toString ( ) ; }
Encodes the input data using the standard base64 encoding scheme .
32,707
public void setSourceSubsampling ( int pXSub , int pYSub ) { if ( xSub != pXSub || ySub != pYSub ) { dispose ( ) ; } if ( pXSub > 1 ) { xSub = pXSub ; } if ( pYSub > 1 ) { ySub = pYSub ; } }
Sets the source subsampling for the new image .
32,708
public void addProgressListener ( ProgressListener pListener ) { if ( pListener == null ) { return ; } if ( listeners == null ) { listeners = new CopyOnWriteArrayList < ProgressListener > ( ) ; } listeners . add ( pListener ) ; }
Adds a progress listener to this factory .
32,709
public void removeProgressListener ( ProgressListener pListener ) { if ( pListener == null ) { return ; } if ( listeners == null ) { return ; } listeners . remove ( pListener ) ; }
Removes a progress listener from this factory .
32,710
protected PasswordAuthentication getPasswordAuthentication ( ) { if ( ! sInitialized && MAGIC . equals ( getRequestingScheme ( ) ) && getRequestingPort ( ) == FOURTYTWO ) { return new PasswordAuthentication ( MAGIC , ( "" + FOURTYTWO ) . toCharArray ( ) ) ; } return passwordAuthentications . get ( new AuthKey ( getRequestingSite ( ) , getRequestingPort ( ) , getRequestingProtocol ( ) , getRequestingPrompt ( ) , getRequestingScheme ( ) ) ) ; }
Gets the PasswordAuthentication for the request . Called when password authorization is needed .
32,711
public PasswordAuthentication registerPasswordAuthentication ( URL pURL , PasswordAuthentication pPA ) { return registerPasswordAuthentication ( NetUtil . createInetAddressFromURL ( pURL ) , pURL . getPort ( ) , pURL . getProtocol ( ) , null , BASIC , pPA ) ; }
Registers a PasswordAuthentication with a given URL address .
32,712
public PasswordAuthentication registerPasswordAuthentication ( InetAddress pAddress , int pPort , String pProtocol , String pPrompt , String pScheme , PasswordAuthentication pPA ) { return passwordAuthentications . put ( new AuthKey ( pAddress , pPort , pProtocol , pPrompt , pScheme ) , pPA ) ; }
Registers a PasswordAuthentication with a given net address .
32,713
public PasswordAuthentication unregisterPasswordAuthentication ( URL pURL ) { return unregisterPasswordAuthentication ( NetUtil . createInetAddressFromURL ( pURL ) , pURL . getPort ( ) , pURL . getProtocol ( ) , null , BASIC ) ; }
Unregisters a PasswordAuthentication with a given URL address .
32,714
public PasswordAuthentication unregisterPasswordAuthentication ( InetAddress pAddress , int pPort , String pProtocol , String pPrompt , String pScheme ) { return passwordAuthentications . remove ( new AuthKey ( pAddress , pPort , pProtocol , pPrompt , pScheme ) ) ; }
Unregisters a PasswordAuthentication with a given net address .
32,715
@ InitParam ( name = "accept-mappings-file" ) public void setAcceptMappingsFile ( String pPropertiesFile ) throws ServletConfigException { Properties mappings = new Properties ( ) ; try { log ( "Reading Accept-mappings properties file: " + pPropertiesFile ) ; mappings . load ( getServletContext ( ) . getResourceAsStream ( pPropertiesFile ) ) ; } catch ( IOException e ) { throw new ServletConfigException ( "Could not read Accept-mappings properties file: " + pPropertiesFile , e ) ; } parseMappings ( mappings ) ; }
Sets the accept - mappings for this filter
32,716
public int doEndTag ( ) throws JspException { String trimmed = truncateWS ( bodyContent . getString ( ) ) ; try { pageContext . getOut ( ) . print ( trimmed ) ; } catch ( IOException ioe ) { throw new JspException ( ioe ) ; } return super . doEndTag ( ) ; }
doEndTag implementation truncates all whitespace .
32,717
private static String truncateWS ( String pStr ) { char [ ] chars = pStr . toCharArray ( ) ; int count = 0 ; boolean lastWasWS = true ; for ( int i = 0 ; i < chars . length ; i ++ ) { if ( ! Character . isWhitespace ( chars [ i ] ) ) { chars [ count ++ ] = chars [ i ] ; lastWasWS = false ; } else { if ( ! lastWasWS ) { if ( chars [ i ] == 0x0d ) { chars [ count ++ ] = 0x0a ; } else { chars [ count ++ ] = chars [ i ] ; } } lastWasWS = true ; } } return new String ( chars , 0 , count ) ; }
Truncates whitespace from the given string .
32,718
private ImageServletResponse createImageServletResponse ( final ServletRequest pRequest , final ServletResponse pResponse ) { if ( pResponse instanceof ImageServletResponseImpl ) { ImageServletResponseImpl response = ( ImageServletResponseImpl ) pResponse ; return response ; } return new ImageServletResponseImpl ( pRequest , pResponse , getServletContext ( ) ) ; }
Creates the image servlet response for this response .
32,719
protected RenderedImage doFilter ( BufferedImage pImage , ServletRequest pRequest , ImageServletResponse pResponse ) { double ang = getAngle ( pRequest ) ; Rectangle2D rect = getBounds ( pRequest , pImage , ang ) ; int width = ( int ) rect . getWidth ( ) ; int height = ( int ) rect . getHeight ( ) ; BufferedImage res = ImageUtil . createTransparent ( width , height , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D g = res . createGraphics ( ) ; String str = pRequest . getParameter ( PARAM_BGCOLOR ) ; if ( ! StringUtil . isEmpty ( str ) ) { Color bgcolor = StringUtil . toColor ( str ) ; g . setBackground ( bgcolor ) ; g . clearRect ( 0 , 0 , width , height ) ; } RenderingHints hints = new RenderingHints ( RenderingHints . KEY_COLOR_RENDERING , RenderingHints . VALUE_COLOR_RENDER_QUALITY ) ; hints . add ( new RenderingHints ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_QUALITY ) ) ; hints . add ( new RenderingHints ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ) ; hints . add ( new RenderingHints ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_BICUBIC ) ) ; g . setRenderingHints ( hints ) ; AffineTransform at = AffineTransform . getRotateInstance ( ang , width / 2.0 , height / 2.0 ) ; at . translate ( width / 2.0 - pImage . getWidth ( ) / 2.0 , height / 2.0 - pImage . getHeight ( ) / 2.0 ) ; g . drawImage ( pImage , at , null ) ; return res ; }
Reads the image from the requested URL rotates it and returns it in the Servlet stream . See above for details on parameters .
32,720
private double getAngle ( ServletRequest pReq ) { double angle = 0.0 ; String str = pReq . getParameter ( PARAM_ANGLE ) ; if ( ! StringUtil . isEmpty ( str ) ) { angle = Double . parseDouble ( str ) ; str = pReq . getParameter ( PARAM_ANGLE_UNITS ) ; if ( ! StringUtil . isEmpty ( str ) && ANGLE_DEGREES . equalsIgnoreCase ( str ) ) { angle = Math . toRadians ( angle ) ; } } return angle ; }
Gets the angle of rotation .
32,721
private Rectangle2D getBounds ( ServletRequest pReq , BufferedImage pImage , double pAng ) { int width = pImage . getWidth ( ) ; int height = pImage . getHeight ( ) ; AffineTransform at = AffineTransform . getRotateInstance ( pAng , width / 2.0 , height / 2.0 ) ; Rectangle2D orig = new Rectangle ( width , height ) ; Shape rotated = at . createTransformedShape ( orig ) ; if ( ServletUtil . getBooleanParameter ( pReq , PARAM_CROP , false ) ) { return rotated . getBounds2D ( ) ; } else { return rotated . getBounds2D ( ) ; } }
Get the bounding rectangle of the rotated image .
32,722
void initIRGB ( int [ ] pTemp ) { final int x = ( 1 << TRUNCBITS ) ; final int xsqr = 1 << ( TRUNCBITS * 2 ) ; final int xsqr2 = xsqr + xsqr ; for ( int i = 0 ; i < numColors ; ++ i ) { if ( i == transparentIndex ) { continue ; } int red , r , rdist , rinc , rxx ; int green , g , gdist , ginc , gxx ; int blue , b , bdist , binc , bxx ; if ( rgbMapByte != null ) { red = rgbMapByte [ i * 4 ] & 0xFF ; green = rgbMapByte [ i * 4 + 1 ] & 0xFF ; blue = rgbMapByte [ i * 4 + 2 ] & 0xFF ; } else if ( rgbMapInt != null ) { red = ( rgbMapInt [ i ] >> 16 ) & 0xFF ; green = ( rgbMapInt [ i ] >> 8 ) & 0xFF ; blue = rgbMapInt [ i ] & 0xFF ; } else { throw new IllegalStateException ( "colormap == null" ) ; } rdist = red - x / 2 ; gdist = green - x / 2 ; bdist = blue - x / 2 ; rdist = rdist * rdist + gdist * gdist + bdist * bdist ; rinc = 2 * ( xsqr - ( red << TRUNCBITS ) ) ; ginc = 2 * ( xsqr - ( green << TRUNCBITS ) ) ; binc = 2 * ( xsqr - ( blue << TRUNCBITS ) ) ; int rgbI = 0 ; for ( r = 0 , rxx = rinc ; r < MAXQUANTVAL ; rdist += rxx , ++ r , rxx += xsqr2 ) { for ( g = 0 , gdist = rdist , gxx = ginc ; g < MAXQUANTVAL ; gdist += gxx , ++ g , gxx += xsqr2 ) { for ( b = 0 , bdist = gdist , bxx = binc ; b < MAXQUANTVAL ; bdist += bxx , ++ b , ++ rgbI , bxx += xsqr2 ) { if ( i == 0 || pTemp [ rgbI ] > bdist ) { pTemp [ rgbI ] = bdist ; inverseRGB [ rgbI ] = ( byte ) i ; } } } } } }
Simple inverse color table creation method .
32,723
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 == Float . class ) { return Float . TYPE ; } else if ( pType == Integer . class ) { return Integer . TYPE ; } else if ( pType == Long . class ) { return Long . TYPE ; } else if ( pType == Short . class ) { return Short . TYPE ; } throw new IllegalArgumentException ( "Not a primitive wrapper: " + pType ) ; }
Returns the primitive type for the given wrapper type .
32,724
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 ) { ( ( ImageInputStream ) pInput ) . mark ( ) ; } else if ( pInput instanceof RandomAccessFile ) { pos = ( ( RandomAccessFile ) pInput ) . getFilePointer ( ) ; } else if ( pInput instanceof LittleEndianRandomAccessFile ) { pos = ( ( LittleEndianRandomAccessFile ) pInput ) . getFilePointer ( ) ; } else { return false ; } } catch ( IOException ignore ) { return false ; } } try { byte [ ] magic = new byte [ 8 ] ; pInput . readFully ( magic ) ; return Arrays . equals ( magic , MAGIC ) ; } catch ( IOException ignore ) { } finally { if ( pReset ) { try { if ( pInput instanceof InputStream && ( ( InputStream ) pInput ) . markSupported ( ) ) { ( ( InputStream ) pInput ) . reset ( ) ; } else if ( pInput instanceof ImageInputStream ) { ( ( ImageInputStream ) pInput ) . reset ( ) ; } else if ( pInput instanceof RandomAccessFile ) { ( ( RandomAccessFile ) pInput ) . seek ( pos ) ; } else if ( pInput instanceof LittleEndianRandomAccessFile ) { ( ( LittleEndianRandomAccessFile ) pInput ) . seek ( pos ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return false ; }
It s probably safer to create one version for InputStream and one for File
32,725
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 chain ; }
Gets the SIdChain for the given stream Id
32,726
private void seekToSId ( final int pSId , final long pStreamSize ) throws IOException { long pos ; if ( isShortStream ( pStreamSize ) ) { Entry root = getRootEntry ( ) ; if ( shortStreamSIdChain == null ) { shortStreamSIdChain = getSIdChain ( root . startSId , root . streamSize ) ; } int shortPerSId = sectorSize / shortSectorSize ; int offset = pSId / shortPerSId ; int shortOffset = pSId - ( offset * shortPerSId ) ; pos = HEADER_SIZE + ( shortStreamSIdChain . get ( offset ) * ( long ) sectorSize ) + ( shortOffset * ( long ) shortSectorSize ) ; } else { pos = HEADER_SIZE + pSId * ( long ) sectorSize ; } if ( input instanceof LittleEndianRandomAccessFile ) { ( ( LittleEndianRandomAccessFile ) input ) . seek ( pos ) ; } else if ( input instanceof ImageInputStream ) { ( ( ImageInputStream ) input ) . seek ( pos ) ; } else { ( ( SeekableLittleEndianDataInputStream ) input ) . seek ( pos ) ; } }
Seeks to the start pos for the given stream Id
32,727
protected Object initPropertyValue ( String pValue , String pType , String pFormat ) throws ClassNotFoundException { if ( pValue == null ) { return null ; } if ( ( pType == null ) || pType . equals ( "String" ) || pType . equals ( "java.lang.String" ) ) { return pValue ; } Object value ; if ( pType . equals ( "Date" ) || pType . equals ( "java.util.Date" ) ) { try { if ( pFormat == null ) { value = StringUtil . toDate ( pValue , sDefaultFormat ) ; } else { value = StringUtil . toDate ( pValue , new SimpleDateFormat ( pFormat ) ) ; } } catch ( IllegalArgumentException e ) { throw e ; } return value ; } else if ( pType . equals ( "java.sql.Timestamp" ) ) { try { value = StringUtil . toTimestamp ( pValue ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e . getMessage ( ) ) ; } return value ; } else { int dot = pType . indexOf ( "." ) ; if ( dot < 0 ) { pType = "java.lang." + pType ; } Class cl = Class . forName ( pType ) ; value = createInstance ( cl , pValue ) ; if ( value == null ) { value = invokeStaticMethod ( cl , "valueOf" , pValue ) ; } } return value ; }
Initializes the value of a property .
32,728
private Object createInstance ( Class pClass , Object pParam ) { Object value ; try { Class [ ] param = { pParam . getClass ( ) } ; Object [ ] arg = { pParam } ; Constructor constructor = pClass . getDeclaredConstructor ( param ) ; value = constructor . newInstance ( arg ) ; } catch ( Exception e ) { return null ; } return value ; }
Creates an object from the given class single argument constructor .
32,729
private Object invokeStaticMethod ( Class pClass , String pMethod , Object pParam ) { Object value = null ; try { Class [ ] param = { pParam . getClass ( ) } ; Object [ ] arg = { pParam } ; java . lang . reflect . Method method = pClass . getMethod ( pMethod , param ) ; if ( Modifier . isPublic ( method . getModifiers ( ) ) && Modifier . isStatic ( method . getModifiers ( ) ) ) { value = method . invoke ( null , arg ) ; } } catch ( Exception e ) { return null ; } return value ; }
Creates an object from any given static method given the parameter
32,730
public synchronized String setPropertyFormat ( String pKey , String pFormat ) { 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 .
32,731
private static void insertElement ( Document pDocument , String pName , Object pValue , String pFormat ) { String [ ] names = StringUtil . toStringArray ( pName , "." ) ; String value = null ; if ( pValue != null ) { if ( pValue instanceof Date ) { if ( pFormat != null ) { value = new SimpleDateFormat ( pFormat ) . format ( pValue ) ; } else { value = sDefaultFormat . format ( pValue ) ; } } else { value = String . valueOf ( pValue ) ; } } Element element = pDocument . getDocumentElement ( ) ; for ( int i = 0 ; i < names . length ; i ++ ) { boolean found = false ; NodeList children = element . getElementsByTagName ( PROPERTY ) ; Element child = null ; for ( int j = 0 ; j < children . getLength ( ) ; j ++ ) { child = ( Element ) children . item ( j ) ; if ( names [ i ] . equals ( child . getAttribute ( PROPERTY_NAME ) ) ) { found = true ; element = child ; break ; } } if ( ! found ) { child = pDocument . createElement ( PROPERTY ) ; child . setAttribute ( PROPERTY_NAME , names [ i ] ) ; element . appendChild ( child ) ; element = child ; } if ( ( i + 1 ) == names . length ) { if ( StringUtil . contains ( value , "\n" ) || StringUtil . contains ( value , "\t" ) || StringUtil . contains ( value , "\"" ) || StringUtil . contains ( value , "&" ) || StringUtil . contains ( value , "<" ) || StringUtil . contains ( value , ">" ) ) { Element valueElement = pDocument . createElement ( PROPERTY_VALUE ) ; String className = pValue . getClass ( ) . getName ( ) ; className = StringUtil . replace ( className , "java.lang." , "" ) ; if ( ! DEFAULT_TYPE . equals ( className ) ) { valueElement . setAttribute ( PROPERTY_TYPE , className ) ; } if ( pFormat != null ) { valueElement . setAttribute ( PROPERTY_FORMAT , pFormat ) ; } CDATASection cdata = pDocument . createCDATASection ( value ) ; valueElement . appendChild ( cdata ) ; child . appendChild ( valueElement ) ; } else { child . setAttribute ( PROPERTY_VALUE , value ) ; String className = pValue . getClass ( ) . getName ( ) ; className = StringUtil . replace ( className , "java.lang." , "" ) ; if ( ! DEFAULT_TYPE . equals ( className ) ) { child . setAttribute ( PROPERTY_TYPE , className ) ; } if ( pFormat != null ) { child . setAttribute ( PROPERTY_FORMAT , pFormat ) ; } } } } }
Inserts elements to the given document one by one and creates all its parents if needed .
32,732
public int doEndTag ( ) throws JspException { String body = bodyContent . getString ( ) . trim ( ) ; transform ( new StreamSource ( new ByteArrayInputStream ( body . getBytes ( ) ) ) ) ; return super . doEndTag ( ) ; }
doEndTag implementation that will perform XML Transformation on the body content .
32,733
public void transform ( Source pIn ) throws JspException { try { Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( getSource ( mStylesheetURI ) ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; StreamResult out = new StreamResult ( os ) ; transformer . transform ( pIn , out ) ; pageContext . getOut ( ) . print ( os . toString ( ) ) ; } catch ( MalformedURLException murle ) { throw new JspException ( murle . getMessage ( ) , murle ) ; } catch ( IOException ioe ) { throw new JspException ( ioe . getMessage ( ) , ioe ) ; } catch ( TransformerException te ) { throw new JspException ( "XSLT Trandformation failed: " + te . getMessage ( ) , te ) ; } }
Performs the transformation and writes the result to the JSP writer .
32,734
private StreamSource getSource ( String pURI ) throws IOException , MalformedURLException { if ( pURI != null && pURI . indexOf ( "://" ) < 0 ) { return new StreamSource ( getResourceAsStream ( pURI ) ) ; } return new StreamSource ( pURI ) ; }
Returns a StreamSource object for the given URI
32,735
private static BufferedImage createSolid ( BufferedImage pOriginal , Color pBackground ) { BufferedImage solid = new BufferedImage ( pOriginal . getColorModel ( ) , pOriginal . copyData ( null ) , pOriginal . isAlphaPremultiplied ( ) , null ) ; Graphics2D g = solid . createGraphics ( ) ; try { g . setColor ( pBackground ) ; g . setComposite ( AlphaComposite . DstOver ) ; g . fillRect ( 0 , 0 , pOriginal . getWidth ( ) , pOriginal . getHeight ( ) ) ; } finally { g . dispose ( ) ; } return solid ; }
Creates a copy of the given image with a solid background
32,736
private static void applyAlpha ( BufferedImage pImage , BufferedImage pAlpha ) { for ( int y = 0 ; y < pAlpha . getHeight ( ) ; y ++ ) { for ( int x = 0 ; x < pAlpha . getWidth ( ) ; x ++ ) { if ( ( ( pAlpha . getRGB ( x , y ) >> 24 ) & 0xFF ) < 0x40 ) { pImage . setRGB ( x , y , 0x00FFFFFF ) ; } } } }
Applies the alpha - component of the alpha image to the given image . The given image is modified in place .
32,737
public byte [ ] toByteArray ( ) { byte newBuf [ ] = new byte [ count ] ; System . arraycopy ( buf , 0 , newBuf , 0 , count ) ; return newBuf ; }
Non - synchronized version of toByteArray
32,738
public void writeHeadersTo ( final CacheResponse pResponse ) { String [ ] headers = getHeaderNames ( ) ; for ( String header : headers ) { if ( HTTPCache . HEADER_CACHED_TIME . equals ( header ) ) { continue ; } String [ ] headerValues = getHeaderValues ( header ) ; for ( int i = 0 ; i < headerValues . length ; i ++ ) { String headerValue = headerValues [ i ] ; if ( i == 0 ) { pResponse . setHeader ( header , headerValue ) ; } else { pResponse . addHeader ( header , headerValue ) ; } } } }
Writes the cached headers to the response
32,739
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
32,740
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 .
32,741
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 . println ( segment ) ; } if ( segment . selector == AdobePathSegment . OPEN_SUBPATH_LENGTH_RECORD || segment . selector == AdobePathSegment . CLOSED_SUBPATH_LENGTH_RECORD ) { if ( currentPath != null ) { if ( currentPathLength != currentPath . size ( ) ) { throw new IIOException ( String . format ( "Bad path, expected %d segments, found only %d" , currentPathLength , currentPath . size ( ) ) ) ; } subPaths . add ( currentPath ) ; } currentPath = new ArrayList < AdobePathSegment > ( segment . length ) ; currentPathLength = segment . length ; } else if ( segment . selector == AdobePathSegment . OPEN_SUBPATH_BEZIER_LINKED || segment . selector == AdobePathSegment . OPEN_SUBPATH_BEZIER_UNLINKED || segment . selector == AdobePathSegment . CLOSED_SUBPATH_BEZIER_LINKED || segment . selector == AdobePathSegment . CLOSED_SUBPATH_BEZIER_UNLINKED ) { if ( currentPath == null ) { throw new IIOException ( "Bad path, missing subpath length record" ) ; } if ( currentPath . size ( ) >= currentPathLength ) { throw new IIOException ( String . format ( "Bad path, expected %d segments, found%d" , currentPathLength , currentPath . size ( ) ) ) ; } currentPath . add ( segment ) ; } } if ( currentPath != null ) { if ( currentPathLength != currentPath . size ( ) ) { throw new IIOException ( String . format ( "Bad path, expected %d segments, found only %d" , currentPathLength , currentPath . size ( ) ) ) ; } subPaths . add ( currentPath ) ; } return pathToShape ( subPaths ) ; }
Builds the path .
32,742
private int getFontStyle ( String pStyle ) { if ( pStyle == null || StringUtil . containsIgnoreCase ( pStyle , FONT_STYLE_PLAIN ) ) { return Font . PLAIN ; } int style = Font . PLAIN ; if ( StringUtil . containsIgnoreCase ( pStyle , FONT_STYLE_BOLD ) ) { style |= Font . BOLD ; } if ( StringUtil . containsIgnoreCase ( pStyle , FONT_STYLE_ITALIC ) ) { style |= Font . ITALIC ; } return style ; }
Returns the font style constant .
32,743
private double getAngle ( ServletRequest pRequest ) { double angle = ServletUtil . getDoubleParameter ( pRequest , PARAM_TEXT_ROTATION , 0.0 ) ; String units = pRequest . getParameter ( PARAM_TEXT_ROTATION_UNITS ) ; if ( ! StringUtil . isEmpty ( units ) && ROTATION_DEGREES . equalsIgnoreCase ( units ) ) { angle = Math . toRadians ( angle ) ; } return angle ; }
Gets the angle of rotation from the request .
32,744
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 .
32,745
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 .
32,746
protected int fill ( ) throws IOException { buffer . clear ( ) ; int read = decoder . decode ( in , buffer ) ; if ( read > buffer . capacity ( ) ) { throw new AssertionError ( String . format ( "Decode beyond buffer (%d): %d (using %s decoder)" , buffer . capacity ( ) , read , decoder . getClass ( ) . getName ( ) ) ) ; } buffer . flip ( ) ; if ( read == 0 ) { return - 1 ; } return read ; }
Fills the buffer by decoding data from the underlying input stream .
32,747
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
32,748
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
32,749
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
32,750
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
32,751
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
32,752
private static void log ( PrintStream ps , String header , String owner , String message , Exception ex ) { synchronized ( ps ) { LogStream logStream = new LogStream ( ps ) ; logStream . time = new Date ( System . currentTimeMillis ( ) ) ; logStream . header = header ; logStream . owner = owner ; if ( message != null ) logStream . println ( message ) ; if ( ex != null ) { logStream . println ( ex . getMessage ( ) ) ; ex . printStackTrace ( logStream ) ; } } }
Internal log method
32,753
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 .
32,754
public Object toObject ( String pString , Class pType , String pFormat ) throws ConversionException { if ( StringUtil . isEmpty ( pString ) ) return null ; TimeFormat format ; try { if ( pFormat == null ) { format = TimeFormat . getInstance ( ) ; } else { format = getTimeFormat ( pFormat ) ; } return format . parse ( pString ) ; } catch ( RuntimeException rte ) { throw new ConversionException ( rte ) ; } }
Converts the string to a time using the given format for parsing .
32,755
static Entry readEntry ( final DataInput pInput ) throws IOException { Entry p = new Entry ( ) ; p . read ( pInput ) ; return p ; }
Reads an entry from the input .
32,756
private void read ( final DataInput pInput ) throws IOException { byte [ ] bytes = new byte [ 64 ] ; pInput . readFully ( bytes ) ; int nameLength = pInput . readShort ( ) ; name = new String ( bytes , 0 , nameLength - 2 , Charset . forName ( "UTF-16LE" ) ) ; type = pInput . readByte ( ) ; nodeColor = pInput . readByte ( ) ; prevDId = pInput . readInt ( ) ; nextDId = pInput . readInt ( ) ; rootNodeDId = pInput . readInt ( ) ; if ( pInput . skipBytes ( 20 ) != 20 ) { throw new CorruptDocumentException ( ) ; } createdTimestamp = CompoundDocument . toJavaTimeInMillis ( pInput . readLong ( ) ) ; modifiedTimestamp = CompoundDocument . toJavaTimeInMillis ( pInput . readLong ( ) ) ; startSId = pInput . readInt ( ) ; streamSize = pInput . readInt ( ) ; pInput . readInt ( ) ; }
Reads this entry
32,757
public static Path2D readPath ( final ImageInputStream stream ) throws IOException { notNull ( stream , "stream" ) ; int magic = readMagic ( stream ) ; if ( magic == PSD . RESOURCE_TYPE ) { return buildPathFromPhotoshopResources ( stream ) ; } else if ( magic == PSD . SIGNATURE_8BPS ) { stream . skipBytes ( 26 ) ; long colorModeLen = stream . readUnsignedInt ( ) ; stream . skipBytes ( colorModeLen ) ; long imageResourcesLen = stream . readUnsignedInt ( ) ; return buildPathFromPhotoshopResources ( new SubImageInputStream ( stream , imageResourcesLen ) ) ; } else if ( magic >>> 16 == JPEG . SOI && ( magic & 0xff00 ) == 0xff00 ) { Map < Integer , java . util . List < String > > segmentIdentifiers = new LinkedHashMap < > ( ) ; segmentIdentifiers . put ( JPEG . APP13 , singletonList ( "Photoshop 3.0" ) ) ; List < JPEGSegment > photoshop = JPEGSegmentUtil . readSegments ( stream , segmentIdentifiers ) ; if ( ! photoshop . isEmpty ( ) ) { return buildPathFromPhotoshopResources ( new MemoryCacheImageInputStream ( photoshop . get ( 0 ) . data ( ) ) ) ; } } else if ( magic >>> 16 == TIFF . BYTE_ORDER_MARK_BIG_ENDIAN && ( magic & 0xffff ) == TIFF . TIFF_MAGIC || magic >>> 16 == TIFF . BYTE_ORDER_MARK_LITTLE_ENDIAN && ( magic & 0xffff ) == TIFF . TIFF_MAGIC << 8 ) { CompoundDirectory IFDs = ( CompoundDirectory ) new TIFFReader ( ) . read ( stream ) ; Directory directory = IFDs . getDirectory ( 0 ) ; Entry photoshop = directory . getEntryById ( TIFF . TAG_PHOTOSHOP ) ; if ( photoshop != null ) { return buildPathFromPhotoshopResources ( new ByteArrayImageInputStream ( ( byte [ ] ) photoshop . getValue ( ) ) ) ; } } return null ; }
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 .
32,758
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 .
32,759
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 .
32,760
protected void service ( HttpServletRequest pRequest , HttpServletResponse pResponse ) throws ServletException , IOException { if ( remoteServer == null ) { log ( MESSAGE_REMOTE_SERVER_NOT_CONFIGURED ) ; pResponse . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , MESSAGE_REMOTE_SERVER_NOT_CONFIGURED ) ; return ; } HttpURLConnection remoteConnection = null ; try { String requestURI = createRemoteRequestURI ( pRequest ) ; URL remoteURL = new URL ( pRequest . getScheme ( ) , remoteServer , remotePort , requestURI ) ; String method = pRequest . getMethod ( ) ; remoteConnection = ( HttpURLConnection ) remoteURL . openConnection ( ) ; remoteConnection . setRequestMethod ( method ) ; copyHeadersFromClient ( pRequest , remoteConnection ) ; copyBodyFromClient ( pRequest , remoteConnection ) ; int responseCode = remoteConnection . getResponseCode ( ) ; pResponse . setStatus ( responseCode ) ; copyHeadersToClient ( remoteConnection , pResponse ) ; copyBodyToClient ( remoteConnection , pResponse ) ; } catch ( ConnectException e ) { log ( "Could not connect to remote server." , e ) ; pResponse . sendError ( HttpServletResponse . SC_BAD_GATEWAY , e . getMessage ( ) ) ; } finally { if ( remoteConnection != null ) { remoteConnection . disconnect ( ) ; } } }
Services a single request . Supports HTTP and HTTPS .
32,761
private String createRemoteRequestURI ( HttpServletRequest pRequest ) { StringBuilder requestURI = new StringBuilder ( remotePath ) ; requestURI . append ( pRequest . getPathInfo ( ) ) ; if ( ! StringUtil . isEmpty ( pRequest . getQueryString ( ) ) ) { requestURI . append ( "?" ) ; requestURI . append ( pRequest . getQueryString ( ) ) ; } return requestURI . toString ( ) ; }
Creates the remote request URI based on the incoming request . The URI will include any query strings etc .
32,762
public void setExpiryTime ( long pExpiryTime ) { long oldEexpiryTime = expiryTime ; expiryTime = pExpiryTime ; if ( expiryTime < oldEexpiryTime ) { 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 .
32,763
private synchronized void removeExpiredEntriesSynced ( long pTime ) { if ( pTime > nextExpiryTime ) { long next = Long . MAX_VALUE ; nextExpiryTime = next ; for ( Iterator < Entry < K , V > > iterator = new EntryIterator ( ) ; iterator . hasNext ( ) ; ) { TimedEntry < K , V > entry = ( TimedEntry < K , V > ) iterator . next ( ) ; long expires = entry . expires ( ) ; if ( expires < next ) { next = expires ; } } nextExpiryTime = next ; } }
Okay I guess this do resemble DCL ...
32,764
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 ] [ lonyb ] ; hi |= RTABLE [ i ] [ hinyb ] ; idx += pSrcStep ; } idx = pDstPos ; pDst [ idx ] = ( byte ) ( ( hi >> 24 ) & 0xFF ) ; idx += pDstStep ; if ( idx < pDst . length ) { pDst [ idx ] = ( byte ) ( ( hi >> 16 ) & 0xFF ) ; idx += pDstStep ; if ( idx < pDst . length ) { pDst [ idx ] = ( byte ) ( ( hi >> 8 ) & 0xFF ) ; idx += pDstStep ; if ( idx < pDst . length ) { pDst [ idx ] = ( byte ) ( hi & 0xFF ) ; idx += pDstStep ; } } } if ( idx < pDst . length ) { pDst [ idx ] = ( byte ) ( ( lo >> 24 ) & 0xFF ) ; idx += pDstStep ; if ( idx < pDst . length ) { pDst [ idx ] = ( byte ) ( ( lo >> 16 ) & 0xFF ) ; idx += pDstStep ; if ( idx < pDst . length ) { pDst [ idx ] = ( byte ) ( ( lo >> 8 ) & 0xFF ) ; idx += pDstStep ; if ( idx < pDst . length ) { pDst [ idx ] = ( byte ) ( lo & 0xFF ) ; } } } } }
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 .
32,765
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 ++ ] = rgb [ 1 ] ; data [ offset ++ ] = rgb [ 2 ] ; } }
Simple read routine . Will not correctly handle run length encoding .
32,766
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 . getFraction ( ) * 256.0 / v ) ; rgbe [ 0 ] = ( byte ) ( red * v ) ; rgbe [ 1 ] = ( byte ) ( green * v ) ; rgbe [ 2 ] = ( byte ) ( blue * v ) ; rgbe [ 3 ] = ( byte ) ( fe . getExponent ( ) + 128 ) ; } }
Standard conversion from float pixels to rgbe pixels .
32,767
protected RenderedImage doFilter ( BufferedImage pImage , ServletRequest pRequest , ImageServletResponse pResponse ) { int x = ServletUtil . getIntParameter ( pRequest , PARAM_CROP_X , - 1 ) ; int y = ServletUtil . getIntParameter ( pRequest , PARAM_CROP_Y , - 1 ) ; int width = ServletUtil . getIntParameter ( pRequest , PARAM_CROP_WIDTH , - 1 ) ; int height = ServletUtil . getIntParameter ( pRequest , PARAM_CROP_HEIGHT , - 1 ) ; boolean uniform = ServletUtil . getBooleanParameter ( pRequest , PARAM_CROP_UNIFORM , false ) ; int units = getUnits ( ServletUtil . getParameter ( pRequest , PARAM_CROP_UNITS , null ) ) ; Rectangle bounds = getBounds ( x , y , width , height , units , uniform , pImage ) ; return pImage . getSubimage ( ( int ) bounds . getX ( ) , ( int ) bounds . getY ( ) , ( int ) bounds . getWidth ( ) , ( int ) bounds . getHeight ( ) ) ; }
Reads the image from the requested URL scales it crops it and returns it in the Servlet stream . See above for details on parameters .
32,768
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 .
32,769
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 announced " + "size!" , 0 ) ; } Type type = Type . get ( buffer . get ( ) ) ; if ( type == null ) { throw new ParseException ( "Unknown message ID!" , buffer . position ( ) - 1 ) ; } switch ( type ) { case CHOKE : return ChokeMessage . parse ( buffer . slice ( ) , torrent ) ; case UNCHOKE : return UnchokeMessage . parse ( buffer . slice ( ) , torrent ) ; case INTERESTED : return InterestedMessage . parse ( buffer . slice ( ) , torrent ) ; case NOT_INTERESTED : return NotInterestedMessage . parse ( buffer . slice ( ) , torrent ) ; case HAVE : return HaveMessage . parse ( buffer . slice ( ) , torrent ) ; case BITFIELD : return BitfieldMessage . parse ( buffer . slice ( ) , torrent ) ; case REQUEST : return RequestMessage . parse ( buffer . slice ( ) , torrent ) ; case PIECE : return PieceMessage . parse ( buffer . slice ( ) , torrent ) ; case CANCEL : return CancelMessage . parse ( buffer . slice ( ) , torrent ) ; default : throw new IllegalStateException ( "Message type should have " + "been properly defined by now." ) ; } }
Parse the given buffer into a peer protocol message .
32,770
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 .
32,771
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 .
32,772
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 .
32,773
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 AnnounceResponseMessage ) ) { throw new AnnounceException ( "Unexpected tracker message type " + message . getType ( ) . name ( ) + "!" ) ; } AnnounceResponseMessage response = ( AnnounceResponseMessage ) message ; this . fireAnnounceResponseEvent ( response . getComplete ( ) , response . getIncomplete ( ) , response . getInterval ( ) , hexInfoHash ) ; if ( inhibitEvents ) { return ; } this . fireDiscoveredPeersEvent ( response . getPeers ( ) , hexInfoHash ) ; }
Handle the announce response from the tracker .
32,774
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 .
32,775
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 .
32,776
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 ) ; } if ( this . isFinished ( ) ) { return ; } try { FileUtils . deleteQuietly ( this . target ) ; this . raf . close ( ) ; FileUtils . moveFile ( this . current , this . target ) ; } catch ( Exception ex ) { logger . error ( "An error occurred while moving file to its final location" , ex ) ; if ( this . target . exists ( ) ) { throw new IOException ( "Was unable to delete existing file " + target . getAbsolutePath ( ) , ex ) ; } FileUtils . copyFile ( this . current , this . target ) ; } this . current = this . target ; FileUtils . deleteQuietly ( this . partial ) ; myIsOpen = false ; logger . debug ( "Moved torrent data from {} to {}." , this . partial . getName ( ) , this . target . getName ( ) ) ; } finally { myLock . writeLock ( ) . unlock ( ) ; } }
Move the partial file to its final location .
32,777
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 ) ) ; response . put ( "complete" , new BEValue ( complete ) ) ; response . put ( "incomplete" , new BEValue ( incomplete ) ) ; if ( hexInfoHash != null ) { response . put ( "torrentIdentifier" , new BEValue ( hexInfoHash ) ) ; } ByteBuffer data = ByteBuffer . allocate ( peers . size ( ) * 6 ) ; for ( Peer peer : peers ) { byte [ ] ip = peer . getRawIp ( ) ; if ( ip == null || ip . length != 4 ) { continue ; } data . put ( ip ) ; data . putShort ( ( short ) peer . getPort ( ) ) ; } response . put ( "peers" , new BEValue ( Arrays . copyOf ( data . array ( ) , data . position ( ) ) ) ) ; return new HTTPAnnounceResponseMessage ( BEncoder . bencode ( response ) , interval , complete , incomplete , peers , hexInfoHash ) ; }
Craft a compact announce response message with a torrent identifier .
32,778
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 ( FileStorage file : this . files ) { if ( file . offset ( ) >= offset + length ) { break ; } if ( file . offset ( ) + file . size ( ) < offset ) { continue ; } long position = offset - file . offset ( ) ; position = position > 0 ? position : 0 ; long size = Math . min ( file . size ( ) - position , length - bytes ) ; selected . add ( new FileOffset ( file , position , size ) ) ; bytes += size ; } if ( selected . size ( ) == 0 || bytes < length ) { throw new IllegalStateException ( "Buffer underrun (only got " + bytes + " out of " + length + " byte(s) requested)!" ) ; } return selected ; }
Select the group of files impacted by an operation .
32,779
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 .
32,780
protected void close ( ) { this . stop = true ; if ( this . socket != null && ! this . socket . isClosed ( ) ) { this . socket . close ( ) ; } }
Close this announce connection .
32,781
private void validateTrackerResponse ( TrackerMessage message ) throws AnnounceException { if ( message instanceof ErrorMessage ) { throw new AnnounceException ( ( ( ErrorMessage ) message ) . getReason ( ) ) ; } if ( message instanceof UDPTrackerMessage && ( ( ( UDPTrackerMessage ) message ) . getTransactionId ( ) != this . transactionId ) ) { throw new AnnounceException ( "Invalid transaction ID!" ) ; } }
Validates an incoming tracker message .
32,782
private void handleTrackerConnectResponse ( TrackerMessage message ) throws AnnounceException { this . validateTrackerResponse ( message ) ; if ( ! ( message instanceof ConnectionResponseMessage ) ) { throw new AnnounceException ( "Unexpected tracker message type " + message . getType ( ) . name ( ) + "!" ) ; } UDPConnectResponseMessage connectResponse = ( UDPConnectResponseMessage ) message ; this . connectionId = connectResponse . getConnectionId ( ) ; Calendar now = Calendar . getInstance ( ) ; now . add ( Calendar . MINUTE , 1 ) ; this . connectionExpiration = now . getTime ( ) ; }
Handles the tracker connect response message .
32,783
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 .
32,784
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 ) ; try { DatagramPacket p = new DatagramPacket ( new byte [ UDP_PACKET_LENGTH ] , UDP_PACKET_LENGTH ) ; this . socket . receive ( p ) ; return ByteBuffer . wrap ( p . getData ( ) , 0 , p . getLength ( ) ) ; } catch ( SocketTimeoutException ste ) { throw ste ; } }
Receive a UDP packet from the tracker .
32,785
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 . toString ( ) ) ; } }
Returns this BEValue as a String interpreted with the specified encoding .
32,786
public Number getNumber ( ) throws InvalidBEncodingException { try { return ( Number ) this . value ; } catch ( ClassCastException cce ) { throw new InvalidBEncodingException ( cce . toString ( ) ) ; } }
Returns this BEValue as a Number .
32,787
@ 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 .
32,788
@ 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 .
32,789
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 > ( ) { { try { add ( new InetSocketAddress ( InetAddress . getByAddress ( new byte [ 4 ] ) , myPort ) ) ; } catch ( Exception ex ) { } try { add ( new InetSocketAddress ( InetAddress . getLocalHost ( ) , myPort ) ) ; } catch ( Exception ex ) { } try { add ( new InetSocketAddress ( InetAddress . getByName ( new URL ( getAnnounceUrl ( ) ) . getHost ( ) ) , myPort ) ) ; } catch ( Exception ex ) { } } } ; boolean started = false ; for ( SocketAddress address : tries ) { try { if ( ( myBoundAddress = connection . connect ( address ) ) != null ) { logger . info ( "Started torrent tracker on {}" , address ) ; started = true ; break ; } } catch ( IOException ioe ) { logger . info ( "Can't start the tracker using address{} : " , address . toString ( ) , ioe . getMessage ( ) ) ; } } if ( ! started ) { logger . error ( "Cannot start tracker on port {}. Stopping now..." , myPort ) ; stop ( ) ; return ; } if ( startPeerCleaningThread ) { if ( myPeerCollectorThread == null || ! myPeerCollectorThread . isAlive ( ) || myPeerCollectorThread . getState ( ) != Thread . State . NEW ) { myPeerCollectorThread = new PeerCollectorThread ( myTorrentsRepository ) ; } myPeerCollectorThread . setName ( "peer-peerCollectorThread:" + myPort ) ; myPeerCollectorThread . start ( ) ; } }
Start the tracker thread .
32,790
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 < HTTPTrackerMessage > ( ) ; for ( final Peer address : adresses ) { final URL target = encodeAnnounceToURL ( event , torrentInfo , address ) ; try { sendAnnounce ( target , "GET" , new ResponseParser ( ) { public void parse ( InputStream inputStream , int responseCode ) throws IOException , MessageValidationException { if ( responseCode != 200 ) { logger . info ( "received not http 200 code from tracker for request " + target ) ; return ; } trackerResponses . add ( HTTPTrackerMessage . parse ( inputStream ) ) ; } } ) ; } catch ( ConnectException e ) { throw new AnnounceException ( e . getMessage ( ) , e ) ; } } if ( trackerResponses . size ( ) > 0 ) { final HTTPTrackerMessage message = trackerResponses . get ( 0 ) ; this . handleTrackerAnnounceResponse ( message , inhibitEvents , torrentInfo . getHexInfoHash ( ) ) ; } }
Build send and process a tracker announce request .
32,791
private HTTPAnnounceRequestMessage buildAnnounceRequest ( AnnounceRequestMessage . RequestEvent event , AnnounceableInformation torrentInfo , Peer peer ) throws IOException , MessageValidationException { final long uploaded = torrentInfo . getUploaded ( ) ; final long downloaded = torrentInfo . getDownloaded ( ) ; final long left = torrentInfo . getLeft ( ) ; return HTTPAnnounceRequestMessage . craft ( torrentInfo . getInfoHash ( ) , peer . getPeerIdArray ( ) , peer . getPort ( ) , uploaded , downloaded , left , true , false , event , peer . getIp ( ) , AnnounceRequestMessage . DEFAULT_NUM_WANT ) ; }
Build the announce request tracker message .
32,792
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 . encode ( new String ( this . getInfoHash ( ) , Constants . BYTE_ENCODING ) , Constants . BYTE_ENCODING ) ) . append ( "&peer_id=" ) . append ( URLEncoder . encode ( new String ( this . getPeerId ( ) , Constants . BYTE_ENCODING ) , Constants . BYTE_ENCODING ) ) . append ( "&port=" ) . append ( this . getPort ( ) ) . append ( "&uploaded=" ) . append ( this . getUploaded ( ) ) . append ( "&downloaded=" ) . append ( this . getDownloaded ( ) ) . append ( "&left=" ) . append ( this . getLeft ( ) ) . append ( "&compact=" ) . append ( this . isCompact ( ) ? 1 : 0 ) . append ( "&no_peer_id=" ) . append ( this . canOmitPeerId ( ) ? 1 : 0 ) ; if ( this . getEvent ( ) != null && ! RequestEvent . NONE . equals ( this . getEvent ( ) ) ) { url . append ( "&event=" ) . append ( this . getEvent ( ) . getEventName ( ) ) ; } if ( this . getIp ( ) != null ) { url . append ( "&ip=" ) . append ( this . getIp ( ) ) ; } return new URL ( url . toString ( ) ) ; }
Build the announce request URL for the given tracker announce URL .
32,793
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 .
32,794
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 .
32,795
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 ( 'h' , "help" ) ; CmdLineParser . Option port = parser . addIntegerOption ( 'p' , "port" ) ; try { parser . parse ( args ) ; } catch ( CmdLineParser . OptionException oe ) { System . err . println ( oe . getMessage ( ) ) ; usage ( System . err ) ; System . exit ( 1 ) ; } if ( Boolean . TRUE . equals ( ( Boolean ) parser . getOptionValue ( help ) ) ) { usage ( System . out ) ; System . exit ( 0 ) ; } Integer portValue = ( Integer ) parser . getOptionValue ( port , Integer . valueOf ( Tracker . DEFAULT_TRACKER_PORT ) ) ; String [ ] otherArgs = parser . getRemainingArgs ( ) ; if ( otherArgs . length > 1 ) { usage ( System . err ) ; System . exit ( 1 ) ; } String directory = otherArgs . length > 0 ? otherArgs [ 0 ] : "." ; FilenameFilter filter = new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ".torrent" ) ; } } ; try { Tracker t = new Tracker ( portValue ) ; File parent = new File ( directory ) ; for ( File f : parent . listFiles ( filter ) ) { logger . info ( "Loading torrent from " + f . getName ( ) ) ; t . announce ( TrackedTorrent . load ( f ) ) ; } logger . info ( "Starting tracker with {} announced torrents..." , t . getTrackedTorrents ( ) . size ( ) ) ; t . start ( true ) ; } catch ( Exception e ) { logger . error ( "{}" , e . getMessage ( ) , e ) ; System . exit ( 2 ) ; } }
Main function to start a tracker .
32,796
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 ( 'h' , "help" ) ; CmdLineParser . Option output = parser . addStringOption ( 'o' , "output" ) ; CmdLineParser . Option iface = parser . addStringOption ( 'i' , "iface" ) ; CmdLineParser . Option seedTime = parser . addIntegerOption ( 's' , "seed" ) ; CmdLineParser . Option maxUpload = parser . addDoubleOption ( 'u' , "max-upload" ) ; CmdLineParser . Option maxDownload = parser . addDoubleOption ( 'd' , "max-download" ) ; try { parser . parse ( args ) ; } catch ( CmdLineParser . OptionException oe ) { System . err . println ( oe . getMessage ( ) ) ; usage ( System . err ) ; System . exit ( 1 ) ; } if ( Boolean . TRUE . equals ( ( Boolean ) parser . getOptionValue ( help ) ) ) { usage ( System . out ) ; System . exit ( 0 ) ; } String outputValue = ( String ) parser . getOptionValue ( output , DEFAULT_OUTPUT_DIRECTORY ) ; String ifaceValue = ( String ) parser . getOptionValue ( iface ) ; int seedTimeValue = ( Integer ) parser . getOptionValue ( seedTime , - 1 ) ; String [ ] otherArgs = parser . getRemainingArgs ( ) ; if ( otherArgs . length != 1 ) { usage ( System . err ) ; System . exit ( 1 ) ; } SimpleClient client = new SimpleClient ( ) ; try { Inet4Address iPv4Address = getIPv4Address ( ifaceValue ) ; File torrentFile = new File ( otherArgs [ 0 ] ) ; File outputFile = new File ( outputValue ) ; client . downloadTorrent ( torrentFile . getAbsolutePath ( ) , outputFile . getAbsolutePath ( ) , iPv4Address ) ; if ( seedTimeValue > 0 ) { Thread . sleep ( seedTimeValue * 1000 ) ; } } catch ( Exception e ) { logger . error ( "Fatal error: {}" , e . getMessage ( ) , e ) ; System . exit ( 2 ) ; } finally { client . stop ( ) ; } }
Main client entry point for stand - alone operation .
32,797
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 .
32,798
public synchronized void markCompleted ( Piece piece ) { if ( this . completedPieces . get ( piece . getIndex ( ) ) ) { return ; } myTorrentStatistic . addLeft ( - piece . size ( ) ) ; this . completedPieces . set ( piece . getIndex ( ) ) ; if ( completedPieces . cardinality ( ) == getPiecesCount ( ) ) { logger . info ( "all pieces are received for torrent {}. Validating..." , this ) ; } }
Mark a piece as completed decrementing the piece size in bytes from our left bytes to download counter .
32,799
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 . createTrackerClient ( myPeers , defaultTrackerURI ) ; myDefaultTracker . register ( listener ) ; this . clients . put ( defaultTrackerURI . toString ( ) , myDefaultTracker ) ; } catch ( Exception e ) { } } else { myDefaultTracker = null ; } this . stop = false ; this . forceStop = false ; if ( this . thread == null || ! this . thread . isAlive ( ) ) { this . thread = new Thread ( this ) ; this . thread . setName ( "torrent tracker announce thread" ) ; this . thread . start ( ) ; } }
Start the announce request thread .