idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
32,600 | private static void writeRequestHeaders ( OutputStream pOut , URL pURL , String pMethod , Properties pProps , boolean pUsingProxy , PasswordAuthentication pAuth , String pAuthType ) { PrintWriter out = new PrintWriter ( pOut , true ) ; if ( ! pUsingProxy ) { out . println ( pMethod + " " + ( ! StringUtil . isEmpty ( pURL . getPath ( ) ) ? pURL . getPath ( ) : "/" ) + ( ( pURL . getQuery ( ) != null ) ? "?" + pURL . getQuery ( ) : "" ) + " HTTP/1.1" ) ; out . println ( "Host: " + pURL . getHost ( ) + ( ( pURL . getPort ( ) != - 1 ) ? ":" + pURL . getPort ( ) : "" ) ) ; } else { out . println ( pMethod + " " + pURL . getProtocol ( ) + "://" + pURL . getHost ( ) + ( ( pURL . getPort ( ) != - 1 ) ? ":" + pURL . getPort ( ) : "" ) + pURL . getPath ( ) + ( ( pURL . getQuery ( ) != null ) ? "?" + pURL . getQuery ( ) : "" ) + " HTTP/1.1" ) ; } if ( pAuth != null ) { byte [ ] userPass = ( pAuth . getUserName ( ) + ":" + new String ( pAuth . getPassword ( ) ) ) . getBytes ( ) ; out . println ( "Authorization: " + pAuthType + " " + BASE64 . encode ( userPass ) ) ; } for ( Map . Entry < Object , Object > property : pProps . entrySet ( ) ) { out . println ( property . getKey ( ) + ": " + property . getValue ( ) ) ; } out . println ( ) ; } | Writes the HTTP request headers for HTTP GET method . |
32,601 | private static int findEndOfHeader ( byte [ ] pBytes , int pEnd ) { byte [ ] header = HTTP_HEADER_END . getBytes ( ) ; for ( int i = 0 ; i < pEnd - 4 ; i ++ ) { if ( ( pBytes [ i ] == header [ 0 ] ) && ( pBytes [ i + 1 ] == header [ 1 ] ) && ( pBytes [ i + 2 ] == header [ 2 ] ) && ( pBytes [ i + 3 ] == header [ 3 ] ) ) { return i + 4 ; } } if ( ( pEnd - 1 >= 0 ) && ( pBytes [ pEnd - 1 ] == header [ 0 ] ) ) { return - 2 ; } else if ( ( pEnd - 2 >= 0 ) && ( pBytes [ pEnd - 2 ] == header [ 0 ] ) && ( pBytes [ pEnd - 1 ] == header [ 1 ] ) ) { return - 3 ; } else if ( ( pEnd - 3 >= 0 ) && ( pBytes [ pEnd - 3 ] == header [ 0 ] ) && ( pBytes [ pEnd - 2 ] == header [ 1 ] ) && ( pBytes [ pEnd - 1 ] == header [ 2 ] ) ) { return - 4 ; } return - 1 ; } | Finds the end of the HTTP response header in an array of bytes . |
32,602 | private static InputStream detatchResponseHeader ( BufferedInputStream pIS ) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream ( ) ; pIS . mark ( BUF_SIZE ) ; byte [ ] buffer = new byte [ BUF_SIZE ] ; int length ; int headerEnd ; while ( ( length = pIS . read ( buffer ) ) != - 1 ) { headerEnd = findEndOfHeader ( buffer , length ) ; if ( headerEnd >= 0 ) { bytes . write ( buffer , 0 , headerEnd ) ; pIS . reset ( ) ; pIS . skip ( headerEnd ) ; break ; } else if ( headerEnd < - 1 ) { bytes . write ( buffer , 0 , length - 4 ) ; pIS . reset ( ) ; pIS . skip ( length - 4 ) ; } else { bytes . write ( buffer , 0 , length ) ; } pIS . mark ( BUF_SIZE ) ; } return new ByteArrayInputStream ( bytes . toByteArray ( ) ) ; } | Reads the header part of the response and copies it to a different InputStream . |
32,603 | private static Properties parseHeaderFields ( String [ ] pHeaders ) { Properties headers = new Properties ( ) ; int split ; String field ; String value ; for ( String header : pHeaders ) { if ( ( split = header . indexOf ( ":" ) ) > 0 ) { field = header . substring ( 0 , split ) ; value = header . substring ( split + 1 ) ; headers . setProperty ( StringUtil . toLowerCase ( field ) , value . trim ( ) ) ; } } return headers ; } | Pareses the response header fields . |
32,604 | private static String [ ] parseResponseHeader ( InputStream pIS ) throws IOException { List < String > headers = new ArrayList < String > ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( pIS ) ) ; String header ; while ( ( header = in . readLine ( ) ) != null ) { headers . add ( header ) ; } return headers . toArray ( new String [ headers . size ( ) ] ) ; } | Parses the response headers . |
32,605 | public int filterRGB ( int pX , int pY , int pARGB ) { int r = pARGB >> 16 & 0xFF ; int g = pARGB >> 8 & 0xFF ; int b = pARGB & 0xFF ; int gray = ( 222 * r + 707 * g + 71 * b ) / 1000 ; if ( range != 1.0f ) { gray = low + ( int ) ( gray * range ) ; } return ( pARGB & 0xFF000000 ) | ( gray << 16 ) | ( gray << 8 ) | gray ; } | Filters one pixel using ITU color - conversion . |
32,606 | public final int decode ( final InputStream stream , final ByteBuffer buffer ) throws IOException { if ( buffer . capacity ( ) < row . length ) { throw new AssertionError ( "This decoder needs a buffer.capacity() of at least one row" ) ; } while ( buffer . remaining ( ) >= row . length && srcY >= 0 ) { if ( dstX == 0 && srcY == dstY ) { decodeRow ( stream ) ; } int length = Math . min ( row . length - ( dstX * bitsPerSample ) / 8 , buffer . remaining ( ) ) ; buffer . put ( row , 0 , length ) ; dstX += ( length * 8 ) / bitsPerSample ; if ( dstX == ( row . length * 8 ) / bitsPerSample ) { dstX = 0 ; dstY ++ ; if ( srcX > dstX ) { Arrays . fill ( row , 0 , ( srcX * bitsPerSample ) / 8 , ( byte ) 0 ) ; } if ( srcY > dstY ) { Arrays . fill ( row , ( byte ) 0 ) ; } } } return buffer . position ( ) ; } | Decodes as much data as possible from the stream into the buffer . |
32,607 | public void init ( ) throws ServletException { String uploadDirParam = getInitParameter ( "uploadDir" ) ; if ( ! StringUtil . isEmpty ( uploadDirParam ) ) { try { URL uploadDirURL = getServletContext ( ) . getResource ( uploadDirParam ) ; uploadDir = FileUtil . toFile ( uploadDirURL ) ; } catch ( MalformedURLException e ) { throw new ServletException ( e . getMessage ( ) , e ) ; } } if ( uploadDir == null ) { uploadDir = ServletUtil . getTempDir ( getServletContext ( ) ) ; } } | This method is called by the server before the filter goes into service and here it determines the file upload directory . |
32,608 | private static boolean copyDir ( File pFrom , File pTo , boolean pOverWrite ) throws IOException { if ( pTo . exists ( ) && ! pTo . isDirectory ( ) ) { throw new IOException ( "A directory may only be copied to another directory, not to a file" ) ; } pTo . mkdirs ( ) ; boolean allOkay = true ; File [ ] files = pFrom . listFiles ( ) ; for ( File file : files ) { if ( ! copy ( file , new File ( pTo , file . getName ( ) ) , pOverWrite ) ) { allOkay = false ; } } return allOkay ; } | Copies a directory recursively . If the destination folder does not exist it is created |
32,609 | public static boolean copy ( InputStream pFrom , OutputStream pTo ) throws IOException { Validate . notNull ( pFrom , "from" ) ; Validate . notNull ( pTo , "to" ) ; InputStream in = new BufferedInputStream ( pFrom , BUF_SIZE * 2 ) ; OutputStream out = new BufferedOutputStream ( pTo , BUF_SIZE * 2 ) ; byte [ ] buffer = new byte [ BUF_SIZE ] ; int count ; while ( ( count = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , count ) ; } out . flush ( ) ; return true ; } | Copies all data from one stream to another . The data is copied from the fromStream to the toStream using buffered streams for efficiency . |
32,610 | public static String getDirectoryname ( final String pPath , final char pSeparator ) { int index = pPath . lastIndexOf ( pSeparator ) ; if ( index < 0 ) { return "" ; } return pPath . substring ( 0 , index ) ; } | Extracts the directory path without the filename from a complete filename path . |
32,611 | public static String getFilename ( final String pPath , final char pSeparator ) { int index = pPath . lastIndexOf ( pSeparator ) ; if ( index < 0 ) { return pPath ; } return pPath . substring ( index + 1 ) ; } | Extracts the filename of a complete filename path . |
32,612 | public static boolean isEmpty ( File pFile ) { if ( pFile . isDirectory ( ) ) { return ( pFile . list ( ) . length == 0 ) ; } return ( pFile . length ( ) == 0 ) ; } | Tests if a file or directory has no content . A file is empty if it has a length of 0L . A non - existing file is also considered empty . A directory is considered empty if it contains no files . |
32,613 | public static String getTempDir ( ) { synchronized ( FileUtil . class ) { if ( TEMP_DIR == null ) { String tmpDir = System . getProperty ( "java.io.tmpdir" ) ; if ( StringUtil . isEmpty ( tmpDir ) ) { if ( new File ( "/temp" ) . exists ( ) ) { tmpDir = "/temp" ; } else { tmpDir = "/tmp" ; } } TEMP_DIR = tmpDir ; } } return TEMP_DIR ; } | Gets the default temp directory for the system . |
32,614 | public static byte [ ] read ( File pFile ) throws IOException { if ( ! pFile . exists ( ) ) { throw new FileNotFoundException ( pFile . toString ( ) ) ; } byte [ ] bytes = new byte [ ( int ) pFile . length ( ) ] ; InputStream in = null ; try { in = new BufferedInputStream ( new FileInputStream ( pFile ) , BUF_SIZE * 2 ) ; int off = 0 ; int len ; while ( ( len = in . read ( bytes , off , in . available ( ) ) ) != - 1 && ( off < bytes . length ) ) { off += len ; } } finally { close ( in ) ; } return bytes ; } | Gets the contents of the given file as a byte array . |
32,615 | public static byte [ ] read ( InputStream pInput ) throws IOException { ByteArrayOutputStream bytes = new FastByteArrayOutputStream ( BUF_SIZE ) ; copy ( pInput , bytes ) ; return bytes . toByteArray ( ) ; } | Reads all data from the input stream to a byte array . |
32,616 | public static boolean write ( File pFile , byte [ ] pData ) throws IOException { boolean success = false ; OutputStream out = null ; try { out = new BufferedOutputStream ( new FileOutputStream ( pFile ) ) ; success = write ( out , pData ) ; } finally { close ( out ) ; } return success ; } | Writes the contents from a byte array to a file . |
32,617 | public static boolean delete ( final File pFile , final boolean pForce ) throws IOException { if ( pForce && pFile . isDirectory ( ) ) { return deleteDir ( pFile ) ; } return pFile . exists ( ) && pFile . delete ( ) ; } | Deletes the specified file . |
32,618 | private static boolean fixProfileXYZTag ( final ICC_Profile profile , final int tagSignature ) { byte [ ] data = profile . getData ( tagSignature ) ; if ( data != null && intFromBigEndian ( data , 0 ) == CORBIS_RGB_ALTERNATE_XYZ ) { intToBigEndian ( ICC_Profile . icSigXYZData , data , 0 ) ; profile . setData ( tagSignature , data ) ; return true ; } return false ; } | Fixes problematic XYZ tags in Corbis RGB profile . |
32,619 | private static void buildYCCtoRGBtable ( ) { if ( ColorSpaces . DEBUG ) { System . err . println ( "Building YCC conversion table" ) ; } for ( int i = 0 , x = - CENTERJSAMPLE ; i <= MAXJSAMPLE ; i ++ , x ++ ) { Cr_R_LUT [ i ] = ( int ) ( ( 1.40200 * ( 1 << SCALEBITS ) + 0.5 ) * x + ONE_HALF ) >> SCALEBITS ; Cb_B_LUT [ i ] = ( int ) ( ( 1.77200 * ( 1 << SCALEBITS ) + 0.5 ) * x + ONE_HALF ) >> SCALEBITS ; Cr_G_LUT [ i ] = - ( int ) ( 0.71414 * ( 1 << SCALEBITS ) + 0.5 ) * x ; Cb_G_LUT [ i ] = - ( int ) ( ( 0.34414 ) * ( 1 << SCALEBITS ) + 0.5 ) * x + ONE_HALF ; } } | Initializes tables for YCC - > RGB color space conversion . |
32,620 | private int getOparamCountFromRequest ( HttpServletRequest pRequest ) { Integer count = ( Integer ) pRequest . getAttribute ( COUNTER ) ; if ( count == null ) { count = new Integer ( 0 ) ; } else { count = new Integer ( count . intValue ( ) + 1 ) ; } pRequest . setAttribute ( COUNTER , count ) ; return count . intValue ( ) ; } | Gets the current oparam count for this request |
32,621 | private static int getFilterType ( RenderingHints pHints ) { if ( pHints == null ) { return FILTER_UNDEFINED ; } if ( pHints . containsKey ( KEY_RESAMPLE_INTERPOLATION ) ) { Object value = pHints . get ( KEY_RESAMPLE_INTERPOLATION ) ; if ( ! KEY_RESAMPLE_INTERPOLATION . isCompatibleValue ( value ) ) { throw new IllegalArgumentException ( value + " incompatible with key " + KEY_RESAMPLE_INTERPOLATION ) ; } return value != null ? ( ( Value ) value ) . getFilterType ( ) : FILTER_UNDEFINED ; } else if ( RenderingHints . VALUE_INTERPOLATION_NEAREST_NEIGHBOR . equals ( pHints . get ( RenderingHints . KEY_INTERPOLATION ) ) || ( ! pHints . containsKey ( RenderingHints . KEY_INTERPOLATION ) && ( RenderingHints . VALUE_RENDER_SPEED . equals ( pHints . get ( RenderingHints . KEY_RENDERING ) ) || RenderingHints . VALUE_COLOR_RENDER_SPEED . equals ( pHints . get ( RenderingHints . KEY_COLOR_RENDERING ) ) ) ) ) { return FILTER_POINT ; } else if ( RenderingHints . VALUE_INTERPOLATION_BILINEAR . equals ( pHints . get ( RenderingHints . KEY_INTERPOLATION ) ) ) { return FILTER_TRIANGLE ; } else if ( RenderingHints . VALUE_INTERPOLATION_BICUBIC . equals ( pHints . get ( RenderingHints . KEY_INTERPOLATION ) ) ) { return FILTER_QUADRATIC ; } else if ( RenderingHints . VALUE_RENDER_QUALITY . equals ( pHints . get ( RenderingHints . KEY_RENDERING ) ) || RenderingHints . VALUE_COLOR_RENDER_QUALITY . equals ( pHints . get ( RenderingHints . KEY_COLOR_RENDERING ) ) ) { return FILTER_MITCHELL ; } return FILTER_UNDEFINED ; } | Gets the filter type specified by the given hints . |
32,622 | public String getColumn ( String pProperty ) { if ( mPropertiesMap == null || pProperty == null ) return null ; return ( String ) mPropertiesMap . get ( pProperty ) ; } | Gets the column for a given property . |
32,623 | public String getTable ( String pProperty ) { String table = getColumn ( pProperty ) ; if ( table != null ) { int dotIdx = 0 ; if ( ( dotIdx = table . lastIndexOf ( "." ) ) >= 0 ) table = table . substring ( 0 , dotIdx ) ; else return null ; } return table ; } | Gets the table name for a given property . |
32,624 | public String getProperty ( String pColumn ) { if ( mColumnMap == null || pColumn == null ) return null ; String property = ( String ) mColumnMap . get ( pColumn ) ; int dotIdx = 0 ; if ( property == null && ( dotIdx = pColumn . lastIndexOf ( "." ) ) >= 0 ) property = ( String ) mColumnMap . get ( pColumn . substring ( dotIdx + 1 ) ) ; return property ; } | Gets the property for a given database column . If the column incudes table qualifier the table qualifier is removed . |
32,625 | public synchronized Object [ ] mapObjects ( ResultSet pRSet ) throws SQLException { Vector result = new Vector ( ) ; ResultSetMetaData meta = pRSet . getMetaData ( ) ; int cols = meta . getColumnCount ( ) ; String [ ] colNames = new String [ cols ] ; for ( int i = 0 ; i < cols ; i ++ ) { colNames [ i ] = meta . getColumnName ( i + 1 ) ; } while ( pRSet . next ( ) ) { Object obj = null ; try { obj = mInstanceClass . newInstance ( ) ; } catch ( IllegalAccessException iae ) { mLog . logError ( iae ) ; } catch ( InstantiationException ie ) { mLog . logError ( ie ) ; } for ( int i = 0 ; i < cols ; i ++ ) { String property = ( String ) mColumnMap . get ( colNames [ i ] ) ; if ( property != null ) { mapColumnProperty ( pRSet , i + 1 , property , obj ) ; } } result . addElement ( obj ) ; } return result . toArray ( ( Object [ ] ) Array . newInstance ( mInstanceClass , result . size ( ) ) ) ; } | Maps each row of the given result set to an object ot this OM s type . |
32,626 | String buildIdentitySQL ( String [ ] pKeys ) { mTables = new Hashtable ( ) ; mColumns = new Vector ( ) ; mColumns . addElement ( getPrimaryKey ( ) ) ; tableJoins ( null , false ) ; for ( int i = 0 ; i < pKeys . length ; i ++ ) { tableJoins ( getColumn ( pKeys [ i ] ) , true ) ; } return "SELECT " + getPrimaryKey ( ) + " " + buildFromClause ( ) + buildWhereClause ( ) ; } | Creates a SQL query string to get the primary keys for this ObjectMapper . |
32,627 | public String buildSQL ( ) { mTables = new Hashtable ( ) ; mColumns = new Vector ( ) ; String key = null ; for ( Enumeration keys = mPropertiesMap . keys ( ) ; keys . hasMoreElements ( ) ; ) { key = ( String ) keys . nextElement ( ) ; String column = ( String ) mPropertiesMap . get ( key ) ; mColumns . addElement ( column ) ; tableJoins ( column , false ) ; } return buildSelectClause ( ) + buildFromClause ( ) + buildWhereClause ( ) ; } | Creates a SQL query string to get objects for this ObjectMapper . |
32,628 | private String buildSelectClause ( ) { StringBuilder sqlBuf = new StringBuilder ( ) ; sqlBuf . append ( "SELECT " ) ; String column = null ; for ( Enumeration select = mColumns . elements ( ) ; select . hasMoreElements ( ) ; ) { column = ( String ) select . nextElement ( ) ; String mapType = ( String ) mMapTypes . get ( getProperty ( column ) ) ; if ( mapType == null || mapType . equals ( DIRECTMAP ) ) { sqlBuf . append ( column ) ; sqlBuf . append ( select . hasMoreElements ( ) ? ", " : " " ) ; } } return sqlBuf . toString ( ) ; } | Builds a SQL SELECT clause from the columns Vector |
32,629 | private void tableJoins ( String pColumn , boolean pWhereJoin ) { String join = null ; String table = null ; if ( pColumn == null ) { join = getIdentityJoin ( ) ; table = getTable ( getProperty ( getPrimaryKey ( ) ) ) ; } else { int dotIndex = - 1 ; if ( ( dotIndex = pColumn . lastIndexOf ( "." ) ) <= 0 ) { return ; } table = pColumn . substring ( 0 , dotIndex ) ; String property = ( String ) getProperty ( pColumn ) ; if ( property != null ) { String mapType = ( String ) mMapTypes . get ( property ) ; if ( ! pWhereJoin && mapType != null && ! mapType . equals ( DIRECTMAP ) ) { return ; } join = ( String ) mJoins . get ( property ) ; } } if ( mTables . get ( table ) == null ) { if ( join != null ) { mTables . put ( table , join ) ; StringTokenizer tok = new StringTokenizer ( join , "= " ) ; String next = null ; while ( tok . hasMoreElements ( ) ) { next = tok . nextToken ( ) ; if ( next . equals ( "AND" ) || next . equals ( "OR" ) || next . equals ( "NOT" ) || next . equals ( "IN" ) ) { continue ; } tableJoins ( next , false ) ; } } else { join = "" ; mTables . put ( table , join ) ; } } } | Finds tables used in mappings and joins and adds them to the tables Hashtable with the table name as key and the join as value . |
32,630 | public final void seek ( long pPosition ) throws IOException { checkOpen ( ) ; if ( pPosition < flushedPosition ) { throw new IndexOutOfBoundsException ( "position < flushedPosition!" ) ; } seekImpl ( pPosition ) ; position = pPosition ; } | probably a good idea to extract a delegate .. ? |
32,631 | public static String getMIMEType ( final String pFileExt ) { List < String > types = sExtToMIME . get ( StringUtil . toLowerCase ( pFileExt ) ) ; return ( types == null || types . isEmpty ( ) ) ? null : types . get ( 0 ) ; } | Returns the default MIME type for the given file extension . |
32,632 | public static List < String > getMIMETypes ( final String pFileExt ) { List < String > types = sExtToMIME . get ( StringUtil . toLowerCase ( pFileExt ) ) ; return maskNull ( types ) ; } | Returns all MIME types for the given file extension . |
32,633 | private static List < String > getExtensionForWildcard ( final String pMIME ) { final String family = pMIME . substring ( 0 , pMIME . length ( ) - 1 ) ; Set < String > extensions = new LinkedHashSet < String > ( ) ; for ( Map . Entry < String , List < String > > mimeToExt : sMIMEToExt . entrySet ( ) ) { if ( "*/" . equals ( family ) || mimeToExt . getKey ( ) . startsWith ( family ) ) { extensions . addAll ( mimeToExt . getValue ( ) ) ; } } return Collections . unmodifiableList ( new ArrayList < String > ( extensions ) ) ; } | Gets all extensions for a wildcard MIME type |
32,634 | private static List < String > maskNull ( List < String > pTypes ) { return ( pTypes == null ) ? Collections . < String > emptyList ( ) : pTypes ; } | Returns the list or empty list if list is null |
32,635 | public int decode ( final InputStream stream , final ByteBuffer buffer ) throws IOException { while ( buffer . remaining ( ) >= 64 ) { int val = stream . read ( ) ; if ( val < 0 ) { break ; } if ( ( val & COMPRESSED_RUN_MASK ) == COMPRESSED_RUN_MASK ) { int count = val & ~ COMPRESSED_RUN_MASK ; int pixel = stream . read ( ) ; if ( pixel < 0 ) { break ; } for ( int i = 0 ; i < count ; i ++ ) { buffer . put ( ( byte ) pixel ) ; } } else { buffer . put ( ( byte ) val ) ; } } return buffer . position ( ) ; } | even if this will make the output larger . |
32,636 | private boolean buildRegexpParser ( ) { String regexp = convertWildcardExpressionToRegularExpression ( mStringMask ) ; if ( regexp == null ) { out . println ( DebugUtil . getPrefixErrorMessage ( this ) + "irregularity in regexp conversion - now not able to parse any strings, all strings will be rejected!" ) ; return false ; } try { mRegexpParser = Pattern . compile ( regexp ) ; } catch ( PatternSyntaxException e ) { if ( mDebugging ) { out . println ( DebugUtil . getPrefixErrorMessage ( this ) + "RESyntaxException \"" + e . getMessage ( ) + "\" caught - now not able to parse any strings, all strings will be rejected!" ) ; } if ( mDebugging ) { e . printStackTrace ( System . err ) ; } return false ; } if ( mDebugging ) { out . println ( DebugUtil . getPrefixDebugMessage ( this ) + "regular expression parser from regular expression " + regexp + " extracted from wildcard string mask " + mStringMask + "." ) ; } return true ; } | Builds the regexp parser . |
32,637 | private boolean checkStringToBeParsed ( final String pStringToBeParsed ) { if ( pStringToBeParsed == null ) { if ( mDebugging ) { out . println ( DebugUtil . getPrefixDebugMessage ( this ) + "string to be parsed is null - rejection!" ) ; } return false ; } for ( int i = 0 ; i < pStringToBeParsed . length ( ) ; i ++ ) { if ( ! isInAlphabet ( pStringToBeParsed . charAt ( i ) ) ) { if ( mDebugging ) { out . println ( DebugUtil . getPrefixDebugMessage ( this ) + "one or more characters in string to be parsed are not legal characters - rejection!" ) ; } return false ; } } return true ; } | Simple check of the string to be parsed . |
32,638 | public static boolean isInAlphabet ( final char pCharToCheck ) { for ( int i = 0 ; i < ALPHABET . length ; i ++ ) { if ( pCharToCheck == ALPHABET [ i ] ) { return true ; } } return false ; } | Tests if a certain character is a valid character in the alphabet that is applying for this automaton . |
32,639 | @ SuppressWarnings ( { "UnusedDeclaration" , "UnusedAssignment" , "unchecked" } ) public static void main ( String [ ] pArgs ) { int howMany = 1000 ; if ( pArgs . length > 0 ) { howMany = Integer . parseInt ( pArgs [ 0 ] ) ; } long start ; long end ; String [ ] stringArr1 = new String [ ] { "zero" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" } ; stringArr1 = new String [ ] { "zero" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" , "ten" , "eleven" , "twelve" , "thirteen" , "fourteen" , "fifteen" , "sixteen" , "seventeen" , "eighteen" , "nineteen" } ; System . out . println ( "\nFilterIterators:\n" ) ; List list = Arrays . asList ( stringArr1 ) ; Iterator iter = new FilterIterator ( list . iterator ( ) , new FilterIterator . Filter ( ) { public boolean accept ( Object pElement ) { return ( ( String ) pElement ) . length ( ) > 5 ; } } ) ; while ( iter . hasNext ( ) ) { String str = ( String ) iter . next ( ) ; System . out . println ( str + " has more than 5 letters!" ) ; } iter = new FilterIterator ( list . iterator ( ) , new FilterIterator . Filter ( ) { public boolean accept ( Object pElement ) { return ( ( String ) pElement ) . length ( ) <= 5 ; } } ) ; while ( iter . hasNext ( ) ) { String str = ( String ) iter . next ( ) ; System . out . println ( str + " has less than, or exactly 5 letters!" ) ; } start = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < howMany ; i ++ ) { iter = new FilterIterator ( list . iterator ( ) , new FilterIterator . Filter ( ) { public boolean accept ( Object pElement ) { return ( ( String ) pElement ) . length ( ) <= 5 ; } } ) ; while ( iter . hasNext ( ) ) { iter . next ( ) ; System . out . print ( "" ) ; } } } | Testing only . |
32,640 | public static Object mergeArrays ( Object pArray1 , Object pArray2 ) { return mergeArrays ( pArray1 , 0 , Array . getLength ( pArray1 ) , pArray2 , 0 , Array . getLength ( pArray2 ) ) ; } | Merges two arrays into a new array . Elements from array1 and array2 will be copied into a new array that has array1 . length + array2 . length elements . |
32,641 | @ SuppressWarnings ( { "SuspiciousSystemArraycopy" } ) public static Object mergeArrays ( Object pArray1 , int pOffset1 , int pLength1 , Object pArray2 , int pOffset2 , int pLength2 ) { Class class1 = pArray1 . getClass ( ) ; Class type = class1 . getComponentType ( ) ; Object array = Array . newInstance ( type , pLength1 + pLength2 ) ; System . arraycopy ( pArray1 , pOffset1 , array , 0 , pLength1 ) ; System . arraycopy ( pArray2 , pOffset2 , array , pLength1 , pLength2 ) ; return array ; } | Merges two arrays into a new array . Elements from pArray1 and pArray2 will be copied into a new array that has pLength1 + pLength2 elements . |
32,642 | public static < E > void addAll ( Collection < E > pCollection , Iterator < ? extends E > pIterator ) { while ( pIterator . hasNext ( ) ) { pCollection . add ( pIterator . next ( ) ) ; } } | Adds all elements of the iterator to the collection . |
32,643 | < T > void registerSPIs ( final URL pResource , final Class < T > pCategory , final ClassLoader pLoader ) { Properties classNames = new Properties ( ) ; try { classNames . load ( pResource . openStream ( ) ) ; } catch ( IOException e ) { throw new ServiceConfigurationError ( e ) ; } if ( ! classNames . isEmpty ( ) ) { @ SuppressWarnings ( { "unchecked" } ) CategoryRegistry < T > registry = categoryMap . get ( pCategory ) ; Set providerClassNames = classNames . keySet ( ) ; for ( Object providerClassName : providerClassNames ) { String className = ( String ) providerClassName ; try { @ SuppressWarnings ( { "unchecked" } ) Class < T > providerClass = ( Class < T > ) Class . forName ( className , true , pLoader ) ; T provider = providerClass . newInstance ( ) ; registry . register ( provider ) ; } catch ( ClassNotFoundException e ) { throw new ServiceConfigurationError ( e ) ; } catch ( IllegalAccessException e ) { throw new ServiceConfigurationError ( e ) ; } catch ( InstantiationException e ) { throw new ServiceConfigurationError ( e ) ; } catch ( IllegalArgumentException e ) { throw new ServiceConfigurationError ( e ) ; } } } } | Registers all SPIs listed in the given resource . |
32,644 | private < T > CategoryRegistry < T > getRegistry ( final Class < T > pCategory ) { @ SuppressWarnings ( { "unchecked" } ) CategoryRegistry < T > registry = categoryMap . get ( pCategory ) ; if ( registry == null ) { throw new IllegalArgumentException ( "No such category: " + pCategory . getName ( ) ) ; } return registry ; } | Gets the category registry for the given category . |
32,645 | public boolean register ( final Object pProvider ) { Iterator < Class < ? > > categories = compatibleCategories ( pProvider ) ; boolean registered = false ; while ( categories . hasNext ( ) ) { Class < ? > category = categories . next ( ) ; if ( registerImpl ( pProvider , category ) && ! registered ) { registered = true ; } } return registered ; } | Registers the given provider for all categories it matches . |
32,646 | public < T > boolean register ( final T pProvider , final Class < ? super T > pCategory ) { return registerImpl ( pProvider , pCategory ) ; } | Registers the given provider for the given category . |
32,647 | public boolean deregister ( final Object pProvider ) { Iterator < Class < ? > > categories = containingCategories ( pProvider ) ; boolean deregistered = false ; while ( categories . hasNext ( ) ) { Class < ? > category = categories . next ( ) ; if ( deregister ( pProvider , category ) && ! deregistered ) { deregistered = true ; } } return deregistered ; } | De - registers the given provider from all categories it s currently registered in . |
32,648 | public static boolean isEmpty ( String [ ] pStringArray ) { if ( pStringArray == null ) { return true ; } for ( String string : pStringArray ) { if ( ! isEmpty ( string ) ) { return false ; } } return true ; } | Tests a string array to see if all items are null or an empty string . |
32,649 | public static boolean contains ( String pContainer , String pLookFor ) { return ( ( pContainer != null ) && ( pLookFor != null ) && ( pContainer . indexOf ( pLookFor ) >= 0 ) ) ; } | Tests if a string contains another string . |
32,650 | public static boolean containsIgnoreCase ( String pString , int pChar ) { return ( ( pString != null ) && ( ( pString . indexOf ( Character . toLowerCase ( ( char ) pChar ) ) >= 0 ) || ( pString . indexOf ( Character . toUpperCase ( ( char ) pChar ) ) >= 0 ) ) ) ; } | Tests if a string contains a specific character ignoring case . |
32,651 | public static int indexOfIgnoreCase ( String pString , int pChar , int pPos ) { if ( ( pString == null ) ) { return - 1 ; } char lower = Character . toLowerCase ( ( char ) pChar ) ; char upper = Character . toUpperCase ( ( char ) pChar ) ; int indexLower ; int indexUpper ; indexLower = pString . indexOf ( lower , pPos ) ; indexUpper = pString . indexOf ( upper , pPos ) ; if ( indexLower < 0 ) { return indexUpper ; } else if ( indexUpper < 0 ) { return indexLower ; } else { return ( indexLower < indexUpper ) ? indexLower : indexUpper ; } } | Returns the index within this string of the first occurrence of the specified character starting at the specified index . |
32,652 | public static int lastIndexOfIgnoreCase ( String pString , int pChar ) { return lastIndexOfIgnoreCase ( pString , pChar , pString != null ? pString . length ( ) : - 1 ) ; } | Returns the index within this string of the last occurrence of the specified character . |
32,653 | public static int lastIndexOfIgnoreCase ( String pString , int pChar , int pPos ) { if ( ( pString == null ) ) { return - 1 ; } char lower = Character . toLowerCase ( ( char ) pChar ) ; char upper = Character . toUpperCase ( ( char ) pChar ) ; int indexLower ; int indexUpper ; indexLower = pString . lastIndexOf ( lower , pPos ) ; indexUpper = pString . lastIndexOf ( upper , pPos ) ; if ( indexLower < 0 ) { return indexUpper ; } else if ( indexUpper < 0 ) { return indexLower ; } else { return ( indexLower > indexUpper ) ? indexLower : indexUpper ; } } | Returns the index within this string of the last occurrence of the specified character searching backward starting at the specified index . |
32,654 | public static String ltrim ( String pString ) { if ( ( pString == null ) || ( pString . length ( ) == 0 ) ) { return pString ; } for ( int i = 0 ; i < pString . length ( ) ; i ++ ) { if ( ! Character . isWhitespace ( pString . charAt ( i ) ) ) { if ( i == 0 ) { return pString ; } else { return pString . substring ( i ) ; } } } return "" ; } | Trims the argument string for whitespace on the left side only . |
32,655 | public static String replace ( String pSource , String pPattern , String pReplace ) { if ( pPattern . length ( ) == 0 ) { return pSource ; } int match ; int offset = 0 ; StringBuilder result = new StringBuilder ( ) ; while ( ( match = pSource . indexOf ( pPattern , offset ) ) != - 1 ) { result . append ( pSource . substring ( offset , match ) ) ; result . append ( pReplace ) ; offset = match + pPattern . length ( ) ; } result . append ( pSource . substring ( offset ) ) ; return result . toString ( ) ; } | Replaces a substring of a string with another string . All matches are replaced . |
32,656 | public static String replaceIgnoreCase ( String pSource , String pPattern , String pReplace ) { if ( pPattern . length ( ) == 0 ) { return pSource ; } int match ; int offset = 0 ; StringBuilder result = new StringBuilder ( ) ; while ( ( match = indexOfIgnoreCase ( pSource , pPattern , offset ) ) != - 1 ) { result . append ( pSource . substring ( offset , match ) ) ; result . append ( pReplace ) ; offset = match + pPattern . length ( ) ; } result . append ( pSource . substring ( offset ) ) ; return result . toString ( ) ; } | Replaces a substring of a string with another string ignoring case . All matches are replaced . |
32,657 | public static String capitalize ( String pString , int pIndex ) { if ( pIndex < 0 ) { throw new IndexOutOfBoundsException ( "Negative index not allowed: " + pIndex ) ; } if ( pString == null || pString . length ( ) <= pIndex ) { return pString ; } if ( Character . isUpperCase ( pString . charAt ( pIndex ) ) ) { return pString ; } char [ ] charArray = pString . toCharArray ( ) ; charArray [ pIndex ] = Character . toUpperCase ( charArray [ pIndex ] ) ; return new String ( charArray ) ; } | Makes the Nth letter of a String uppercase . If the index is outside the the length of the argument string the argument is simply returned . |
32,658 | public static String pad ( String pSource , int pRequiredLength , String pPadString , boolean pPrepend ) { if ( pPadString == null || pPadString . length ( ) == 0 ) { throw new IllegalArgumentException ( "Pad string: \"" + pPadString + "\"" ) ; } if ( pSource . length ( ) >= pRequiredLength ) { return pSource ; } int gap = pRequiredLength - pSource . length ( ) ; StringBuilder result = new StringBuilder ( pPadString ) ; while ( result . length ( ) < gap ) { result . append ( result ) ; } if ( result . length ( ) > gap ) { result . delete ( gap , result . length ( ) ) ; } return pPrepend ? result . append ( pSource ) . toString ( ) : result . insert ( 0 , pSource ) . toString ( ) ; } | String length check with simple concatenation of selected pad - string . E . g . a zip number from 123 to the correct 0123 . |
32,659 | public static String [ ] toStringArray ( String pString , String pDelimiters ) { if ( isEmpty ( pString ) ) { return new String [ 0 ] ; } StringTokenIterator st = new StringTokenIterator ( pString , pDelimiters ) ; List < String > v = new ArrayList < String > ( ) ; while ( st . hasMoreElements ( ) ) { v . add ( st . nextToken ( ) ) ; } return v . toArray ( new String [ v . size ( ) ] ) ; } | Converts a delimiter separated String to an array of Strings . |
32,660 | public static int [ ] toIntArray ( String pString , String pDelimiters , int pBase ) { if ( isEmpty ( pString ) ) { return new int [ 0 ] ; } String [ ] temp = toStringArray ( pString , pDelimiters ) ; int [ ] array = new int [ temp . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { array [ i ] = Integer . parseInt ( temp [ i ] , pBase ) ; } return array ; } | Converts a comma - separated String to an array of ints . |
32,661 | public static long [ ] toLongArray ( String pString , String pDelimiters ) { if ( isEmpty ( pString ) ) { return new long [ 0 ] ; } String [ ] temp = toStringArray ( pString , pDelimiters ) ; long [ ] array = new long [ temp . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { array [ i ] = Long . parseLong ( temp [ i ] ) ; } return array ; } | Converts a comma - separated String to an array of longs . |
32,662 | public static double [ ] toDoubleArray ( String pString , String pDelimiters ) { if ( isEmpty ( pString ) ) { return new double [ 0 ] ; } String [ ] temp = toStringArray ( pString , pDelimiters ) ; double [ ] array = new double [ temp . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { array [ i ] = Double . valueOf ( temp [ i ] ) ; } return array ; } | Converts a comma - separated String to an array of doubles . |
32,663 | public static String toCSVString ( Object [ ] pStringArray , String pDelimiterString ) { if ( pStringArray == null ) { return "" ; } if ( pDelimiterString == null ) { throw new IllegalArgumentException ( "delimiter == null" ) ; } StringBuilder buffer = new StringBuilder ( ) ; for ( int i = 0 ; i < pStringArray . length ; i ++ ) { if ( i > 0 ) { buffer . append ( pDelimiterString ) ; } buffer . append ( pStringArray [ i ] ) ; } return buffer . toString ( ) ; } | Converts a string array to a string separated by the given delimiter . |
32,664 | static void loadLibrary0 ( String pLibrary , String pResource , ClassLoader pLoader ) { if ( pLibrary == null ) { throw new IllegalArgumentException ( "library == null" ) ; } UnsatisfiedLinkError unsatisfied ; try { System . loadLibrary ( pLibrary ) ; return ; } catch ( UnsatisfiedLinkError err ) { unsatisfied = err ; } final ClassLoader loader = pLoader != null ? pLoader : Thread . currentThread ( ) . getContextClassLoader ( ) ; final String resource = pResource != null ? pResource : getResourceFor ( pLibrary ) ; if ( resource == null ) { throw unsatisfied ; } File dir = new File ( System . getProperty ( "user.home" ) + "/.twelvemonkeys/lib" ) ; dir . mkdirs ( ) ; File libraryFile = new File ( dir . getAbsolutePath ( ) , pLibrary + "." + FileUtil . getExtension ( resource ) ) ; if ( ! libraryFile . exists ( ) ) { try { extractToUserDir ( resource , libraryFile , loader ) ; } catch ( IOException ioe ) { UnsatisfiedLinkError err = new UnsatisfiedLinkError ( "Unable to extract resource to dir: " + libraryFile . getAbsolutePath ( ) ) ; err . initCause ( ioe ) ; throw err ; } } System . load ( libraryFile . getAbsolutePath ( ) ) ; } | Loads a native library . |
32,665 | public Rational plus ( final Rational pOther ) { if ( equals ( ZERO ) ) { return pOther ; } if ( pOther . equals ( ZERO ) ) { return this ; } long f = gcd ( numerator , pOther . numerator ) ; long g = gcd ( denominator , pOther . denominator ) ; return new Rational ( ( ( numerator / f ) * ( pOther . denominator / g ) + ( pOther . numerator / f ) * ( denominator / g ) ) * f , lcm ( denominator , pOther . denominator ) ) ; } | return a + b staving off overflow |
32,666 | public void service ( PageContext pContext ) throws ServletException , IOException { JspWriter writer = pContext . getOut ( ) ; writer . print ( value ) ; } | Services the page fragment . This version simply prints the value of this parameter to teh PageContext s out . |
32,667 | static void main ( String [ ] argv ) { Time time = null ; TimeFormat in = null ; TimeFormat out = null ; if ( argv . length >= 3 ) { System . out . println ( "Creating out TimeFormat: \"" + argv [ 2 ] + "\"" ) ; out = new TimeFormat ( argv [ 2 ] ) ; } if ( argv . length >= 2 ) { System . out . println ( "Creating in TimeFormat: \"" + argv [ 1 ] + "\"" ) ; in = new TimeFormat ( argv [ 1 ] ) ; } else { System . out . println ( "Using default format for in" ) ; in = DEFAULT_FORMAT ; } if ( out == null ) out = in ; if ( argv . length >= 1 ) { System . out . println ( "Parsing: \"" + argv [ 0 ] + "\" with format \"" + in . formatString + "\"" ) ; time = in . parse ( argv [ 0 ] ) ; } else time = new Time ( ) ; System . out . println ( "Time is \"" + out . format ( time ) + "\" according to format \"" + out . formatString + "\"" ) ; } | Main method for testing ONLY |
32,668 | public String format ( Time pTime ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < formatter . length ; i ++ ) { buf . append ( formatter [ i ] . format ( pTime ) ) ; } return buf . toString ( ) ; } | Formats the the given time using this format . |
32,669 | void registerContent ( final String pCacheURI , final CacheRequest pRequest , final CachedResponse pCachedResponse ) throws IOException { if ( "HEAD" . equals ( pRequest . getMethod ( ) ) ) { return ; } String extension = MIMEUtil . getExtension ( pCachedResponse . getHeaderValue ( HEADER_CONTENT_TYPE ) ) ; if ( extension == null ) { extension = "[NULL]" ; } synchronized ( contentCache ) { contentCache . put ( pCacheURI + '.' + extension , pCachedResponse ) ; if ( ! contentCache . containsKey ( pCacheURI ) ) { contentCache . put ( pCacheURI , pCachedResponse ) ; } } File content = new File ( tempDir , "./" + pCacheURI + '.' + extension ) ; if ( deleteCacheOnExit && ! content . exists ( ) ) { content . deleteOnExit ( ) ; } File parent = content . getParentFile ( ) ; if ( ! ( parent . exists ( ) || parent . mkdirs ( ) ) ) { log ( "Could not create directory " + parent . getAbsolutePath ( ) ) ; return ; } OutputStream mContentStream = new BufferedOutputStream ( new FileOutputStream ( content ) ) ; try { pCachedResponse . writeContentsTo ( mContentStream ) ; } finally { try { mContentStream . close ( ) ; } catch ( IOException e ) { log ( "Error closing content stream: " + e . getMessage ( ) , e ) ; } } File headers = new File ( content . getAbsolutePath ( ) + FILE_EXT_HEADERS ) ; if ( deleteCacheOnExit && ! headers . exists ( ) ) { headers . deleteOnExit ( ) ; } FileWriter writer = new FileWriter ( headers ) ; PrintWriter headerWriter = new PrintWriter ( writer ) ; try { String [ ] names = pCachedResponse . getHeaderNames ( ) ; for ( String name : names ) { String [ ] values = pCachedResponse . getHeaderValues ( name ) ; headerWriter . print ( name ) ; headerWriter . print ( ": " ) ; headerWriter . println ( StringUtil . toCSVString ( values , "\\" ) ) ; } } finally { headerWriter . flush ( ) ; try { writer . close ( ) ; } catch ( IOException e ) { log ( "Error closing header stream: " + e . getMessage ( ) , e ) ; } } String [ ] varyHeaders = pCachedResponse . getHeaderValues ( HEADER_VARY ) ; if ( varyHeaders != null && varyHeaders . length > 0 ) { Properties variations = getVaryProperties ( pCacheURI ) ; String vary = StringUtil . toCSVString ( varyHeaders ) ; variations . setProperty ( HEADER_VARY , vary ) ; String varyKey = createVaryKey ( varyHeaders , pRequest ) ; variations . setProperty ( varyKey , extension ) ; storeVaryProperties ( pCacheURI , variations ) ; } } | Registers content for the given URI in the cache . |
32,670 | static long getDateHeader ( final String pHeaderValue ) { long date = - 1L ; if ( pHeaderValue != null ) { date = HTTPUtil . parseHTTPDate ( pHeaderValue ) ; } return date ; } | Utility to read a date header from a cached response . |
32,671 | public void service ( ServletRequest pRequest , ServletResponse pResponse ) throws IOException , ServletException { int red = 0 ; int green = 0 ; int blue = 0 ; String rgb = pRequest . getParameter ( RGB_PARAME ) ; if ( rgb != null && rgb . length ( ) >= 6 && rgb . length ( ) <= 7 ) { int index = 0 ; if ( rgb . length ( ) == 7 ) { index ++ ; } try { String r = rgb . substring ( index , index += 2 ) ; red = Integer . parseInt ( r , 0x10 ) ; String g = rgb . substring ( index , index += 2 ) ; green = Integer . parseInt ( g , 0x10 ) ; String b = rgb . substring ( index , index += 2 ) ; blue = Integer . parseInt ( b , 0x10 ) ; } catch ( NumberFormatException nfe ) { log ( "Wrong color format for ColorDroplet: " + rgb + ". Must be RRGGBB." ) ; } } pResponse . setContentType ( "image/png" ) ; ServletOutputStream out = pResponse . getOutputStream ( ) ; try { out . write ( PNG_IMG , 0 , PLTE_CHUNK_START ) ; byte [ ] palette = makePalette ( red , green , blue ) ; out . write ( palette ) ; int pos = PLTE_CHUNK_START + PLTE_CHUNK_LENGTH + 4 ; out . write ( PNG_IMG , pos , PNG_IMG . length - pos ) ; } finally { out . flush ( ) ; } } | Renders the 1 x 1 single color PNG to the response . |
32,672 | public static String getParameter ( final ServletRequest pReq , final String pName , final String pDefault ) { String str = pReq . getParameter ( pName ) ; return str != null ? str : pDefault ; } | Gets the value of the given parameter from the request or if the parameter is not set the default value . |
32,673 | static < T > T getParameter ( final ServletRequest pReq , final String pName , final Class < T > pType , final String pFormat , final T pDefault ) { if ( pDefault != null && ! pType . isInstance ( pDefault ) ) { throw new IllegalArgumentException ( "default value not instance of " + pType + ": " + pDefault . getClass ( ) ) ; } String str = pReq . getParameter ( pName ) ; if ( str == null ) { return pDefault ; } try { return pType . cast ( Converter . getInstance ( ) . toObject ( str , pType , pFormat ) ) ; } catch ( ConversionException ce ) { return pDefault ; } } | Gets the value of the given parameter from the request converted to an Object . If the parameter is not set or not parseable the default value is returned . |
32,674 | static String getScriptName ( final HttpServletRequest pRequest ) { String requestURI = pRequest . getRequestURI ( ) ; return StringUtil . getLastElement ( requestURI , "/" ) ; } | Gets the name of the servlet or the script that generated the servlet . |
32,675 | public static String getSessionId ( final HttpServletRequest pRequest ) { HttpSession session = pRequest . getSession ( ) ; return ( session != null ) ? session . getId ( ) : null ; } | Gets the unique identifier assigned to this session . The identifier is assigned by the servlet container and is implementation dependent . |
32,676 | protected static Object toUpper ( final Object pObject ) { if ( pObject instanceof String ) { return ( ( String ) pObject ) . toUpperCase ( ) ; } return pObject ; } | Converts the parameter to uppercase if it s a String . |
32,677 | private static long scanForSequence ( final ImageInputStream pStream , final byte [ ] pSequence ) throws IOException { long start = - 1l ; int index = 0 ; int nullBytes = 0 ; for ( int read ; ( read = pStream . read ( ) ) >= 0 ; ) { if ( pSequence [ index ] == ( byte ) read ) { if ( start == - 1 ) { start = pStream . getStreamPosition ( ) - 1 ; } if ( nullBytes == 1 || nullBytes == 3 ) { pStream . skipBytes ( nullBytes ) ; } index ++ ; if ( index == pSequence . length ) { return start ; } } else if ( index == 1 && read == 0 && nullBytes < 3 ) { nullBytes ++ ; } else if ( index != 0 ) { index = 0 ; start = - 1 ; nullBytes = 0 ; } } return - 1l ; } | Scans for a given ASCII sequence . |
32,678 | private static InputStream getResourceAsStream ( ClassLoader pClassLoader , String pName , boolean pGuessSuffix ) { InputStream is ; if ( ! pGuessSuffix ) { is = pClassLoader . getResourceAsStream ( pName ) ; if ( is != null && pName . endsWith ( XML_PROPERTIES ) ) { is = new XMLPropertiesInputStream ( is ) ; } } else { is = pClassLoader . getResourceAsStream ( pName + STD_PROPERTIES ) ; if ( is == null ) { is = pClassLoader . getResourceAsStream ( pName + XML_PROPERTIES ) ; if ( is != null ) { is = new XMLPropertiesInputStream ( is ) ; } } } return is ; } | Gets the named resource as a stream from the given Class Classoader . If the pGuessSuffix parameter is true the method will try to append typical properties file suffixes such as . properties or . xml . |
32,679 | private static InputStream getFileAsStream ( String pName , boolean pGuessSuffix ) { InputStream is = null ; File propertiesFile ; try { if ( ! pGuessSuffix ) { propertiesFile = new File ( pName ) ; if ( propertiesFile . exists ( ) ) { is = new FileInputStream ( propertiesFile ) ; if ( pName . endsWith ( XML_PROPERTIES ) ) { is = new XMLPropertiesInputStream ( is ) ; } } } else { propertiesFile = new File ( pName + STD_PROPERTIES ) ; if ( propertiesFile . exists ( ) ) { is = new FileInputStream ( propertiesFile ) ; } else { propertiesFile = new File ( pName + XML_PROPERTIES ) ; if ( propertiesFile . exists ( ) ) { is = new XMLPropertiesInputStream ( new FileInputStream ( propertiesFile ) ) ; } } } } catch ( FileNotFoundException fnf ) { } return is ; } | Gets the named file as a stream from the current directory . If the pGuessSuffix parameter is true the method will try to append typical properties file suffixes such as . properties or . xml . |
32,680 | private static Properties loadProperties ( InputStream pInput ) throws IOException { if ( pInput == null ) { throw new IllegalArgumentException ( "InputStream == null!" ) ; } Properties mapping = new Properties ( ) ; mapping . load ( pInput ) ; return mapping ; } | Returns a Properties loaded from the given inputstream . If the given inputstream is null then an empty Properties object is returned . |
32,681 | private static char initMaxDelimiter ( char [ ] pDelimiters ) { if ( pDelimiters == null ) { return 0 ; } char max = 0 ; for ( char c : pDelimiters ) { if ( max < c ) { max = c ; } } return max ; } | Returns the highest char in the delimiter set . |
32,682 | private Rectangle getPICTFrame ( ) throws IOException { if ( frame == null ) { readPICTHeader ( imageInput ) ; if ( DEBUG ) { System . out . println ( "Done reading PICT header!" ) ; } } return frame ; } | Open and read the frame size of the PICT file . |
32,683 | private void readPICTHeader ( final ImageInputStream pStream ) throws IOException { pStream . seek ( 0l ) ; try { readPICTHeader0 ( pStream ) ; } catch ( IIOException e ) { pStream . seek ( 0l ) ; PICTImageReaderSpi . skipNullHeader ( pStream ) ; readPICTHeader0 ( pStream ) ; } } | Read the PICT header . The information read is shown on stdout if DEBUG is true . |
32,684 | private void readRectangle ( DataInput pStream , Rectangle pDestRect ) throws IOException { int y = pStream . readUnsignedShort ( ) ; int x = pStream . readUnsignedShort ( ) ; int h = pStream . readUnsignedShort ( ) ; int w = pStream . readUnsignedShort ( ) ; pDestRect . setLocation ( getXPtCoord ( x ) , getYPtCoord ( y ) ) ; pDestRect . setSize ( getXPtCoord ( w - x ) , getYPtCoord ( h - y ) ) ; } | Reads the rectangle location and size from an 8 - byte rectangle stream . |
32,685 | private Polygon readPoly ( DataInput pStream , Rectangle pBounds ) throws IOException { int size = pStream . readUnsignedShort ( ) ; readRectangle ( pStream , pBounds ) ; int points = ( size - 10 ) / 4 ; Polygon polygon = new Polygon ( ) ; for ( int i = 0 ; i < points ; i ++ ) { int y = getYPtCoord ( pStream . readShort ( ) ) ; int x = getXPtCoord ( pStream . readShort ( ) ) ; polygon . addPoint ( x , y ) ; } if ( ! pBounds . contains ( polygon . getBounds ( ) ) ) { processWarningOccurred ( "Bad poly, contains point(s) out of bounds " + pBounds + ": " + polygon ) ; } return polygon ; } | Read in a polygon . The input stream should be positioned at the first byte of the polygon . |
32,686 | public void setMaxConcurrentThreadCount ( String pMaxConcurrentThreadCount ) { if ( ! StringUtil . isEmpty ( pMaxConcurrentThreadCount ) ) { try { maxConcurrentThreadCount = Integer . parseInt ( pMaxConcurrentThreadCount ) ; } catch ( NumberFormatException nfe ) { } } } | Sets the minimum free thread count . |
32,687 | private String getContentType ( HttpServletRequest pRequest ) { if ( responseMessageTypes != null ) { String accept = pRequest . getHeader ( "Accept" ) ; for ( String type : responseMessageTypes ) { if ( StringUtil . contains ( accept , type ) ) { return type ; } } } return DEFAULT_TYPE ; } | Gets the content type for the response suitable for the requesting user agent . |
32,688 | private String getMessage ( String pContentType ) { String fileName = responseMessageNames . get ( pContentType ) ; CacheEntry entry = responseCache . get ( fileName ) ; if ( ( entry == null ) || entry . isExpired ( ) ) { entry = new CacheEntry ( readMessage ( fileName ) ) ; responseCache . put ( fileName , entry ) ; } return ( entry . getValue ( ) != null ) ? ( String ) entry . getValue ( ) : DEFUALT_RESPONSE_MESSAGE ; } | Gets the response message for the given content type . |
32,689 | private String readMessage ( String pFileName ) { try { InputStream is = getServletContext ( ) . getResourceAsStream ( pFileName ) ; if ( is != null ) { return new String ( FileUtil . read ( is ) ) ; } else { log ( "File not found: " + pFileName ) ; } } catch ( IOException ioe ) { log ( "Error reading file: " + pFileName + " (" + ioe . getMessage ( ) + ")" ) ; } return null ; } | Reads the response message from a file in the current web app . |
32,690 | public void init ( ) throws ServletException { FilterConfig config = getFilterConfig ( ) ; boolean deleteCacheOnExit = "TRUE" . equalsIgnoreCase ( config . getInitParameter ( "deleteCacheOnExit" ) ) ; int expiryTime = 10 * 60 * 1000 ; String expiryTimeStr = config . getInitParameter ( "expiryTime" ) ; if ( ! StringUtil . isEmpty ( expiryTimeStr ) ) { try { expiryTime = Integer . parseInt ( expiryTimeStr ) ; } catch ( NumberFormatException e ) { throw new ServletConfigException ( "Could not parse expiryTime: " + e . toString ( ) , e ) ; } } int memCacheSize = 10 ; String memCacheSizeStr = config . getInitParameter ( "memCacheSize" ) ; if ( ! StringUtil . isEmpty ( memCacheSizeStr ) ) { try { memCacheSize = Integer . parseInt ( memCacheSizeStr ) ; } catch ( NumberFormatException e ) { throw new ServletConfigException ( "Could not parse memCacheSize: " + e . toString ( ) , e ) ; } } int maxCachedEntites = 10000 ; try { cache = new HTTPCache ( getTempFolder ( ) , expiryTime , memCacheSize * 1024 * 1024 , maxCachedEntites , deleteCacheOnExit , new ServletContextLoggerAdapter ( getFilterName ( ) , getServletContext ( ) ) ) { protected File getRealFile ( CacheRequest pRequest ) { String contextRelativeURI = ServletUtil . getContextRelativeURI ( ( ( ServletCacheRequest ) pRequest ) . getRequest ( ) ) ; String path = getServletContext ( ) . getRealPath ( contextRelativeURI ) ; if ( path != null ) { return new File ( path ) ; } return null ; } } ; log ( "Created cache: " + cache ) ; } catch ( IllegalArgumentException e ) { throw new ServletConfigException ( "Could not create cache: " + e . toString ( ) , e ) ; } } | Initializes the filter |
32,691 | protected Entry < K , V > removeEntry ( Entry < K , V > pEntry ) { if ( pEntry == null ) { return null ; } Entry < K , V > candidate = getEntry ( pEntry . getKey ( ) ) ; if ( candidate == pEntry || ( candidate != null && candidate . equals ( pEntry ) ) ) { remove ( pEntry . getKey ( ) ) ; return pEntry ; } return null ; } | Removes the given entry from the Map . |
32,692 | public void writeHtml ( JspWriter pOut , String pHtml ) throws IOException { StringTokenizer parser = new StringTokenizer ( pHtml , "<>&" , true ) ; while ( parser . hasMoreTokens ( ) ) { String token = parser . nextToken ( ) ; if ( token . equals ( "<" ) ) { pOut . print ( "<" ) ; } else if ( token . equals ( ">" ) ) { pOut . print ( ">" ) ; } else if ( token . equals ( "&" ) ) { pOut . print ( "&" ) ; } else { pOut . print ( token ) ; } } } | writeHtml ensures that the text being outputted appears as it was entered . This prevents users from hacking the system by entering html or jsp code into an entry form where that value will be displayed later in the site . |
32,693 | public String getInitParameter ( String pName , int pScope ) { switch ( pScope ) { case PageContext . PAGE_SCOPE : return getServletConfig ( ) . getInitParameter ( pName ) ; case PageContext . APPLICATION_SCOPE : return getServletContext ( ) . getInitParameter ( pName ) ; default : throw new IllegalArgumentException ( "Illegal scope." ) ; } } | Returns the initialisation parameter from the scope specified with the name specified . |
32,694 | public Enumeration getInitParameterNames ( int pScope ) { switch ( pScope ) { case PageContext . PAGE_SCOPE : return getServletConfig ( ) . getInitParameterNames ( ) ; case PageContext . APPLICATION_SCOPE : return getServletContext ( ) . getInitParameterNames ( ) ; default : throw new IllegalArgumentException ( "Illegal scope" ) ; } } | Returns an enumeration containing all the parameters defined in the scope specified by the parameter . |
32,695 | public InputStream getResourceAsStream ( String pPath ) { String path = pPath ; if ( pPath != null && ! pPath . startsWith ( "/" ) ) { path = getContextPath ( ) + pPath ; } return pageContext . getServletContext ( ) . getResourceAsStream ( path ) ; } | Gets the resource associated with the given relative path for the current JSP page request . The path may be absolute or relative to the current context root . |
32,696 | public static boolean isCS_sRGB ( final ICC_Profile profile ) { Validate . notNull ( profile , "profile" ) ; return profile . getColorSpaceType ( ) == ColorSpace . TYPE_RGB && Arrays . equals ( getProfileHeaderWithProfileId ( profile ) , sRGB . header ) ; } | Tests whether an ICC color profile is equal to the default sRGB profile . |
32,697 | public Object toObject ( String pString , Class pType , String pFormat ) throws ConversionException { if ( StringUtil . isEmpty ( pString ) ) return null ; try { DateFormat format ; if ( pFormat == null ) { format = DateFormat . getDateTimeInstance ( ) ; } else { format = getDateFormat ( pFormat ) ; } Date date = StringUtil . toDate ( pString , format ) ; if ( pType != Date . class ) { try { date = ( Date ) BeanUtil . createInstance ( pType , new Long ( date . getTime ( ) ) ) ; } catch ( ClassCastException e ) { throw new TypeMismathException ( pType ) ; } catch ( InvocationTargetException e ) { throw new ConversionException ( e ) ; } } return date ; } catch ( RuntimeException rte ) { throw new ConversionException ( rte ) ; } } | Converts the string to a date using the given format for parsing . |
32,698 | private static int [ ] toRGBArray ( int pARGB , int [ ] pBuffer ) { pBuffer [ 0 ] = ( ( pARGB & 0x00ff0000 ) >> 16 ) ; pBuffer [ 1 ] = ( ( pARGB & 0x0000ff00 ) >> 8 ) ; pBuffer [ 2 ] = ( ( pARGB & 0x000000ff ) ) ; return pBuffer ; } | Converts an int ARGB to int triplet . |
32,699 | protected RenderedImage doFilter ( BufferedImage pImage , ServletRequest pRequest , ImageServletResponse pResponse ) { int quality = getQuality ( pRequest . getParameter ( PARAM_SCALE_QUALITY ) ) ; int units = getUnits ( pRequest . getParameter ( PARAM_SCALE_UNITS ) ) ; if ( units == UNITS_UNKNOWN ) { log ( "Unknown units for scale, returning original." ) ; return pImage ; } boolean uniformScale = ServletUtil . getBooleanParameter ( pRequest , PARAM_SCALE_UNIFORM , true ) ; int width = ServletUtil . getIntParameter ( pRequest , PARAM_SCALE_X , - 1 ) ; int height = ServletUtil . getIntParameter ( pRequest , PARAM_SCALE_Y , - 1 ) ; Dimension dim = getDimensions ( pImage , width , height , units , uniformScale ) ; width = ( int ) dim . getWidth ( ) ; height = ( int ) dim . getHeight ( ) ; return ImageUtil . createScaled ( pImage , width , height , quality ) ; } | Reads the image from the requested URL scales it and returns it in the Servlet stream . See above for details on parameters . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.