idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
10,500
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 .
174
10
10,501
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 .
259
9
10,502
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 .
88
20
10,503
private static Geometry parseWkt ( String wkt ) throws WktException { if ( wkt != null ) { int i1 = wkt . indexOf ( ' ' ) ; int i2 = wkt . indexOf ( ' ' ) ; // allow both '(' and ' (' 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!
300
12
10,504
public static XmlPath parse ( String xmlPathQuery ) { // validations if ( xmlPathQuery == null ) { throw new XmlPathException ( "The XML path query can not be a null value" ) ; } xmlPathQuery = xmlPathQuery . trim ( ) ; // simple patterns 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 ) ) ; } } // sub-tree patterns 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
570
5
10,505
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
110
26
10,506
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
127
14
10,507
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
52
13
10,508
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
109
17
10,509
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
102
9
10,510
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 .
254
16
10,511
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 .
37
23
10,512
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 .
83
9
10,513
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 .
56
16
10,514
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 .
68
18
10,515
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 .
75
15
10,516
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 .
54
8
10,517
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 .
125
18
10,518
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 .
50
24
10,519
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 { // add ye bit'o chaos 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 .
262
20
10,520
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 .
397
22
10,521
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 .
42
29
10,522
protected void populateCDs ( Map < String , List < String [ ] > > cdMap , String referencedComponentId , String featureId , String operator , String value , String unit ) { List < String [ ] > list ; // my ( $comp, $feature, $op, $value, $unit ) = @_; 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 .
143
6
10,523
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 .
55
9
10,524
public static List < File > sort ( File sortDir , List < File > files , Comparator < String > comparator ) { // validations 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" ) ; } // sort files List < File > sortedFiles = new ArrayList < File > ( ) ; for ( File file : files ) { FileInputStream inputStream = null ; BufferedWriter writer = null ; try { // readLine part into memory 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 ; // sort Collections . sort ( list , comparator ) ; // write sorted partial 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 ) { // intentionally, do nothing } } if ( writer != null ) { try { writer . close ( ) ; } catch ( IOException e ) { // intentionally, do nothing } } } } return sortedFiles ; }
This method sorts every file in a list of input files
525
11
10,525
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 .
92
16
10,526
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
119
17
10,527
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
75
23
10,528
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
68
16
10,529
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 .
244
8
10,530
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 .
84
17
10,531
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 ) { // add entry to constant pool 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 .
157
16
10,532
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 ) { // add entry to constant pool 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 .
220
16
10,533
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 .
96
16
10,534
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 .
128
18
10,535
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 .
142
10
10,536
public void save ( ProcessingEnvironment env ) throws IOException { Filer filer = env . getFiler ( ) ; //JavaFileObject sourceFile = filer.createClassFile(getQualifiedName(), superClass); 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
160
6
10,537
@ Override 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
283
4
10,538
public boolean matches ( LinkedList < Node > nodePath ) { if ( simplePattern ) { // simple pattern return items . get ( 0 ) . matches ( nodePath . getLast ( ) ) ; } // match the full pattern if ( items . size ( ) != nodePath . size ( ) ) { // different size return false ; } for ( int i = 0 ; i < items . size ( ) ; i ++ ) { if ( ! items . get ( i ) . matches ( nodePath . get ( i ) ) ) { // failed a comparison return false ; } } // pass all comparisons return true ; }
Compare an XML node path with the path query
129
9
10,539
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 .
59
15
10,540
public HtmlFormatter newHtmlFormatter ( String params ) { PyObject object = pythonInterpreter . eval ( "HtmlFormatter(" + params + ")" ) ; return new HtmlFormatter ( object ) ; }
Create a new HTMLFormatter object using the given parameters .
50
12
10,541
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 .
107
15
10,542
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 .
30
39
10,543
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 .
84
14
10,544
void visitSubroutine ( final Label JSR , final long id , final int nbSubroutines ) { // user managed stack of labels, to avoid using a recursive method // (recursivity can lead to stack overflow with very large methods) Label stack = this ; while ( stack != null ) { // removes a label l from the stack Label l = stack ; stack = l . next ; l . next = null ; if ( JSR != null ) { if ( ( l . status & VISITED2 ) != 0 ) { continue ; } l . status |= VISITED2 ; // adds JSR to the successors of l, if it is a RET block 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 the l block already belongs to subroutine 'id', continue if ( l . inSubroutine ( id ) ) { continue ; } // marks the l block as belonging to subroutine 'id' l . addToSubroutine ( id , nbSubroutines ) ; } // pushes each successor of l on the stack, except JSR targets Edge e = l . successors ; while ( e != null ) { // if the l block is a JSR block, then 'l.successors.next' leads // to the JSR target (see {@link #visitJumpInsn}) and must // therefore not be followed if ( ( l . status & Label . JSR ) == 0 || e != l . successors . next ) { // pushes e.successor on the stack if it not already added 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 .
430
52
10,545
public String serialize ( Object object ) { XStream xstream = new XStream ( ) ; return xstream . toXML ( object ) ; }
Serializes an object to XML using the default XStream converter .
32
13
10,546
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 .
52
35
10,547
public static void merge ( File mergeDir , List < File > sortedFiles , File mergedFile , Comparator < String > comparator , int mergeFactor ) { LinkedList < File > mergeFiles = new LinkedList < File > ( sortedFiles ) ; // merge all files LinkedList < BatchFile > batch = new LinkedList < BatchFile > ( ) ; try { while ( mergeFiles . size ( ) > 0 ) { // create batch batch . clear ( ) ; for ( int i = 0 ; i < mergeFactor && mergeFiles . size ( ) > 0 ; i ++ ) { batch . add ( new BatchFile ( mergeFiles . remove ( ) ) ) ; } // create aggregation file File aggFile ; if ( mergeFiles . size ( ) > 0 ) { // create new aggregate file aggFile = File . createTempFile ( "merge-" , ".part" , mergeDir ) ; mergeFiles . addLast ( aggFile ) ; } else { // create final file aggFile = mergedFile ; } BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( aggFile . getAbsoluteFile ( ) , false ) , DataUtilDefaults . charSet ) ) ; // process batch 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 ) { // load comparison buffer int index = - 1 ; String selected = null ; for ( int i = 0 ; i < batch . size ( ) ; i ++ ) { if ( inUse [ i ] ) { if ( buffer [ i ] == null ) { // need more data buffer [ i ] = batch . get ( i ) . getRow ( ) ; if ( buffer [ i ] == null ) { inUse [ i ] = false ; } } if ( buffer [ i ] != null ) { if ( index == - 1 ) { // set item index = i ; selected = buffer [ i ] ; } else if ( comparator . compare ( buffer [ i ] , selected ) < 0 ) { // replace item index = i ; selected = buffer [ i ] ; } } } } if ( index >= 0 ) { // select item and write to new aggregate file writer . write ( buffer [ index ] + DataUtilDefaults . lineTerminator ) ; buffer [ index ] = null ; inUseFlag = true ; } else { inUseFlag = false ; } } // no more data 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 .
592
43
10,548
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 .
81
24
10,549
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
207
16
10,550
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
138
5
10,551
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 .
148
6
10,552
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 .
87
21
10,553
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 .
92
9
10,554
@ Override 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
66
5
10,555
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
63
4
10,556
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
57
11
10,557
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 .
40
35
10,558
private Boolean existsPage ( String page ) throws MalformedURLException { // Searching the page... 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 .
129
15
10,559
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
50
12
10,560
public static < T > Set < T > arrayToSet ( T [ ] array ) { return new HashSet < T > ( Arrays . asList ( array ) ) ; }
Convenience method for building a set from an array
38
11
10,561
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
56
11
10,562
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
56
11
10,563
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
56
20
10,564
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 .
68
44
10,565
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
37
29
10,566
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
38
29
10,567
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 .
195
22
10,568
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 ( ) + "'" ) ; // meh } } return account . getUrl ( ) . equalsIgnoreCase ( url ) ; }
Tests all patterns in an account for a match against the url string .
202
15
10,569
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
72
9
10,570
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
69
9
10,571
public static void deleteFiles ( File dir , FilenameFilter filter ) { // validations 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 ( ) ) ; } // delete files 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
198
9
10,572
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
117
12
10,573
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 .
105
24
10,574
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 ) ' ' ) + random . nextFloat ( ) * 25 ) ) ; } if ( skipTrailingNewline || i < rows ) { strb . append ( "\n" ) ; } } return strb . toString ( ) ; }
This method creates test data containing letters between a - z
144
11
10,575
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
103
12
10,576
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 .
89
13
10,577
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?
106
8
10,578
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 .
109
28
10,579
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?
107
8
10,580
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 .
199
11
10,581
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 .
97
22
10,582
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 .
65
8
10,583
public String serialize ( Object object ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Serializing object to Json" ) ; } XStream xstream = new XStream ( new JettisonMappedXmlDriver ( ) ) ; String json = xstream . toXML ( object ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Object serialized well" ) ; } return json ; }
Serializes an object to Json .
102
8
10,584
public Object deserialize ( String jsonObject ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Deserializing Json object" ) ; } XStream xstream = new XStream ( new JettisonMappedXmlDriver ( ) ) ; Object obj = xstream . fromXML ( jsonObject ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Object deserialized" ) ; } return obj ; }
Deserializes a Json string representation to an object .
105
12
10,585
private Iterator < String > filterOutEmptyStrings ( final Iterator < String > splitted ) { return new Iterator < String > ( ) { String next = getNext ( ) ; @ Override public boolean hasNext ( ) { return next != null ; } @ Override public String next ( ) { if ( ! hasNext ( ) ) throw new NoSuchElementException ( ) ; String result = next ; next = getNext ( ) ; return result ; } public String getNext ( ) { while ( splitted . hasNext ( ) ) { String value = splitted . next ( ) ; if ( value != null && ! value . isEmpty ( ) ) { return value ; } } return null ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Its easier to understand if the logic for omit empty sequences is a filtering iterator
172
15
10,586
public static Envelope toJts ( Bbox bbox ) throws JtsConversionException { if ( bbox == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } return new Envelope ( bbox . getX ( ) , bbox . getMaxX ( ) , bbox . getY ( ) , bbox . getMaxY ( ) ) ; }
Convert a Geomajas bounding box to a JTS envelope .
89
16
10,587
public static com . vividsolutions . jts . geom . Coordinate toJts ( org . geomajas . geometry . Coordinate coordinate ) throws JtsConversionException { if ( coordinate == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } return new com . vividsolutions . jts . geom . Coordinate ( coordinate . getX ( ) , coordinate . getY ( ) ) ; }
Convert a Geomajas coordinate to a JTS coordinate .
98
14
10,588
public static Geometry fromJts ( com . vividsolutions . jts . geom . Geometry geometry ) throws JtsConversionException { if ( geometry == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } int srid = geometry . getSRID ( ) ; int precision = - 1 ; PrecisionModel precisionmodel = geometry . getPrecisionModel ( ) ; if ( ! precisionmodel . isFloating ( ) ) { precision = ( int ) Math . log10 ( precisionmodel . getScale ( ) ) ; } String geometryType = getGeometryType ( geometry ) ; Geometry dto = new Geometry ( geometryType , srid , precision ) ; if ( geometry . isEmpty ( ) ) { // nothing to do } else if ( geometry instanceof Point ) { dto . setCoordinates ( convertCoordinates ( geometry ) ) ; } else if ( geometry instanceof LinearRing ) { dto . setCoordinates ( convertCoordinates ( geometry ) ) ; } else if ( geometry instanceof LineString ) { dto . setCoordinates ( convertCoordinates ( geometry ) ) ; } else if ( geometry instanceof Polygon ) { Polygon polygon = ( Polygon ) geometry ; Geometry [ ] geometries = new Geometry [ polygon . getNumInteriorRing ( ) + 1 ] ; for ( int i = 0 ; i < geometries . length ; i ++ ) { if ( i == 0 ) { geometries [ i ] = fromJts ( polygon . getExteriorRing ( ) ) ; } else { geometries [ i ] = fromJts ( polygon . getInteriorRingN ( i - 1 ) ) ; } } dto . setGeometries ( geometries ) ; } else if ( geometry instanceof MultiPoint ) { dto . setGeometries ( convertGeometries ( geometry ) ) ; } else if ( geometry instanceof MultiLineString ) { dto . setGeometries ( convertGeometries ( geometry ) ) ; } else if ( geometry instanceof MultiPolygon ) { dto . setGeometries ( convertGeometries ( geometry ) ) ; } else { throw new JtsConversionException ( "Cannot convert geometry: Unsupported type." ) ; } return dto ; }
Convert a JTS geometry to a Geomajas geometry .
503
14
10,589
public static Bbox fromJts ( Envelope envelope ) throws JtsConversionException { if ( envelope == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } return new Bbox ( envelope . getMinX ( ) , envelope . getMinY ( ) , envelope . getWidth ( ) , envelope . getHeight ( ) ) ; }
Convert a JTS envelope to a Geomajas bounding box .
82
16
10,590
public static Coordinate fromJts ( com . vividsolutions . jts . geom . Coordinate coordinate ) throws JtsConversionException { if ( coordinate == null ) { throw new JtsConversionException ( "Cannot convert null argument" ) ; } return new Coordinate ( coordinate . x , coordinate . y ) ; }
Convert a GTS coordinate to a Geomajas coordinate .
71
14
10,591
public long writeTo ( File fileOrDirectory ) throws IOException { long written = 0 ; OutputStream fileOut = null ; try { // Only do something if this part contains a file if ( fileName != null ) { // Check if user supplied directory File file ; if ( fileOrDirectory . isDirectory ( ) ) { // Write it to that dir the user supplied, // with the filename it arrived with file = new File ( fileOrDirectory , fileName ) ; } else { // Write it to the file the user supplied, // ignoring the filename it arrived with file = fileOrDirectory ; } if ( policy != null ) { file = policy . rename ( file ) ; fileName = file . getName ( ) ; } fileOut = new BufferedOutputStream ( new FileOutputStream ( file ) ) ; written = write ( fileOut ) ; } } finally { if ( fileOut != null ) fileOut . close ( ) ; } return written ; }
Write this file part to a file or directory . If the user supplied a file we write it to that file and if they supplied a directory we write it to that directory with the filename that accompanied it . If this part doesn t contain a file this method does nothing .
200
54
10,592
public long writeTo ( OutputStream out ) throws IOException { long size = 0 ; // Only do something if this part contains a file if ( fileName != null ) { // Write it out size = write ( out ) ; } return size ; }
Write this file part to the given output stream . If this part doesn t contain a file this method does nothing .
52
23
10,593
long write ( OutputStream out ) throws IOException { // decode macbinary if this was sent if ( contentType . equals ( "application/x-macbinary" ) ) { out = new MacBinaryDecoderOutputStream ( out ) ; } long size = 0 ; int read ; byte [ ] buf = new byte [ 8 * 1024 ] ; while ( ( read = partInput . read ( buf ) ) != - 1 ) { out . write ( buf , 0 , read ) ; size += read ; } return size ; }
Internal method to write this file part ; doesn t check to see if it has contents first .
111
19
10,594
public static Xml readAllFromResource ( String resourceName ) { InputStream is = XmlReader . class . getResourceAsStream ( resourceName ) ; XmlReader reader = new XmlReader ( is ) ; Xml xml = reader . read ( "node()" ) ; reader . close ( ) ; return xml ; }
Read all XML content from a resource location
70
8
10,595
private void init ( InputStream inputStream ) { this . inputStream = inputStream ; currentPath = new LinkedList < Node > ( ) ; nodeQueue = new LinkedList < XmlNode > ( ) ; XMLInputFactory factory = XMLInputFactory . newInstance ( ) ; factory . setProperty ( "javax.xml.stream.isCoalescing" , true ) ; factory . setProperty ( "javax.xml.stream.isReplacingEntityReferences" , true ) ; try { reader = factory . createXMLStreamReader ( inputStream ) ; } catch ( XMLStreamException e ) { throw new XmlReaderException ( e ) ; } }
Initialize XML reader for processing
144
6
10,596
public boolean find ( String xmlPathQuery ) { XmlPath xmlPath = XmlPathParser . parse ( xmlPathQuery ) ; XmlNode node ; while ( ( node = pullXmlNode ( ) ) != null ) { if ( node instanceof XmlStartElement ) { XmlStartElement startElement = ( XmlStartElement ) node ; Element element = new Element ( startElement . getLocalName ( ) ) ; element . addAttributes ( startElement . getAttributes ( ) ) ; currentPath . addLast ( element ) ; if ( xmlPath . matches ( currentPath ) ) { nodeQueue . push ( node ) ; currentPath . removeLast ( ) ; return true ; } } else if ( node instanceof XmlEndElement ) { if ( currentPath . getLast ( ) instanceof Content ) { currentPath . removeLast ( ) ; } currentPath . removeLast ( ) ; } else if ( node instanceof XmlContent ) { XmlContent content = ( XmlContent ) node ; if ( currentPath . getLast ( ) instanceof Content ) { currentPath . removeLast ( ) ; } currentPath . addLast ( new Content ( content . getText ( ) ) ) ; } else { throw new XmlReaderException ( "Unknown XmlNode type: " + node ) ; } } return false ; }
Find position in input stream that matches XML path query
283
10
10,597
private XmlNode pullXmlNode ( ) { // read from queue if ( ! nodeQueue . isEmpty ( ) ) { return nodeQueue . poll ( ) ; } // read from stream try { while ( reader . hasNext ( ) ) { int event = reader . next ( ) ; switch ( event ) { case XMLStreamConstants . START_ELEMENT : return new XmlStartElement ( reader . getLocalName ( ) , getAttributes ( reader ) ) ; case XMLStreamConstants . CHARACTERS : // capture XML? String text = filterWhitespace ( reader . getText ( ) ) ; if ( text . length ( ) > 0 ) { return new XmlContent ( text ) ; } break ; case XMLStreamConstants . END_ELEMENT : return new XmlEndElement ( reader . getLocalName ( ) ) ; default : // do nothing } } } catch ( XMLStreamException e ) { throw new XmlReaderException ( e ) ; } // nothing to return return null ; }
Pull an XML node object from the input stream
216
9
10,598
private String filterWhitespace ( String text ) { text = text . replace ( "\n" , " " ) ; text = text . replaceAll ( " {2,}" , " " ) ; text = XmlEscape . escape ( text ) ; return text . trim ( ) ; }
This method filters out white space characters
62
7
10,599
private List < Attribute > getAttributes ( XMLStreamReader reader ) { List < Attribute > list = new ArrayList < Attribute > ( ) ; for ( int i = 0 ; i < reader . getAttributeCount ( ) ; i ++ ) { list . add ( new Attribute ( reader . getAttributeLocalName ( i ) , reader . getAttributeValue ( i ) ) ) ; } return list ; }
Extract XML element attributes form XML input stream
87
9