idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
10,500 | public void ifge ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFGE ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFGE ) ; out . writeShort ( branch ) ; } } | ge succeeds if and only if value > ; = 0 |
10,501 | public void ifgt ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFGT ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFGT ) ; out . writeShort ( branch ) ; } } | gt succeeds if and only if value > ; 0 |
10,502 | public void ifle ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFLE ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFLE ) ; out . writeShort ( branch ) ; } } | le succeeds if and only if value < ; = 0 |
10,503 | private void createParentChildRelationships ( Database db , HashMap < String , Account > descriptionMap , HashMap < String , ArrayList < String > > seqMap ) throws Exception { ArrayList < String > parentIdStack = new ArrayList < String > ( ) ; if ( ! seqMap . containsKey ( Account . ROOT_ACCOUNT_URI ) ) throw new Exception ( "File does not contain the root account, '" + Account . ROOT_ACCOUNT_URI + "'" ) ; parentIdStack . add ( Account . ROOT_ACCOUNT_URI ) ; while ( parentIdStack . size ( ) > 0 ) { String parentId = parentIdStack . get ( 0 ) ; Account parentAccount = descriptionMap . get ( parentId ) ; parentIdStack . remove ( 0 ) ; if ( parentId . compareTo ( Account . ROOT_ACCOUNT_URI ) != 0 ) { if ( parentAccount != null ) { if ( db . findAccountById ( parentId ) == null ) { Account parentParentAccount = db . findParent ( parentAccount ) ; if ( parentParentAccount == null ) { logger . warning ( "SeqNode[" + parentId + "] does not have a parent, will be dropped" ) ; parentAccount = null ; } } } else { logger . warning ( "SeqNode[" + parentId + "] does not have a matching RDF:Description node, it will be dropped" ) ; } } else { parentAccount = db . getRootAccount ( ) ; } if ( parentAccount != null ) { for ( String childId : seqMap . get ( parentId ) ) { Account childAccount = descriptionMap . get ( childId ) ; if ( childAccount != null ) { if ( ! parentAccount . hasChild ( childAccount ) ) { parentAccount . getChildren ( ) . add ( childAccount ) ; if ( seqMap . containsKey ( childAccount . getId ( ) ) ) { parentIdStack . add ( childId ) ; childAccount . setIsFolder ( true ) ; } } else { logger . warning ( "Duplicate child '" + childId + "' found of parent '" + parentAccount . getId ( ) + "'" ) ; } } else { logger . warning ( "Cannot find RDF:Description for '" + childId + "', it will be dropped" ) ; } } } } } | Iterates through the list of Seqs read in adding the parent node and then adding children which belong to it . |
10,504 | public File rename ( File f ) { if ( createNewFile ( f ) ) { return f ; } String name = f . getName ( ) ; String body = null ; String ext = null ; int dot = name . lastIndexOf ( "." ) ; if ( dot != - 1 ) { body = name . substring ( 0 , dot ) ; ext = name . substring ( dot ) ; } else { body = name ; ext = "" ; } int count = 0 ; while ( ! createNewFile ( f ) && count < 9999 ) { count ++ ; String newName = body + count + ext ; f = new File ( f . getParent ( ) , newName ) ; } return f ; } | is atomic and used here to mark when a file name is chosen |
10,505 | public GeometryValidationState getState ( ) { if ( violations . isEmpty ( ) ) { return GeometryValidationState . VALID ; } else { return violations . get ( 0 ) . getState ( ) ; } } | Get the validation state of the geometry . We take the state of the first violation encountered . |
10,506 | public boolean equalsDelta ( Coordinate coordinate , double delta ) { return null != coordinate && ( Math . abs ( this . x - coordinate . x ) < delta && Math . abs ( this . y - coordinate . y ) < delta ) ; } | Comparison using a tolerance for the equality check . |
10,507 | public double distance ( Coordinate c ) { double dx = x - c . x ; double dy = y - c . y ; return Math . sqrt ( dx * dx + dy * dy ) ; } | Computes the 2 - dimensional Euclidean distance to another location . |
10,508 | public static Geometry toPolygon ( Bbox bounds ) { double minX = bounds . getX ( ) ; double minY = bounds . getY ( ) ; double maxX = bounds . getMaxX ( ) ; double maxY = bounds . getMaxY ( ) ; Geometry polygon = new Geometry ( Geometry . POLYGON , 0 , - 1 ) ; Geometry linearRing = new Geometry ( Geometry . LINEAR_RING , 0 , - 1 ) ; linearRing . setCoordinates ( new Coordinate [ ] { new Coordinate ( minX , minY ) , new Coordinate ( maxX , minY ) , new Coordinate ( maxX , maxY ) , new Coordinate ( minX , maxY ) , new Coordinate ( minX , minY ) } ) ; polygon . setGeometries ( new Geometry [ ] { linearRing } ) ; return polygon ; } | Transform the given bounding box into a polygon geometry . |
10,509 | public static Geometry toLineString ( Coordinate c1 , Coordinate c2 ) { Geometry lineString = new Geometry ( Geometry . LINE_STRING , 0 , - 1 ) ; lineString . setCoordinates ( new Coordinate [ ] { ( Coordinate ) c1 . clone ( ) , ( Coordinate ) c2 . clone ( ) } ) ; return lineString ; } | Create a new linestring based on the specified coordinates . |
10,510 | public static int getNumPoints ( Geometry geometry ) { if ( geometry == null ) { throw new IllegalArgumentException ( "Cannot get total number of points for null geometry." ) ; } int count = 0 ; if ( geometry . getGeometries ( ) != null ) { for ( Geometry child : geometry . getGeometries ( ) ) { count += getNumPoints ( child ) ; } } if ( geometry . getCoordinates ( ) != null ) { count += geometry . getCoordinates ( ) . length ; } return count ; } | Return the total number of coordinates within the geometry . This add up all coordinates within the sub - geometries . |
10,511 | public static boolean isValid ( Geometry geometry , GeometryIndex index ) { validate ( geometry , index ) ; return validationContext . isValid ( ) ; } | Validates a geometry focusing on changes at a specific sub - level of the geometry . The sublevel is indicated by passing an index . The only checks are on intersection and containment we don t check on too few coordinates as we want to support incremental creation of polygons . |
10,512 | public static GeometryValidationState validate ( Geometry geometry ) { validationContext . clear ( ) ; if ( Geometry . LINE_STRING . equals ( geometry . getGeometryType ( ) ) ) { IndexedLineString lineString = helper . createLineString ( geometry ) ; validateLineString ( lineString ) ; } else if ( Geometry . LINEAR_RING . equals ( geometry . getGeometryType ( ) ) ) { IndexedLinearRing ring = helper . createLinearRing ( geometry ) ; validateLinearRing ( ring ) ; } else if ( Geometry . POLYGON . equals ( geometry . getGeometryType ( ) ) ) { IndexedPolygon polygon = helper . createPolygon ( geometry ) ; validatePolygon ( polygon ) ; } else if ( Geometry . MULTI_LINE_STRING . equals ( geometry . getGeometryType ( ) ) ) { IndexedMultiLineString multiLineString = helper . createMultiLineString ( geometry ) ; validateMultiLineString ( multiLineString ) ; } else if ( Geometry . MULTI_POLYGON . equals ( geometry . getGeometryType ( ) ) ) { IndexedMultiPolygon multiPolygon = helper . createMultiPolygon ( geometry ) ; validateMultiPolygon ( multiPolygon ) ; } return validationContext . getState ( ) ; } | Validate this geometry . |
10,513 | public static boolean intersects ( Geometry one , Geometry two ) { if ( one == null || two == null || isEmpty ( one ) || isEmpty ( two ) ) { return false ; } if ( Geometry . POINT . equals ( one . getGeometryType ( ) ) ) { return intersectsPoint ( one , two ) ; } else if ( Geometry . LINE_STRING . equals ( one . getGeometryType ( ) ) ) { return intersectsLineString ( one , two ) ; } else if ( Geometry . MULTI_POINT . equals ( one . getGeometryType ( ) ) || Geometry . MULTI_LINE_STRING . equals ( one . getGeometryType ( ) ) ) { return intersectsMultiSomething ( one , two ) ; } List < Coordinate > coords1 = new ArrayList < Coordinate > ( ) ; List < Coordinate > coords2 = new ArrayList < Coordinate > ( ) ; getAllCoordinates ( one , coords1 ) ; getAllCoordinates ( two , coords2 ) ; for ( int i = 0 ; i < coords1 . size ( ) - 1 ; i ++ ) { for ( int j = 0 ; j < coords2 . size ( ) - 1 ; j ++ ) { if ( MathService . intersectsLineSegment ( coords1 . get ( i ) , coords1 . get ( i + 1 ) , coords2 . get ( j ) , coords2 . get ( j + 1 ) ) ) { return true ; } } } return false ; } | Calculate whether or not two given geometries intersect each other . |
10,514 | public static double getLength ( Geometry geometry ) { double length = 0 ; if ( geometry . getGeometries ( ) != null ) { for ( Geometry child : geometry . getGeometries ( ) ) { length += getLength ( child ) ; } } if ( geometry . getCoordinates ( ) != null && ( Geometry . LINE_STRING . equals ( geometry . getGeometryType ( ) ) || Geometry . LINEAR_RING . equals ( geometry . getGeometryType ( ) ) ) ) { for ( int i = 0 ; i < geometry . getCoordinates ( ) . length - 1 ; i ++ ) { double deltaX = geometry . getCoordinates ( ) [ i + 1 ] . getX ( ) - geometry . getCoordinates ( ) [ i ] . getX ( ) ; double deltaY = geometry . getCoordinates ( ) [ i + 1 ] . getY ( ) - geometry . getCoordinates ( ) [ i ] . getY ( ) ; length += Math . sqrt ( deltaX * deltaX + deltaY * deltaY ) ; } } return length ; } | Return the length of the geometry . This adds up the length of all edges within the geometry . |
10,515 | public static double getDistance ( Geometry geometry , Coordinate coordinate ) { double minDistance = Double . MAX_VALUE ; if ( coordinate != null && geometry != null ) { if ( geometry . getGeometries ( ) != null ) { for ( Geometry child : geometry . getGeometries ( ) ) { double distance = getDistance ( child , coordinate ) ; if ( distance < minDistance ) { minDistance = distance ; } } } if ( geometry . getCoordinates ( ) != null ) { if ( geometry . getCoordinates ( ) . length == 1 ) { double distance = MathService . distance ( coordinate , geometry . getCoordinates ( ) [ 0 ] ) ; if ( distance < minDistance ) { minDistance = distance ; } } else if ( geometry . getCoordinates ( ) . length > 1 ) { for ( int i = 0 ; i < geometry . getCoordinates ( ) . length - 1 ; i ++ ) { double distance = MathService . distance ( geometry . getCoordinates ( ) [ i ] , geometry . getCoordinates ( ) [ i + 1 ] , coordinate ) ; if ( distance < minDistance ) { minDistance = distance ; } } } } } return minDistance ; } | Return the minimal distance between a coordinate and any vertex of a geometry . |
10,516 | private static boolean intersectsPoint ( Geometry point , Geometry geometry ) { if ( geometry . getGeometries ( ) != null ) { for ( Geometry child : geometry . getGeometries ( ) ) { if ( intersectsPoint ( point , child ) ) { return true ; } } } if ( geometry . getCoordinates ( ) != null ) { Coordinate coordinate = point . getCoordinates ( ) [ 0 ] ; if ( geometry . getCoordinates ( ) . length == 1 ) { return coordinate . equals ( geometry . getCoordinates ( ) [ 0 ] ) ; } else { for ( int i = 0 ; i < geometry . getCoordinates ( ) . length - 1 ; i ++ ) { double distance = MathService . distance ( geometry . getCoordinates ( ) [ i ] , geometry . getCoordinates ( ) [ i + 1 ] , coordinate ) ; if ( distance < DEFAULT_DOUBLE_DELTA ) { return true ; } } } } return false ; } | We assume neither is null or empty . |
10,517 | public void sendFile ( File file , OutputStream os ) throws IOException { FileInputStream is = null ; BufferedInputStream buf = null ; ; try { is = new FileInputStream ( file ) ; buf = new BufferedInputStream ( is ) ; int readBytes = 0 ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Writing file..." ) ; } while ( ( readBytes = buf . read ( ) ) != - 1 ) { os . write ( readBytes ) ; } os . flush ( ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "File written" ) ; } } finally { if ( is != null ) { is . close ( ) ; } if ( buf != null ) { buf . close ( ) ; } } } | Write a file to an OuputStream . |
10,518 | public static String toWkt ( Geometry geometry ) throws WktException { if ( Geometry . POINT . equals ( geometry . getGeometryType ( ) ) ) { return toWktPoint ( geometry ) ; } else if ( Geometry . LINE_STRING . equals ( geometry . getGeometryType ( ) ) || Geometry . LINEAR_RING . equals ( geometry . getGeometryType ( ) ) ) { return toWktLineString ( geometry ) ; } else if ( Geometry . POLYGON . equals ( geometry . getGeometryType ( ) ) ) { return toWktPolygon ( geometry ) ; } else if ( Geometry . MULTI_POINT . equals ( geometry . getGeometryType ( ) ) ) { return toWktMultiPoint ( geometry ) ; } else if ( Geometry . MULTI_LINE_STRING . equals ( geometry . getGeometryType ( ) ) ) { return toWktMultiLineString ( geometry ) ; } else if ( Geometry . MULTI_POLYGON . equals ( geometry . getGeometryType ( ) ) ) { return toWktMultiPolygon ( geometry ) ; } return "" ; } | Format a given geometry to Well Known Text . |
10,519 | private static int parseSrid ( String ewktPart ) { if ( ewktPart != null && ! "" . equals ( ewktPart ) ) { String [ ] parts = ewktPart . split ( "=" ) ; if ( parts . length == 2 ) { try { return Integer . parseInt ( parts [ 1 ] ) ; } catch ( Exception e ) { } } } return 0 ; } | Get the SRID from a string like SRDI = 4326 . Used in parsing EWKT . |
10,520 | private static Geometry parseWkt ( String wkt ) throws WktException { if ( wkt != null ) { int i1 = wkt . indexOf ( '(' ) ; int i2 = wkt . indexOf ( ' ' ) ; int i = Math . min ( i1 , i2 ) ; if ( i < 0 ) { i = ( i1 > 0 ? i1 : i2 ) ; } String type = null ; if ( i >= 0 ) { type = typeWktToGeom ( wkt . substring ( 0 , i ) . trim ( ) ) ; } if ( type == null ) { throw new WktException ( ERR_MSG + "type of geometry not supported" ) ; } if ( wkt . indexOf ( "EMPTY" ) >= 0 ) { return new Geometry ( type , 0 , 0 ) ; } Geometry geometry = new Geometry ( type , 0 , 0 ) ; String result = parse ( wkt . substring ( wkt . indexOf ( '(' ) ) , geometry ) ; if ( result . length ( ) != 0 ) { throw new WktException ( ERR_MSG + "unexpected ending \"" + result + "\"" ) ; } return geometry ; } throw new WktException ( ERR_MSG + "illegal argument; no WKT" ) ; } | Parse a WKT string . No EWKT here! |
10,521 | public static XmlPath parse ( String xmlPathQuery ) { if ( xmlPathQuery == null ) { throw new XmlPathException ( "The XML path query can not be a null value" ) ; } xmlPathQuery = xmlPathQuery . trim ( ) ; if ( ! xmlPathQuery . contains ( "/" ) ) { if ( "*" . equals ( xmlPathQuery ) ) { return new XmlPath ( new XmlPathAnyElement ( ) ) ; } else if ( "@*" . equals ( xmlPathQuery ) ) { return new XmlPath ( new XmlPathAnyAttributeElement ( ) ) ; } else if ( "node()" . equals ( xmlPathQuery ) ) { return new XmlPath ( new XmlPathAnyNode ( ) ) ; } else if ( xmlPathQuery . matches ( XmlPathNodenameAttribute . REGEX_MATCH ) ) { return new XmlPath ( new XmlPathNodenameAttribute ( xmlPathQuery ) ) ; } else if ( xmlPathQuery . matches ( XmlPathNodename . REGEX_MATCH ) ) { return new XmlPath ( new XmlPathNodename ( xmlPathQuery ) ) ; } } Matcher m = rePath . matcher ( xmlPathQuery ) ; if ( ! m . matches ( ) ) { throw new XmlPathException ( "Invalid xml path query: " + xmlPathQuery ) ; } XmlPath . Builder builder = XmlPath . builder ( ) ; m = rePathPart . matcher ( xmlPathQuery ) ; while ( m . find ( ) ) { String part = m . group ( 1 ) ; if ( "*" . equals ( part ) ) { builder . add ( new XmlPathAnyElement ( ) ) ; } else if ( "@*" . equals ( part ) ) { builder . add ( new XmlPathAnyAttributeElement ( ) ) ; } else if ( "node()" . equals ( part ) ) { builder . add ( new XmlPathAnyNode ( ) ) ; } else if ( part . matches ( XmlPathNodenameAttribute . REGEX_MATCH ) ) { builder . add ( new XmlPathNodenameAttribute ( part ) ) ; } else if ( part . matches ( XmlPathNodename . REGEX_MATCH ) ) { builder . add ( new XmlPathNodename ( part ) ) ; } else { throw new XmlPathException ( "Invalid part(" + part + ") in xml path query: " + xmlPathQuery ) ; } } return builder . construct ( ) ; } | Parse XML path query |
10,522 | public static int getTypeNumber ( TypeKind kind ) { switch ( kind ) { case BOOLEAN : case BYTE : case CHAR : case SHORT : case INT : case LONG : case FLOAT : case DOUBLE : case VOID : return kind . ordinal ( ) ; case DECLARED : case TYPEVAR : case ARRAY : return TypeKind . DECLARED . ordinal ( ) ; default : throw new IllegalArgumentException ( kind + " not valid" ) ; } } | Returns TypeKind ordinal for primitive types and DECLARED ordinal for DECLARED ARRAY and TYPEVAR |
10,523 | public static TypeMirror normalizeType ( TypeKind kind ) { switch ( kind ) { case BOOLEAN : case BYTE : case CHAR : case SHORT : case INT : case LONG : case FLOAT : case DOUBLE : return Typ . getPrimitiveType ( kind ) ; case DECLARED : case TYPEVAR : case ARRAY : return El . getTypeElement ( "java.lang.Object" ) . asType ( ) ; case VOID : return Typ . Void ; default : throw new IllegalArgumentException ( kind + " not valid" ) ; } } | Returns primitive type for primitive and java . lang . Object type for references |
10,524 | public static boolean isInteger ( TypeMirror type ) { switch ( type . getKind ( ) ) { case INT : case SHORT : case CHAR : case BYTE : case BOOLEAN : return true ; default : return false ; } } | Returns true if type is one of int short char byte or boolean |
10,525 | public static boolean isJavaConstantType ( TypeMirror type ) { switch ( type . getKind ( ) ) { case INT : case LONG : case FLOAT : case DOUBLE : return true ; case DECLARED : DeclaredType dt = ( DeclaredType ) type ; TypeElement te = ( TypeElement ) dt . asElement ( ) ; return "java.lang.String" . contentEquals ( te . getQualifiedName ( ) ) ; default : return false ; } } | Returns true if type is one of int long float double or java . lang . String |
10,526 | public static Object convert ( String constant , TypeKind kind ) { switch ( kind ) { case INT : return Integer . parseInt ( constant ) ; case LONG : return java . lang . Long . parseLong ( constant ) ; case FLOAT : return java . lang . Float . parseFloat ( constant ) ; case DOUBLE : return java . lang . Double . parseDouble ( constant ) ; default : throw new UnsupportedOperationException ( kind + "Not yet implemented" ) ; } } | Returns a Object of type type converted from constant |
10,527 | public Collection < FedoraResource > getChildren ( final String mixin ) throws FedoraException { Node mixinLiteral = null ; if ( mixin != null ) { mixinLiteral = NodeFactory . createLiteral ( mixin ) ; } final ExtendedIterator < Triple > it = graph . find ( Node . ANY , CONTAINS . asNode ( ) , Node . ANY ) ; final Set < FedoraResource > set = new HashSet < > ( ) ; while ( it . hasNext ( ) ) { final Node child = it . next ( ) . getObject ( ) ; if ( mixin == null || graph . contains ( child , HAS_MIXIN_TYPE . asNode ( ) , mixinLiteral ) ) { final String path = child . getURI ( ) . toString ( ) . replaceAll ( repository . getRepositoryUrl ( ) , "" ) ; if ( graph . contains ( child , HAS_MIXIN_TYPE . asNode ( ) , binaryType ) ) { set . add ( repository . getDatastream ( path ) ) ; } else { set . add ( repository . getObject ( path ) ) ; } } } return set ; } | Get the Object and Datastream nodes that are children of the current Object . |
10,528 | public long getTime ( String name ) { Long res = stats . get ( name ) ; return ( res == null ) ? - 1 : res . longValue ( ) ; } | Gets a time for a performance measurement . If no measurement with the specified name exists then it returns - 1 . |
10,529 | public String getStatistics ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( String key : stats . keySet ( ) ) { sb . append ( key ) ; sb . append ( ": " ) ; sb . append ( stats . get ( key ) ) ; sb . append ( "\n" ) ; } return sb . toString ( ) ; } | Returns a string with all the current statistics . |
10,530 | public static DateTime getDateTime ( final ResultSet rs , final String columnName ) throws SQLException { final Timestamp ts = rs . getTimestamp ( columnName ) ; return ( ts == null ) ? null : new DateTime ( ts ) ; } | Returns a DateTime object representing the date or null if the input is null . |
10,531 | public static DateTime getUTCDateTime ( final ResultSet rs , final String columnName ) throws SQLException { final Timestamp ts = rs . getTimestamp ( columnName ) ; return ( ts == null ) ? null : new DateTime ( ts ) . withZone ( DateTimeZone . UTC ) ; } | Returns a DateTime object representing the date in UTC or null if the input is null . |
10,532 | public static < T extends Enum < T > > T getEnum ( final ResultSet rs , final Class < T > enumType , final String columnName ) throws SQLException { final String str = rs . getString ( columnName ) ; return ( str == null ) ? null : Enum . valueOf ( enumType , str ) ; } | Returns an Enum representing the data or null if the input is null . |
10,533 | private Method methodExists ( Class < ? > clazz , String method , Class < ? > [ ] params ) { try { return clazz . getMethod ( method , params ) ; } catch ( NoSuchMethodException e ) { return null ; } } | Checks if a class method exists . |
10,534 | private Object invokeAction ( Object clazz , Method method , UrlInfo urlInfo , Object ... args ) throws IllegalAccessException , InvocationTargetException { if ( this . isRequestMethodServed ( method , urlInfo . getRequestMethod ( ) ) ) { return method . invoke ( clazz , args ) ; } else { throw new IllegalArgumentException ( "Method " + urlInfo . getController ( ) + "." + urlInfo . getAction ( ) + " doesn't accept requests by " + urlInfo . getRequestMethod ( ) + " HTTP_METHOD" ) ; } } | Invokes a method checking previously if that method accepts requests using a particular HTTP_METHOD . |
10,535 | public SecureUTF8String makePassword ( final SecureUTF8String masterPassword , final Account account , final String inputText ) throws Exception { return makePassword ( masterPassword , account , inputText , account . getUsername ( ) ) ; } | Generates a hash of the master password with settings from the account . It will use the username assigned to the account . |
10,536 | private SecureUTF8String hashTheData ( SecureUTF8String masterPassword , SecureUTF8String data , Account account ) throws Exception { final SecureUTF8String output = new SecureUTF8String ( ) ; final SecureUTF8String secureIteration = new SecureUTF8String ( ) ; SecureUTF8String intermediateOutput = null ; int count = 0 ; final int length = account . getLength ( ) ; try { while ( output . size ( ) < length ) { if ( count == 0 ) { intermediateOutput = runAlgorithm ( masterPassword , data , account ) ; } else { secureIteration . replace ( masterPassword ) ; secureIteration . append ( NEW_LINE ) ; secureIteration . append ( new SecureCharArray ( Integer . toString ( count ) ) ) ; intermediateOutput = runAlgorithm ( secureIteration , data , account ) ; secureIteration . erase ( ) ; } output . append ( intermediateOutput ) ; intermediateOutput . erase ( ) ; count ++ ; } } catch ( Exception e ) { output . erase ( ) ; throw e ; } finally { if ( intermediateOutput != null ) intermediateOutput . erase ( ) ; secureIteration . erase ( ) ; } return output ; } | Intermediate step of generating a password . Performs constant hashing until the resulting hash is long enough . |
10,537 | private SecureUTF8String runAlgorithm ( SecureUTF8String masterPassword , SecureUTF8String data , Account account ) throws Exception { SecureUTF8String output = null ; SecureCharArray digestChars = null ; SecureByteArray masterPasswordBytes = null ; SecureByteArray dataBytes = null ; try { masterPasswordBytes = new SecureByteArray ( masterPassword ) ; dataBytes = new SecureByteArray ( data ) ; if ( ! account . isHmac ( ) ) { dataBytes . prepend ( masterPasswordBytes ) ; } if ( account . isHmac ( ) ) { Mac mac ; String algoName = "HMAC" + account . getAlgorithm ( ) . getName ( ) ; mac = Mac . getInstance ( algoName , CRYPTO_PROVIDER ) ; mac . init ( new SecretKeySpec ( masterPasswordBytes . getData ( ) , algoName ) ) ; mac . reset ( ) ; mac . update ( dataBytes . getData ( ) ) ; digestChars = new SecureCharArray ( mac . doFinal ( ) ) ; } else { MessageDigest md = MessageDigest . getInstance ( account . getAlgorithm ( ) . getName ( ) , CRYPTO_PROVIDER ) ; digestChars = new SecureCharArray ( md . digest ( dataBytes . getData ( ) ) ) ; } output = rstr2any ( digestChars . getData ( ) , account . getCharacterSet ( ) , account . isTrim ( ) ) ; } catch ( Exception e ) { if ( output != null ) output . erase ( ) ; throw e ; } finally { if ( masterPasswordBytes != null ) masterPasswordBytes . erase ( ) ; if ( dataBytes != null ) dataBytes . erase ( ) ; if ( digestChars != null ) digestChars . erase ( ) ; } return output ; } | This performs the actual hashing . It obtains an instance of the hashing algorithm and feeds in the necessary data . |
10,538 | private void fill ( ) throws IOException { int i = in . read ( buf , 0 , buf . length ) ; if ( i > 0 ) { pos = 0 ; count = i ; } } | Fill up our buffer from the underlying input stream . Users of this method must ensure that they use all characters in the buffer before calling this method . |
10,539 | protected void populateCDs ( Map < String , List < String [ ] > > cdMap , String referencedComponentId , String featureId , String operator , String value , String unit ) { List < String [ ] > list ; if ( ! cdMap . containsKey ( referencedComponentId ) ) { list = new ArrayList < > ( ) ; cdMap . put ( referencedComponentId , list ) ; } else { list = cdMap . get ( referencedComponentId ) ; } list . add ( new String [ ] { featureId , operator , value , unit } ) ; } | Populates concrete domains information . |
10,540 | protected OntologyBuilder getOntologyBuilder ( VersionRows vr , String rootModuleId , String rootModuleVersion , Map < String , String > metadata ) { return new OntologyBuilder ( vr , rootModuleId , rootModuleVersion , metadata ) ; } | Hook method for subclasses to override . |
10,541 | public static List < File > sort ( File sortDir , List < File > files , Comparator < String > comparator ) { if ( sortDir == null ) { throw new DataUtilException ( "The sort directory parameter can't be a null value" ) ; } else if ( ! sortDir . exists ( ) ) { throw new DataUtilException ( "The sort directory doesn't exist" ) ; } if ( files == null ) { throw new DataUtilException ( "The files parameter can't be a null value" ) ; } List < File > sortedFiles = new ArrayList < File > ( ) ; for ( File file : files ) { FileInputStream inputStream = null ; BufferedWriter writer = null ; try { ArrayList < String > list = new ArrayList < String > ( ) ; inputStream = new FileInputStream ( file ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( inputStream , DataUtilDefaults . charSet ) ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { list . add ( line ) ; } inputStream . close ( ) ; inputStream = null ; Collections . sort ( list , comparator ) ; File sortedFile = File . createTempFile ( "sorted-" , ".part" , sortDir ) ; sortedFiles . add ( sortedFile ) ; writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( sortedFile . getAbsoluteFile ( ) , false ) , DataUtilDefaults . charSet ) ) ; for ( String item : list ) { writer . write ( item + DataUtilDefaults . lineTerminator ) ; } writer . flush ( ) ; writer . close ( ) ; writer = null ; } catch ( FileNotFoundException e ) { throw new DataUtilException ( e ) ; } catch ( UnsupportedEncodingException e ) { throw new DataUtilException ( e ) ; } catch ( IOException e ) { throw new DataUtilException ( e ) ; } finally { if ( inputStream != null ) { try { inputStream . close ( ) ; } catch ( IOException e ) { } } if ( writer != null ) { try { writer . close ( ) ; } catch ( IOException e ) { } } } } return sortedFiles ; } | This method sorts every file in a list of input files |
10,542 | public void processRecordInternally ( Record record ) { if ( record instanceof FormatRecord ) { FormatRecord fr = ( FormatRecord ) record ; _customFormatRecords . put ( Integer . valueOf ( fr . getIndexCode ( ) ) , fr ) ; } if ( record instanceof ExtendedFormatRecord ) { ExtendedFormatRecord xr = ( ExtendedFormatRecord ) record ; _xfRecords . add ( xr ) ; } } | Process the record ourselves but do not pass it on to the child Listener . |
10,543 | public int getFormatIndex ( CellValueRecordInterface cell ) { ExtendedFormatRecord xfr = _xfRecords . get ( cell . getXFIndex ( ) ) ; if ( xfr == null ) { logger . log ( POILogger . ERROR , "Cell " + cell . getRow ( ) + "," + cell . getColumn ( ) + " uses XF with index " + cell . getXFIndex ( ) + ", but we don't have that" ) ; return - 1 ; } return xfr . getFormatIndex ( ) ; } | Returns the index of the format string used by your cell or - 1 if none found |
10,544 | public static String readResourceAsStream ( String path ) { try { InputStream inputStream = ResourceUtil . getResourceAsStream ( path ) ; return ResourceUtil . readFromInputStreamIntoString ( inputStream ) ; } catch ( Exception e ) { throw new DataUtilException ( "Failed to load resource" , e ) ; } } | This method looks for a file on the provided path attempts to load it as a stream and returns it as a string |
10,545 | public static String readResource ( String path ) { try { File file = ResourceUtil . getResourceFile ( path ) ; return ResourceUtil . readFromFileIntoString ( file ) ; } catch ( Exception e ) { throw new DataUtilException ( "Failed to load resource" , e ) ; } } | This method looks for a file on the provided path and returns it as a string |
10,546 | private Geometry cloneRecursively ( Geometry geometry ) { Geometry clone = new Geometry ( geometry . geometryType , geometry . srid , geometry . precision ) ; if ( geometry . getGeometries ( ) != null ) { Geometry [ ] geometryClones = new Geometry [ geometry . getGeometries ( ) . length ] ; for ( int i = 0 ; i < geometry . getGeometries ( ) . length ; i ++ ) { geometryClones [ i ] = cloneRecursively ( geometry . getGeometries ( ) [ i ] ) ; } clone . setGeometries ( geometryClones ) ; } if ( geometry . getCoordinates ( ) != null ) { Coordinate [ ] coordinateClones = new Coordinate [ geometry . getCoordinates ( ) . length ] ; for ( int i = 0 ; i < geometry . getCoordinates ( ) . length ; i ++ ) { coordinateClones [ i ] = ( Coordinate ) geometry . getCoordinates ( ) [ i ] . clone ( ) ; } clone . setCoordinates ( coordinateClones ) ; } return clone ; } | Recursive cloning of geometries . |
10,547 | int resolveFieldIndex ( VariableElement field ) { TypeElement declaringClass = ( TypeElement ) field . getEnclosingElement ( ) ; String descriptor = Descriptor . getDesriptor ( field ) ; int index = resolveFieldIndex ( declaringClass , field . getSimpleName ( ) . toString ( ) , descriptor ) ; addIndexedElement ( index , field ) ; return index ; } | Returns the constant map index to field . If entry doesn t exist it is created . |
10,548 | private int resolveFieldIndex ( TypeElement declaringClass , String name , String descriptor ) { int size = 0 ; int index = 0 ; constantReadLock . lock ( ) ; try { size = getConstantPoolSize ( ) ; index = getRefIndex ( Fieldref . class , declaringClass . getQualifiedName ( ) . toString ( ) , name , descriptor ) ; } finally { constantReadLock . unlock ( ) ; } if ( index == - 1 ) { int ci = resolveClassIndex ( declaringClass ) ; int nati = resolveNameAndTypeIndex ( name , descriptor ) ; return addConstantInfo ( new Fieldref ( ci , nati ) , size ) ; } return index ; } | Returns the constant map index to field If entry doesn t exist it is created . |
10,549 | int resolveMethodIndex ( ExecutableElement method ) { int size = 0 ; int index = 0 ; constantReadLock . lock ( ) ; TypeElement declaringClass = ( TypeElement ) method . getEnclosingElement ( ) ; String declaringClassname = declaringClass . getQualifiedName ( ) . toString ( ) ; String descriptor = Descriptor . getDesriptor ( method ) ; String name = method . getSimpleName ( ) . toString ( ) ; try { size = getConstantPoolSize ( ) ; index = getRefIndex ( Methodref . class , declaringClassname , name , descriptor ) ; } finally { constantReadLock . unlock ( ) ; } if ( index == - 1 ) { int ci = resolveClassIndex ( declaringClass ) ; int nati = resolveNameAndTypeIndex ( name , descriptor ) ; index = addConstantInfo ( new Methodref ( ci , nati ) , size ) ; } addIndexedElement ( index , method ) ; return index ; } | Returns the constant map index to method If entry doesn t exist it is created . |
10,550 | final int resolveNameIndex ( CharSequence name ) { int size = 0 ; int index = 0 ; constantReadLock . lock ( ) ; try { size = getConstantPoolSize ( ) ; index = getNameIndex ( name ) ; } finally { constantReadLock . unlock ( ) ; } if ( index != - 1 ) { return index ; } else { return addConstantInfo ( new Utf8 ( name ) , size ) ; } } | Returns the constant map index to name If entry doesn t exist it is created . |
10,551 | int resolveNameAndTypeIndex ( String name , String descriptor ) { int size = 0 ; int index = 0 ; constantReadLock . lock ( ) ; try { size = getConstantPoolSize ( ) ; index = getNameAndTypeIndex ( name , descriptor ) ; } finally { constantReadLock . unlock ( ) ; } if ( index != - 1 ) { return index ; } else { int nameIndex = resolveNameIndex ( name ) ; int typeIndex = resolveNameIndex ( descriptor ) ; return addConstantInfo ( new NameAndType ( nameIndex , typeIndex ) , size ) ; } } | Returns the constant map index to name and type If entry doesn t exist it is created . |
10,552 | public void defineConstantField ( int modifier , String fieldName , int constant ) { DeclaredType dt = ( DeclaredType ) asType ( ) ; VariableBuilder builder = new VariableBuilder ( this , fieldName , dt . getTypeArguments ( ) , typeParameterMap ) ; builder . addModifiers ( modifier ) ; builder . addModifier ( Modifier . STATIC ) ; builder . setType ( Typ . IntA ) ; FieldInfo fieldInfo = new FieldInfo ( this , builder . getVariableElement ( ) , new ConstantValue ( this , constant ) ) ; addFieldInfo ( fieldInfo ) ; fieldInfo . readyToWrite ( ) ; } | Define constant field and set the constant value . |
10,553 | public void save ( ProcessingEnvironment env ) throws IOException { Filer filer = env . getFiler ( ) ; FileObject sourceFile = filer . createResource ( StandardLocation . CLASS_OUTPUT , El . getPackageOf ( this ) . getQualifiedName ( ) , getSimpleName ( ) + ".class" ) ; BufferedOutputStream bos = new BufferedOutputStream ( sourceFile . openOutputStream ( ) ) ; DataOutputStream dos = new DataOutputStream ( bos ) ; write ( dos ) ; dos . close ( ) ; System . err . println ( "wrote " + sourceFile . getName ( ) ) ; } | Saves subclass as class file |
10,554 | public void write ( DataOutput out ) throws IOException { addSignatureIfNeed ( ) ; out . writeInt ( magic ) ; out . writeShort ( minor_version ) ; out . writeShort ( major_version ) ; out . writeShort ( constant_pool . size ( ) + 1 ) ; for ( ConstantInfo ci : constant_pool ) { ci . write ( out ) ; } int modifier = ClassFlags . getModifier ( getModifiers ( ) ) ; modifier |= ClassFlags . ACC_SYNTHETIC | ClassFlags . ACC_PUBLIC | ClassFlags . ACC_SUPER ; out . writeShort ( modifier ) ; out . writeShort ( this_class ) ; out . writeShort ( super_class ) ; out . writeShort ( interfaces . size ( ) ) ; for ( int ii : interfaces ) { out . writeShort ( ii ) ; } out . writeShort ( fields . size ( ) ) ; for ( FieldInfo fi : fields ) { fi . write ( out ) ; } out . writeShort ( methods . size ( ) ) ; for ( MethodInfo mi : methods ) { mi . write ( out ) ; } out . writeShort ( attributes . size ( ) ) ; for ( AttributeInfo ai : attributes ) { ai . write ( out ) ; } } | Writes the class |
10,555 | public boolean matches ( LinkedList < Node > nodePath ) { if ( simplePattern ) { return items . get ( 0 ) . matches ( nodePath . getLast ( ) ) ; } if ( items . size ( ) != nodePath . size ( ) ) { return false ; } for ( int i = 0 ; i < items . size ( ) ; i ++ ) { if ( ! items . get ( i ) . matches ( nodePath . get ( i ) ) ) { return false ; } } return true ; } | Compare an XML node path with the path query |
10,556 | public Lexer newLexer ( String name ) { PyObject object = pythonInterpreter . get ( "get_lexer_by_name" ) ; object = object . __call__ ( new PyString ( name ) ) ; return new Lexer ( object ) ; } | Obtain a new lexer implementation based on the given lexer name . |
10,557 | public HtmlFormatter newHtmlFormatter ( String params ) { PyObject object = pythonInterpreter . eval ( "HtmlFormatter(" + params + ")" ) ; return new HtmlFormatter ( object ) ; } | Create a new HTMLFormatter object using the given parameters . |
10,558 | public String highlight ( String code , Lexer lexer , Formatter formatter ) { PyFunction function = pythonInterpreter . get ( "highlight" , PyFunction . class ) ; PyString pyCode = new PyString ( code ) ; PyObject pyLexer = lexer . getLexer ( ) ; PyObject pyFormatter = formatter . getFormatter ( ) ; return function . __call__ ( pyCode , pyLexer , pyFormatter ) . asString ( ) ; } | Highlight the given code piece using the provided lexer and formatter . |
10,559 | protected void putParam ( String name , Object object ) { this . response . getRequest ( ) . setAttribute ( name , object ) ; } | Adds an object to the request . If a page will be renderer and it needs some objects to work with this method a developer can add objects to the request so the page can obtain them . |
10,560 | void addToSubroutine ( final long id , final int nbSubroutines ) { if ( ( status & VISITED ) == 0 ) { status |= VISITED ; srcAndRefPositions = new int [ nbSubroutines / 32 + 1 ] ; } srcAndRefPositions [ ( int ) ( id >>> 32 ) ] |= ( int ) id ; } | Marks this basic block as belonging to the given subroutine . |
10,561 | void visitSubroutine ( final Label JSR , final long id , final int nbSubroutines ) { Label stack = this ; while ( stack != null ) { Label l = stack ; stack = l . next ; l . next = null ; if ( JSR != null ) { if ( ( l . status & VISITED2 ) != 0 ) { continue ; } l . status |= VISITED2 ; if ( ( l . status & RET ) != 0 ) { if ( ! l . inSameSubroutine ( JSR ) ) { Edge e = new Edge ( ) ; e . info = l . inputStackTop ; e . successor = JSR . successors . successor ; e . next = l . successors ; l . successors = e ; } } } else { if ( l . inSubroutine ( id ) ) { continue ; } l . addToSubroutine ( id , nbSubroutines ) ; } Edge e = l . successors ; while ( e != null ) { if ( ( l . status & Label . JSR ) == 0 || e != l . successors . next ) { if ( e . successor . next == null ) { e . successor . next = stack ; stack = e . successor ; } } e = e . next ; } } } | Finds the basic blocks that belong to a given subroutine and marks these blocks as belonging to this subroutine . This method follows the control flow graph to find all the blocks that are reachable from the current block WITHOUT following any JSR target . |
10,562 | public String serialize ( Object object ) { XStream xstream = new XStream ( ) ; return xstream . toXML ( object ) ; } | Serializes an object to XML using the default XStream converter . |
10,563 | public static void merge ( File mergeDir , List < File > sortedFiles , File mergedFile , Comparator < String > comparator ) { merge ( mergeDir , sortedFiles , mergedFile , comparator , MERGE_FACTOR ) ; } | Merge multiple files into a single file . Multi - pass approach where the merge factor controls how many passes that are required . This method uses the default merge factor for merging . |
10,564 | public static void merge ( File mergeDir , List < File > sortedFiles , File mergedFile , Comparator < String > comparator , int mergeFactor ) { LinkedList < File > mergeFiles = new LinkedList < File > ( sortedFiles ) ; LinkedList < BatchFile > batch = new LinkedList < BatchFile > ( ) ; try { while ( mergeFiles . size ( ) > 0 ) { batch . clear ( ) ; for ( int i = 0 ; i < mergeFactor && mergeFiles . size ( ) > 0 ; i ++ ) { batch . add ( new BatchFile ( mergeFiles . remove ( ) ) ) ; } File aggFile ; if ( mergeFiles . size ( ) > 0 ) { aggFile = File . createTempFile ( "merge-" , ".part" , mergeDir ) ; mergeFiles . addLast ( aggFile ) ; } else { aggFile = mergedFile ; } BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( aggFile . getAbsoluteFile ( ) , false ) , DataUtilDefaults . charSet ) ) ; String [ ] buffer = new String [ batch . size ( ) ] ; Arrays . fill ( buffer , null ) ; boolean [ ] inUse = new boolean [ batch . size ( ) ] ; Arrays . fill ( inUse , true ) ; boolean inUseFlag = true ; while ( inUseFlag ) { int index = - 1 ; String selected = null ; for ( int i = 0 ; i < batch . size ( ) ; i ++ ) { if ( inUse [ i ] ) { if ( buffer [ i ] == null ) { buffer [ i ] = batch . get ( i ) . getRow ( ) ; if ( buffer [ i ] == null ) { inUse [ i ] = false ; } } if ( buffer [ i ] != null ) { if ( index == - 1 ) { index = i ; selected = buffer [ i ] ; } else if ( comparator . compare ( buffer [ i ] , selected ) < 0 ) { index = i ; selected = buffer [ i ] ; } } } } if ( index >= 0 ) { writer . write ( buffer [ index ] + DataUtilDefaults . lineTerminator ) ; buffer [ index ] = null ; inUseFlag = true ; } else { inUseFlag = false ; } } writer . flush ( ) ; writer . close ( ) ; } } catch ( IOException e ) { throw new DataUtilException ( e ) ; } } | Merge multiple files into a single file . Multi - pass approach where the merge factor controls how many passes that are required . If a merge factor of X is specified then X files will be opened concurrently for merging . |
10,565 | public void readyToWrite ( ) { addSignatureIfNeed ( ) ; this . name_index = ( ( SubClass ) classFile ) . resolveNameIndex ( getSimpleName ( ) ) ; this . descriptor_index = ( ( SubClass ) classFile ) . resolveNameIndex ( Descriptor . getDesriptor ( this ) ) ; readyToWrite = true ; } | Call to this method tells that the Attribute is ready writing . This method must be called before constant pool is written . |
10,566 | private boolean bfsComparison ( Node root , Node other ) { if ( root instanceof Content || other instanceof Content ) { return root . equals ( other ) ; } if ( ! root . equals ( other ) ) { return false ; } List < Node > a = ( ( Element ) root ) . getChildElements ( ) ; List < Node > b = ( ( Element ) other ) . getChildElements ( ) ; if ( a . size ( ) != b . size ( ) ) { return false ; } for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( ! a . get ( i ) . equals ( b . get ( i ) ) ) { return false ; } } for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( ! bfsComparison ( a . get ( i ) , b . get ( i ) ) ) { return false ; } } return true ; } | A strict breadth - first search traversal to evaluate two XML trees against each other |
10,567 | private int bsfHashCode ( Node node , int result ) { result += 31 * node . hashCode ( ) ; if ( node instanceof Content ) { return result ; } Element elem = ( Element ) node ; List < Node > childElements = elem . getChildElements ( ) ; for ( Node childElement : childElements ) { result += 31 * childElement . hashCode ( ) ; } for ( Node child : childElements ) { if ( child instanceof Content ) { result += 31 * child . hashCode ( ) ; } else { result = bsfHashCode ( child , result ) ; } } return result ; } | Recursive hash code creator |
10,568 | private void deepCopy ( Element origElement , Element copyElement ) { List < Node > children = origElement . getChildElements ( ) ; for ( Node node : children ) { try { if ( node instanceof Content ) { Content content = ( Content ) ( ( Content ) node ) . clone ( ) ; copyElement . addChildElement ( content ) ; } else { Element element = ( Element ) ( ( Element ) node ) . clone ( ) ; copyElement . addChildElement ( element ) ; deepCopy ( ( Element ) node , element ) ; } } catch ( CloneNotSupportedException e ) { throw new XmlModelException ( "Unable to clone object" , e ) ; } } } | Deep copy recursive helper method . |
10,569 | public String makeJavaIdentifier ( String id ) { String jid = makeJavaId ( id ) ; String old = map . put ( jid , id ) ; if ( old != null && ! old . equals ( id ) ) { throw new IllegalArgumentException ( "both " + id + " and " + old + " makes the same java id " + jid ) ; } return jid ; } | Returns a String capable for java identifier . Throws IllegalArgumentException if same id was already created . |
10,570 | public String makeUniqueJavaIdentifier ( String id ) { String jid = makeJavaId ( id ) ; String old = map . put ( jid , id ) ; if ( old != null ) { String oid = jid ; for ( int ii = 1 ; old != null ; ii ++ ) { jid = oid + ii ; old = map . put ( jid , id ) ; } } return jid ; } | Returns a unique String capable for java identifier . |
10,571 | public void write ( String output ) throws MapReduceException { try { writer . write ( output + DataUtilDefaults . lineTerminator ) ; } catch ( IOException e ) { throw new MapReduceException ( "Failed to write to the output collector" , e ) ; } } | Write to the output collector |
10,572 | public void close ( ) throws MapReduceException { try { if ( writer != null ) { writer . flush ( ) ; writer . close ( ) ; } } catch ( IOException e ) { throw new MapReduceException ( "Failed to close the output collector" , e ) ; } } | Close the output collector |
10,573 | public static String pad ( int repeat , String str ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < repeat ; i ++ ) { sb . append ( str ) ; } return sb . toString ( ) ; } | This method will pad a String with a character or string |
10,574 | public void setFile ( File file , String attachmentFilename , String contentType ) { this . file = file ; this . attachmentFilename = attachmentFilename ; this . contentType = contentType ; } | Sets the file to send to the client . If a file is set then the framework will try to read it and write it into the response using a FileSerializer . |
10,575 | private Boolean existsPage ( String page ) throws MalformedURLException { LOGGER . debug ( "Searching page [{}]..." , page ) ; LOGGER . debug ( "Page's real path is [{}]" , this . context . getRealPath ( page ) ) ; File file = new File ( this . context . getRealPath ( page ) ) ; Boolean exists = file . exists ( ) ; LOGGER . debug ( "Page [{}]{}found" , page , ( exists ? " " : " not " ) ) ; return exists ; } | Checks if a given page exists in the container and could be served . |
10,576 | public static < T > Set < T > createSet ( T ... args ) { HashSet < T > newSet = new HashSet < T > ( ) ; Collections . addAll ( newSet , args ) ; return newSet ; } | Convenience method for building a set from vararg arguments |
10,577 | public static < T > Set < T > arrayToSet ( T [ ] array ) { return new HashSet < T > ( Arrays . asList ( array ) ) ; } | Convenience method for building a set from an array |
10,578 | public static < T > Set < T > intersection ( Set < T > setA , Set < T > setB ) { Set < T > intersection = new HashSet < T > ( setA ) ; intersection . retainAll ( setB ) ; return intersection ; } | This method finds the intersection between set A and set B |
10,579 | public static < T > Set < T > union ( Set < T > setA , Set < T > setB ) { Set < T > union = new HashSet < T > ( setA ) ; union . addAll ( setB ) ; return union ; } | This method finds the union of set A and set B |
10,580 | public static < T > Set < T > difference ( Set < T > setA , Set < T > setB ) { Set < T > difference = new HashSet < T > ( setA ) ; difference . removeAll ( setB ) ; return difference ; } | This method finds the difference between set A and set B i . e . set A minus set B |
10,581 | public static < T > Set < T > symmetricDifference ( Set < T > setA , Set < T > setB ) { Set < T > union = union ( setA , setB ) ; Set < T > intersection = intersection ( setA , setB ) ; return difference ( union , intersection ) ; } | This method finds the symmetric difference between set A and set B i . e . which items does not exist in either set A or set B . This is the opposite of the intersect of set A and set B . |
10,582 | public static < T > boolean isSubset ( Set < T > setA , Set < T > setB ) { return setB . containsAll ( setA ) ; } | This method returns true if set A is a subset of set B i . e . it answers the question if all items in A exists in B |
10,583 | public static < T > boolean isSuperset ( Set < T > setA , Set < T > setB ) { return setA . containsAll ( setB ) ; } | This method returns true if set A is a superset of set B i . e . it answers the question if A contains all items from B |
10,584 | public String getClassName ( ) { switch ( sort ) { case VOID : return "void" ; case BOOLEAN : return "boolean" ; case CHAR : return "char" ; case BYTE : return "byte" ; case SHORT : return "short" ; case INT : return "int" ; case FLOAT : return "float" ; case LONG : return "long" ; case DOUBLE : return "double" ; case ARRAY : StringBuilder sb = new StringBuilder ( getElementType ( ) . getClassName ( ) ) ; for ( int i = getDimensions ( ) ; i > 0 ; -- i ) { sb . append ( "[]" ) ; } return sb . toString ( ) ; case OBJECT : return new String ( buf , off , len ) . replace ( '/' , '.' ) . intern ( ) ; default : return null ; } } | Returns the binary name of the class corresponding to this type . This method must not be used on method types . |
10,585 | public static boolean matchUrl ( Account account , String url ) { for ( AccountPatternData pattern : account . getPatterns ( ) ) { AccountPatternType type = pattern . getType ( ) ; if ( type == AccountPatternType . REGEX ) { if ( regexMatch ( pattern . getPattern ( ) , url ) ) return true ; } else if ( type == AccountPatternType . WILDCARD ) { if ( globMatch ( pattern . getPattern ( ) , url ) ) return true ; } else { Logger logger = Logger . getLogger ( AccountPatternMatcher . class . getName ( ) ) ; logger . warning ( "Unknown pattern match type '" + type . toString ( ) + "' for account '" + account . getName ( ) + "' id='" + account . getId ( ) + "'" ) ; } } return account . getUrl ( ) . equalsIgnoreCase ( url ) ; } | Tests all patterns in an account for a match against the url string . |
10,586 | public static void deleteFilesByExtension ( File dir , String extension ) { if ( extension == null ) { throw new DataUtilException ( "Filename extension can not be a null value" ) ; } FilenameFilter filter = new FileExtensionFilenameFilter ( extension ) ; FileDeleter . deleteFiles ( dir , filter ) ; } | Delete files in a directory matching a file extension |
10,587 | public static void deleteFilesByRegex ( File dir , String regex ) { if ( regex == null ) { throw new DataUtilException ( "Filename regex can not be null" ) ; } FilenameFilter filter = new RegexFilenameFilter ( regex ) ; FileDeleter . deleteFiles ( dir , filter ) ; } | Delete files in a directory matching a regular expression |
10,588 | public static void deleteFiles ( File dir , FilenameFilter filter ) { if ( dir == null ) { throw new DataUtilException ( "The delete directory parameter can not be a null value" ) ; } else if ( ! dir . exists ( ) || ! dir . isDirectory ( ) ) { throw new DataUtilException ( "The delete directory does not exist: " + dir . getAbsolutePath ( ) ) ; } File [ ] files ; if ( filter == null ) { files = dir . listFiles ( ) ; } else { files = dir . listFiles ( filter ) ; } if ( files != null ) { for ( File file : files ) { if ( file . isFile ( ) ) { if ( ! file . delete ( ) ) { throw new DataUtilException ( "Failed to delete file: " + file . getAbsolutePath ( ) ) ; } } } } } | Delete files in a directory matching a filename filter |
10,589 | public static String readFromFileIntoString ( File file ) throws IOException { FileInputStream inputStream = new FileInputStream ( file ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream , "UTF-8" ) ) ; StringBuilder text = new StringBuilder ( ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { text . append ( line ) . append ( "\n" ) ; } inputStream . close ( ) ; return text . toString ( ) ; } | This method reads all data from a file into a String object |
10,590 | public static File writeStringToTempFile ( String prefix , String suffix , String data ) throws IOException { File testFile = File . createTempFile ( prefix , suffix ) ; BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( testFile . getAbsoluteFile ( ) , false ) , DataUtilDefaults . charSet ) ) ; writer . write ( data ) ; writer . flush ( ) ; writer . close ( ) ; return testFile ; } | This method writes all data from a string to a temp file . The file will be automatically deleted on JVM shutdown . |
10,591 | public static String createRandomData ( int rows , int rowLength , boolean skipTrailingNewline ) { Random random = new Random ( System . currentTimeMillis ( ) ) ; StringBuilder strb = new StringBuilder ( ) ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < rowLength ; j ++ ) { strb . append ( ( char ) ( ( ( int ) 'a' ) + random . nextFloat ( ) * 25 ) ) ; } if ( skipTrailingNewline || i < rows ) { strb . append ( "\n" ) ; } } return strb . toString ( ) ; } | This method creates test data containing letters between a - z |
10,592 | public static File createTmpDir ( String directoryName ) { File tmpDir = new File ( System . getProperty ( "java.io.tmpdir" ) ) ; File testDir = new File ( tmpDir , directoryName ) ; if ( ! testDir . mkdir ( ) ) { throw new ResourceUtilException ( "Can't create directory: " + testDir . getAbsolutePath ( ) ) ; } testDir . deleteOnExit ( ) ; return testDir ; } | This method will create a new directory in the system temp folder |
10,593 | public static Bbox setCenterPoint ( Bbox bbox , Coordinate center ) { double x = center . getX ( ) - 0.5 * bbox . getWidth ( ) ; double y = center . getY ( ) - 0.5 * bbox . getHeight ( ) ; return new Bbox ( x , y , bbox . getWidth ( ) , bbox . getHeight ( ) ) ; } | Translate a bounding box by applying a new center point . |
10,594 | public static boolean contains ( Bbox parent , Bbox child ) { if ( child . getX ( ) < parent . getX ( ) ) { return false ; } if ( child . getY ( ) < parent . getY ( ) ) { return false ; } if ( child . getMaxX ( ) > parent . getMaxX ( ) ) { return false ; } if ( child . getMaxY ( ) > parent . getMaxY ( ) ) { return false ; } return true ; } | Does one bounding box contain another? |
10,595 | public static boolean contains ( Bbox bbox , Coordinate coordinate ) { if ( bbox . getX ( ) >= coordinate . getX ( ) ) { return false ; } if ( bbox . getY ( ) >= coordinate . getY ( ) ) { return false ; } if ( bbox . getMaxX ( ) <= coordinate . getX ( ) ) { return false ; } if ( bbox . getMaxY ( ) <= coordinate . getY ( ) ) { return false ; } return true ; } | Is the given coordinate contained within the bounding box or not? If the coordinate is on the bounding box border it is considered outside . |
10,596 | public static boolean intersects ( Bbox one , Bbox two ) { if ( two . getX ( ) > one . getMaxX ( ) ) { return false ; } if ( two . getY ( ) > one . getMaxY ( ) ) { return false ; } if ( two . getMaxX ( ) < one . getX ( ) ) { return false ; } if ( two . getMaxY ( ) < one . getY ( ) ) { return false ; } return true ; } | Does one bounding box intersect another? |
10,597 | public static Bbox intersection ( Bbox one , Bbox two ) { if ( ! intersects ( one , two ) ) { return null ; } else { double minx = two . getX ( ) > one . getX ( ) ? two . getX ( ) : one . getX ( ) ; double maxx = two . getMaxX ( ) < one . getMaxX ( ) ? two . getMaxX ( ) : one . getMaxX ( ) ; double miny = two . getY ( ) > one . getY ( ) ? two . getY ( ) : one . getY ( ) ; double maxy = two . getMaxY ( ) < one . getMaxY ( ) ? two . getMaxY ( ) : one . getMaxY ( ) ; return new Bbox ( minx , miny , ( maxx - minx ) , ( maxy - miny ) ) ; } } | Calculates the intersection between 2 bounding boxes . |
10,598 | public static Bbox buffer ( Bbox bbox , double range ) { if ( range >= 0 ) { double r2 = range * 2 ; return new Bbox ( bbox . getX ( ) - range , bbox . getY ( ) - range , bbox . getWidth ( ) + r2 , bbox . getHeight ( ) + r2 ) ; } throw new IllegalArgumentException ( "Buffer range must always be positive." ) ; } | Return a new bounding box that has increased in size by adding a range to a given bounding box . |
10,599 | public static Bbox translate ( Bbox bbox , double deltaX , double deltaY ) { return new Bbox ( bbox . getX ( ) + deltaX , bbox . getY ( ) + deltaY , bbox . getWidth ( ) , bbox . getHeight ( ) ) ; } | Translate the given bounding box . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.