idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
38,500 | public void shutdown ( ) { if ( executor != null ) { executor . shutdown ( ) ; executor = null ; } if ( timer != null ) { timer . cancel ( ) ; timer = null ; } instance = null ; } | Shuts down the task engine service . |
38,501 | private static String getColumnNameFromGetter ( Method getter , Field f ) { String columnName = "" ; Column columnAnno = getter . getAnnotation ( Column . class ) ; if ( columnAnno != null ) { columnName = columnAnno . name ( ) ; } if ( columnName == null || "" . equals ( columnName ) ) { columnName = IdUtils . toUnderscore ( f . getName ( ) ) ; } return columnName ; } | use getter to guess column name if there is annotation then use annotation value if not then guess from field name |
38,502 | public static SqlParamsPairs handleIn ( String sql , Object [ ] params ) { String [ ] sqlPieces = sql . split ( "\\?" ) ; String [ ] questionPlaceholders ; if ( sql . endsWith ( "?" ) ) { questionPlaceholders = new String [ sqlPieces . length ] ; } else { questionPlaceholders = new String [ sqlPieces . length - 1 ] ; } for ( int i = 0 ; i < questionPlaceholders . length ; i ++ ) { questionPlaceholders [ i ] = "?" ; } List < Object > plist = new ArrayList < Object > ( ) ; for ( int i = 0 ; i < params . length ; i ++ ) { Object p = params [ i ] ; if ( p . getClass ( ) . equals ( ArrayList . class ) ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "(" ) ; ArrayList inParams = ( ArrayList ) p ; for ( int j = 0 ; j < inParams . size ( ) ; j ++ ) { if ( j != 0 ) { sb . append ( "," ) ; } sb . append ( "?" ) ; plist . add ( inParams . get ( j ) ) ; } sb . append ( ")" ) ; questionPlaceholders [ i ] = sb . toString ( ) ; } else { plist . add ( p ) ; } } StringBuilder sqlsb = new StringBuilder ( ) ; for ( int i = 0 ; i < sqlPieces . length ; i ++ ) { sqlsb . append ( sqlPieces [ i ] ) ; if ( i < questionPlaceholders . length ) { sqlsb . append ( questionPlaceholders [ i ] ) ; } } SqlParamsPairs spPairs = new SqlParamsPairs ( sqlsb . toString ( ) , plist . toArray ( ) ) ; return spPairs ; } | Change sql if found array in params |
38,503 | public static String toCamel ( String name ) { return CaseFormat . LOWER_UNDERSCORE . to ( CaseFormat . LOWER_CAMEL , name ) ; } | Convert underscore style to camel style |
38,504 | public static String toUnderscore ( String name ) { return CaseFormat . LOWER_CAMEL . to ( CaseFormat . LOWER_UNDERSCORE , name ) ; } | Convert camel style to underscore style |
38,505 | private JdbcTemplateProxy getProxy ( ) { if ( _proxy == null ) { _proxy = new JdbcTemplateProxy ( ) ; _proxy . setJdbcTemplate ( jdbcTemplate ) ; } return _proxy ; } | return the singleton proxy |
38,506 | public int insert ( String sql , Object [ ] params , String autoGeneratedColumnName ) throws DataAccessException { sql = changeCatalog ( sql ) ; ReturnIdPreparedStatementCreator psc = new ReturnIdPreparedStatementCreator ( sql , params , autoGeneratedColumnName ) ; KeyHolder keyHolder = new GeneratedKeyHolder ( ) ; try { jdbcTemplate . update ( psc , keyHolder ) ; } catch ( DataAccessException e ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "[" ) ; for ( Object p : params ) { sb . append ( p + " | " ) ; } sb . append ( "]" ) ; logger . error ( "Error SQL: " + sql + " Params: " + sb . toString ( ) ) ; throw e ; } return keyHolder . getKey ( ) . intValue ( ) ; } | insert a row with auto increament id |
38,507 | public static String changeCatalog ( String sql ) { CatalogContext catalogContext = catalogContextHolder . get ( ) ; if ( catalogContext != null && catalogContext . getCatalog ( ) != null && catalogContext . getPlaceHolder ( ) != null ) { sql = sql . replace ( catalogContext . getPlaceHolder ( ) , catalogContext . getCatalog ( ) ) ; } logger . debug ( "real sql: " + sql ) ; return sql ; } | JdbcTemplateTool supports mulitiple catalog query . You can put a placeholder before your table name JdbcTemplateTool will change this placeholder to real catalog name with the catalog stored in catalogContext . |
38,508 | private void V ( StringBuilder buf ) { Token t = getNextToken ( ) ; if ( t . tokenType != TokenType . VALUE ) { throw new IllegalStateException ( "Unexpected token " + t ) ; } buf . append ( t . getValue ( ) ) ; t = getNextToken ( ) ; if ( t . tokenType == TokenType . EOL ) { return ; } else if ( t . tokenType == TokenType . TRAILING_BACKSLASH ) { Vopt ( buf ) ; } } | Vopt = EOL V |
38,509 | public List < Cal10nError > verifyAllLocales ( ) { List < Cal10nError > errorList = new ArrayList < Cal10nError > ( ) ; String [ ] localeNameArray = getLocaleNames ( ) ; ErrorFactory errorFactory = new ErrorFactory ( enumTypeAsStr , null , getBaseName ( ) ) ; if ( localeNameArray == null || localeNameArray . length == 0 ) { errorList . add ( errorFactory . buildError ( MISSING_LOCALE_DATA_ANNOTATION , "*" ) ) ; return errorList ; } for ( String localeName : localeNameArray ) { Locale locale = MiscUtil . toLocale ( localeName ) ; List < Cal10nError > tmpList = verify ( locale ) ; errorList . addAll ( tmpList ) ; } return errorList ; } | Verify all declared locales in one step . |
38,510 | private double [ ] readListProperty ( final ListProperty property ) throws IOException { int valueCount = ( int ) stream . read ( property . getCountType ( ) ) ; double [ ] values = new double [ valueCount ] ; for ( int i = 0 ; i < values . length ; i ++ ) { values [ i ] = stream . read ( property . getType ( ) ) ; } return values ; } | Reads the values of a list - property . |
38,511 | static HeaderEntry parse ( final String elementLine ) throws IOException { if ( ! elementLine . startsWith ( "element " ) ) { throw new IOException ( "not an element: '" + elementLine + "'" ) ; } String definition = elementLine . substring ( "element " . length ( ) ) ; String [ ] parts = definition . split ( " +" , 2 ) ; if ( parts . length != 2 ) { throw new IOException ( "Expected two parts in element definition: '" + elementLine + "'" ) ; } String name = parts [ 0 ] ; String countStr = parts [ 1 ] ; int count ; try { count = Integer . parseInt ( countStr ) ; } catch ( NumberFormatException e ) { throw new IOException ( "Invalid element entry. Not an integer: '" + countStr + "'." ) ; } return new HeaderEntry ( name , count ) ; } | Parses a header line starting an element description . |
38,512 | public RandomElementReader getElementReader ( final String elementType ) throws IOException { if ( elementType == null ) { throw new NullPointerException ( "elementType must not be null." ) ; } if ( ! buffer . containsKey ( elementType ) ) { throw new IllegalArgumentException ( "No such element type." ) ; } if ( closed ) { throw new IllegalStateException ( "Reader is closed." ) ; } while ( buffer . get ( elementType ) == null ) { ElementReader eReader = reader . nextElementReader ( ) ; BufferedElementReader bReader = new BufferedElementReader ( eReader ) ; bReader . detach ( ) ; buffer . put ( eReader . getElementType ( ) . getName ( ) , bReader ) ; } return buffer . get ( elementType ) . duplicate ( ) ; } | Returns an element reader for the given element type . |
38,513 | static Property parse ( final String propertyLine ) throws IOException { if ( ! propertyLine . startsWith ( "property " ) ) { throw new IOException ( "not a property: '" + propertyLine + "'" ) ; } String definition = propertyLine . substring ( "property " . length ( ) ) ; if ( definition . startsWith ( "list" ) ) { return ListProperty . parse ( propertyLine ) ; } String [ ] parts = definition . split ( " +" , 2 ) ; if ( parts . length != 2 ) { throw new IOException ( "Expected two parts in property definition: '" + propertyLine + "'" ) ; } String type = parts [ 0 ] ; String name = parts [ 1 ] ; DataType dataType ; try { dataType = DataType . parse ( type ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( e . getMessage ( ) ) ; } return new Property ( name , dataType ) ; } | Parses a property header line . |
38,514 | private String getSourceName ( final String property ) { if ( propertyNameMap . containsKey ( property ) ) { return propertyNameMap . get ( property ) ; } else { return property ; } } | Get the name of a property in the source type . |
38,515 | private double getValue ( final double x , final double y , final double z , final Axis axis ) { switch ( axis ) { case X : return x ; case X_INVERTED : return - x ; case Y : return y ; case Y_INVERTED : return - y ; case Z : return z ; case Z_INVERTED : return - z ; default : throw new IllegalArgumentException ( "Unsupported axis." ) ; } } | Returns the value of a given axis . |
38,516 | public void generateNormals ( final RandomElementReader vertexReader , final ElementReader faceReader ) throws IOException { if ( vertexReader == null ) { throw new NullPointerException ( "vertexReader must not be null." ) ; } if ( faceReader == null ) { throw new NullPointerException ( "faceReader must not be null." ) ; } if ( ! vertexReader . getElementType ( ) . getName ( ) . equals ( "vertex" ) ) { throw new IllegalArgumentException ( "vertexReader does not read vertices." ) ; } boolean foundX = false ; boolean foundY = false ; boolean foundZ = false ; for ( Property p : vertexReader . getElementType ( ) . getProperties ( ) ) { foundX |= p . getName ( ) . equals ( "x" ) && ! ( p instanceof ListProperty ) ; foundY |= p . getName ( ) . equals ( "y" ) && ! ( p instanceof ListProperty ) ; foundZ |= p . getName ( ) . equals ( "z" ) && ! ( p instanceof ListProperty ) ; } if ( ! foundX || ! foundY || ! foundZ ) { throw new IllegalArgumentException ( "Vertex type does not include" + " the three non-list properties x y and z." ) ; } if ( ! faceReader . getElementType ( ) . getName ( ) . equals ( "face" ) ) { throw new IllegalArgumentException ( "faceReader does not read faces." ) ; } boolean foundVertexIndex = false ; for ( Property p : faceReader . getElementType ( ) . getProperties ( ) ) { foundVertexIndex |= p . getName ( ) . equals ( "vertex_index" ) && ( p instanceof ListProperty ) ; } if ( ! foundVertexIndex ) { throw new IllegalArgumentException ( "Face type does not include a list property named " + "vertex_index." ) ; } for ( Element face = faceReader . readElement ( ) ; face != null ; face = faceReader . readElement ( ) ) { accumulateNormals ( vertexReader , face ) ; } for ( Element vertex = vertexReader . readElement ( ) ; vertex != null ; vertex = vertexReader . readElement ( ) ) { normalize ( vertex ) ; } } | Performs the normal generation . |
38,517 | private void normalize ( final Element vertex ) { double nx = vertex . getDouble ( "nx" ) ; double ny = vertex . getDouble ( "ny" ) ; double nz = vertex . getDouble ( "nz" ) ; double n = Math . sqrt ( nx * nx + ny * ny + nz * nz ) ; if ( n < EPSILON ) { vertex . setDouble ( "nx" , 0 ) ; vertex . setDouble ( "ny" , 0 ) ; vertex . setDouble ( "nz" , 0 ) ; } vertex . setDouble ( "nx" , nx / n ) ; vertex . setDouble ( "ny" , ny / n ) ; vertex . setDouble ( "nz" , nz / n ) ; } | Normalizes the normal vector of a vertex . |
38,518 | private void accumulateNormals ( final RandomElementReader vertices , final Element face ) throws IOException { int [ ] indices = face . getIntList ( "vertex_index" ) ; for ( int i = 0 ; i < indices . length ; i ++ ) { int pre ; int post ; if ( counterClockwise ) { pre = ( i + indices . length - 1 ) % indices . length ; post = ( i + 1 ) % indices . length ; } else { pre = ( i + 1 ) % indices . length ; post = ( i + indices . length - 1 ) % indices . length ; } Element centerVertex ; Element preVertex ; Element postVertex ; try { centerVertex = vertices . readElement ( indices [ i ] ) ; preVertex = vertices . readElement ( indices [ pre ] ) ; postVertex = vertices . readElement ( indices [ post ] ) ; accumulateNormal ( centerVertex , preVertex , postVertex ) ; } catch ( IndexOutOfBoundsException e ) { } } } | Calculate the face normal weight by angle and add them to the vertices . |
38,519 | private void accumulateNormal ( final Element center , final Element pre , final Element post ) { double cx = center . getDouble ( "x" ) ; double cy = center . getDouble ( "y" ) ; double cz = center . getDouble ( "z" ) ; double ax = post . getDouble ( "x" ) - cx ; double ay = post . getDouble ( "y" ) - cy ; double az = post . getDouble ( "z" ) - cz ; double a = Math . sqrt ( ax * ax + ay * ay + az * az ) ; if ( a < EPSILON ) { return ; } double bx = pre . getDouble ( "x" ) - cx ; double by = pre . getDouble ( "y" ) - cy ; double bz = pre . getDouble ( "z" ) - cz ; double b = Math . sqrt ( bx * bx + by * by + bz * bz ) ; if ( b < EPSILON ) { return ; } double nx = ay * bz - az * by ; double ny = az * bx - ax * bz ; double nz = ax * by - ay * bx ; double n = Math . sqrt ( nx * nx + ny * ny + nz * nz ) ; if ( n < EPSILON ) { return ; } double sin = n / ( a * b ) ; double dot = ax * bx + ay * by + az * bz ; double angle ; if ( dot < 0 ) { angle = Math . PI - Math . asin ( sin ) ; } else { angle = Math . asin ( sin ) ; } double factor = angle / n ; nx *= factor ; ny *= factor ; nz *= factor ; center . setDouble ( "nx" , center . getDouble ( "nx" ) + nx ) ; center . setDouble ( "ny" , center . getDouble ( "ny" ) + ny ) ; center . setDouble ( "nz" , center . getDouble ( "nz" ) + nz ) ; } | Calculate the face normal weight by angle and add them to the vertex . |
38,520 | private static RectBounds fillBuffers ( PlyReader plyReader , FloatBuffer vertexBuffer , IntBuffer indexBuffer ) throws IOException { ElementReader reader = plyReader . nextElementReader ( ) ; RectBounds bounds = null ; while ( reader != null ) { if ( reader . getElementType ( ) . getName ( ) . equals ( "vertex" ) ) { bounds = fillVertexBuffer ( reader , vertexBuffer ) ; } else if ( reader . getElementType ( ) . getName ( ) . equals ( "face" ) ) { fillIndexBuffer ( reader , indexBuffer ) ; } reader . close ( ) ; reader = plyReader . nextElementReader ( ) ; } return bounds ; } | Loads the data from the PLY file into the buffers . |
38,521 | private static RectBounds fillVertexBuffer ( ElementReader reader , FloatBuffer vertexBuffer ) throws IOException { Element vertex = reader . readElement ( ) ; RectBounds bounds = new RectBounds ( ) ; while ( vertex != null ) { double x = vertex . getDouble ( "x" ) ; double y = vertex . getDouble ( "y" ) ; double z = vertex . getDouble ( "z" ) ; double nx = vertex . getDouble ( "nx" ) ; double ny = vertex . getDouble ( "ny" ) ; double nz = vertex . getDouble ( "nz" ) ; vertexBuffer . put ( ( float ) x ) ; vertexBuffer . put ( ( float ) y ) ; vertexBuffer . put ( ( float ) z ) ; vertexBuffer . put ( ( float ) nx ) ; vertexBuffer . put ( ( float ) ny ) ; vertexBuffer . put ( ( float ) nz ) ; bounds . addPoint ( x , y , z ) ; vertex = reader . readElement ( ) ; } return bounds ; } | Fill the vertex buffer with the data from the PLY file . |
38,522 | private static void fillIndexBuffer ( ElementReader reader , IntBuffer indexBuffer ) throws IOException { Element triangle = reader . readElement ( ) ; while ( triangle != null ) { int [ ] indices = triangle . getIntList ( "vertex_index" ) ; for ( int index : indices ) { indexBuffer . put ( index ) ; } triangle = reader . readElement ( ) ; } } | Fill the index buffer with the data from the PLY file . |
38,523 | private static int createShaders ( ) throws IOException { String vertexShaderCode = IOUtils . toString ( ClassLoader . getSystemResourceAsStream ( "vertexShader.glsl" ) ) ; int vertexShaderId = glCreateShaderObjectARB ( GL_VERTEX_SHADER_ARB ) ; glShaderSourceARB ( vertexShaderId , vertexShaderCode ) ; glCompileShaderARB ( vertexShaderId ) ; printLogInfo ( vertexShaderId ) ; String fragmentShaderCode = IOUtils . toString ( ClassLoader . getSystemResourceAsStream ( "fragmentShader.glsl" ) ) ; int fragmentShaderId = glCreateShaderObjectARB ( GL_FRAGMENT_SHADER_ARB ) ; glShaderSourceARB ( fragmentShaderId , fragmentShaderCode ) ; glCompileShaderARB ( fragmentShaderId ) ; printLogInfo ( fragmentShaderId ) ; int programId = ARBShaderObjects . glCreateProgramObjectARB ( ) ; glAttachObjectARB ( programId , vertexShaderId ) ; glAttachObjectARB ( programId , fragmentShaderId ) ; glValidateProgramARB ( programId ) ; glLinkProgramARB ( programId ) ; printLogInfo ( programId ) ; return programId ; } | Loads the vertex and fragment shader . |
38,524 | private static boolean printLogInfo ( int obj ) { IntBuffer iVal = BufferUtils . createIntBuffer ( 1 ) ; ARBShaderObjects . glGetObjectParameterARB ( obj , ARBShaderObjects . GL_OBJECT_INFO_LOG_LENGTH_ARB , iVal ) ; int length = iVal . get ( ) ; if ( length > 1 ) { ByteBuffer infoLog = BufferUtils . createByteBuffer ( length ) ; iVal . flip ( ) ; ARBShaderObjects . glGetInfoLogARB ( obj , iVal , infoLog ) ; byte [ ] infoBytes = new byte [ length ] ; infoLog . get ( infoBytes ) ; String out = new String ( infoBytes ) ; System . out . println ( "Info log:\n" + out ) ; } else { return true ; } return false ; } | Helper to get the log messages from the shader compiler . |
38,525 | public String readLine ( ) throws IOException { StringBuilder str = new StringBuilder ( ) ; while ( true ) { int c = read ( ) ; if ( c < 0 ) { break ; } if ( c == '\n' ) { int peek = stream . read ( ) ; if ( peek != '\r' && peek >= 0 ) { stream . unread ( peek ) ; } break ; } if ( c == '\r' ) { int peek = stream . read ( ) ; if ( peek != '\n' && peek >= 0 ) { stream . unread ( peek ) ; } break ; } str . append ( ( char ) c ) ; } return str . toString ( ) ; } | Reads the next line . |
38,526 | public double getScaleToUnityBox ( ) { double largestEdge = 0 ; largestEdge = Math . max ( largestEdge , maxX - minX ) ; largestEdge = Math . max ( largestEdge , maxY - minY ) ; largestEdge = Math . max ( largestEdge , maxZ - minZ ) ; return 1.0 / largestEdge ; } | Gets the scale factor by which the box needs to be multiplied that it fits into a cube with edge length 1 . |
38,527 | private static ElementType addNormalProps ( final ElementType sourceType ) { List < Property > properties = new ArrayList < Property > ( ) ; boolean foundNX = false ; boolean foundNY = false ; boolean foundNZ = false ; for ( Property property : sourceType . getProperties ( ) ) { if ( property . getName ( ) . equals ( "nx" ) ) { foundNX = true ; } if ( property . getName ( ) . equals ( "ny" ) ) { foundNY = true ; } if ( property . getName ( ) . equals ( "nz" ) ) { foundNZ = true ; } properties . add ( property ) ; } if ( foundNX && foundNY && foundNZ ) { return sourceType ; } if ( ! foundNX ) { properties . add ( new Property ( "nx" , DataType . DOUBLE ) ) ; } if ( ! foundNY ) { properties . add ( new Property ( "ny" , DataType . DOUBLE ) ) ; } if ( ! foundNZ ) { properties . add ( new Property ( "nz" , DataType . DOUBLE ) ) ; } return new ElementType ( "vertex" , properties ) ; } | Adds properties for nx ny and nz if they don t already exist . |
38,528 | private static ElementType addTextureProps ( final ElementType sourceType ) { List < Property > properties = new ArrayList < Property > ( ) ; boolean foundU = false ; boolean foundV = false ; for ( Property property : sourceType . getProperties ( ) ) { if ( property . getName ( ) . equals ( "u" ) ) { foundU = true ; } if ( property . getName ( ) . equals ( "v" ) ) { foundV = true ; } properties . add ( property ) ; } if ( foundU && foundV ) { return sourceType ; } if ( ! foundU ) { properties . add ( new Property ( "u" , DataType . DOUBLE ) ) ; } if ( ! foundV ) { properties . add ( new Property ( "v" , DataType . DOUBLE ) ) ; } return new ElementType ( "vertex" , properties ) ; } | Adds properties for u and v if they don t already exist . |
38,529 | public void setDouble ( final String propertyName , final double value ) { if ( propertyName == null ) { throw new NullPointerException ( "propertyName must not be null." ) ; } Integer index = propertyMap . get ( propertyName ) ; if ( index == null ) { throw new IllegalArgumentException ( "non existent property: '" + propertyName + "'." ) ; } this . data [ index ] = new double [ ] { value } ; } | Sets the value of a property - list . If the property is a list the list will be set to a single entry . |
38,530 | static Property parse ( final String line ) throws IOException { if ( ! line . startsWith ( "property " ) ) { throw new IOException ( "not a property: '" + line + "'" ) ; } String definition = line . substring ( "property " . length ( ) ) ; definition = definition . trim ( ) ; if ( ! definition . startsWith ( "list " ) ) { throw new IllegalArgumentException ( "not a list property: '" + line + "'" ) ; } definition = definition . substring ( "list " . length ( ) ) ; definition = definition . trim ( ) ; String [ ] parts = definition . split ( " +" , 3 ) ; if ( parts . length != 3 ) { throw new IOException ( "Expected three parts in list property " + "definition: '" + line + "'" ) ; } String countType = parts [ 0 ] ; String type = parts [ 1 ] ; String name = parts [ 2 ] ; DataType dataType ; DataType countDataType ; try { dataType = DataType . parse ( type ) ; countDataType = DataType . parse ( countType ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( e . getMessage ( ) ) ; } return new ListProperty ( countDataType , name , dataType ) ; } | Parses a list - property header line . |
38,531 | public int getElementCount ( final String elementType ) { if ( elementType == null ) { throw new IllegalArgumentException ( "elementType must not be null." ) ; } Integer count = elementCounts . get ( elementType ) ; if ( count == null ) { throw new IllegalArgumentException ( "Type does not exist in this file." ) ; } else { return count ; } } | Gets the number of elements for a given element type . |
38,532 | private ElementReader nextElementReaderInternal ( ) { if ( nextElement >= elements . size ( ) ) { return null ; } try { ElementType type = elements . get ( nextElement ) ; switch ( format ) { case ASCII : return new AsciiElementReader ( type , getElementCount ( type . getName ( ) ) , asciiReader ) ; case BINARY_BIG_ENDIAN : case BINARY_LITTLE_ENDIAN : return new BinaryElementReader ( type , getElementCount ( type . getName ( ) ) , binaryStream ) ; default : throw new UnsupportedOperationException ( "PLY format " + format + " is currently not supported." ) ; } } finally { nextElement ++ ; } } | Creates the next element reader . |
38,533 | public double read ( final DataType type ) throws IOException { if ( type == null ) { throw new NullPointerException ( "type must not be null." ) ; } switch ( type ) { case CHAR : ensureAvailable ( 1 ) ; return buffer . get ( ) ; case UCHAR : ensureAvailable ( 1 ) ; return ( ( int ) buffer . get ( ) ) & 0x000000FF ; case SHORT : ensureAvailable ( 2 ) ; return buffer . getShort ( ) ; case USHORT : ensureAvailable ( 2 ) ; return ( ( int ) buffer . getShort ( ) ) & 0x0000FFFF ; case INT : ensureAvailable ( 4 ) ; return buffer . getInt ( ) ; case UINT : ensureAvailable ( 4 ) ; return ( ( long ) buffer . getShort ( ) ) & 0x00000000FFFFFFFF ; case FLOAT : ensureAvailable ( 4 ) ; return buffer . getFloat ( ) ; case DOUBLE : ensureAvailable ( 8 ) ; return buffer . getDouble ( ) ; default : throw new IllegalArgumentException ( "Unsupported type: " + type ) ; } } | Reads a value from the stream . |
38,534 | private void ensureAvailable ( final int bytes ) throws IOException { while ( buffer . remaining ( ) < bytes ) { buffer . compact ( ) ; if ( channel . read ( buffer ) < 0 ) { throw new EOFException ( ) ; } buffer . flip ( ) ; } } | Ensures that a certain amount of bytes are in the buffer ready to be read . |
38,535 | public static Node getFirstNode ( String mathml ) { try { return getFirstNode ( new CMMLInfo ( mathml ) ) ; } catch ( Exception e ) { logger . error ( "failed to get apply node" , e ) ; return null ; } } | Get the first node of the MathML - Content annotations within a MathML document . |
38,536 | public static Node getStrictCmml ( String mathml ) { try { CMMLInfo cmmlInfo = new CMMLInfo ( mathml ) . toStrictCmml ( ) ; return getFirstApplyNode ( cmmlInfo ) ; } catch ( Exception e ) { logger . error ( "failed to get apply node" , e ) ; return null ; } } | Get the first node of the MathML - Content annotations within a MathML document . Before the MathML document was converted to strict CMML and subsequently also converted to display only the abstract variation of the content dictionary . |
38,537 | public static Node getElement ( Node node , String xExpr , XPath xPath ) throws XPathExpressionException { return ( Node ) xPath . compile ( xExpr ) . evaluate ( node , XPathConstants . NODE ) ; } | Extracts a single node for the specified XPath expression . |
38,538 | public String transform ( Element formulaNode ) throws Exception , MathConverterException { formulaNode = consolidateMathMLNamespace ( formulaNode ) ; Content content = scanFormulaNode ( formulaNode ) ; String rawMathML ; if ( content == Content . pmml || content == Content . cmml || content == Content . mathml ) { Element mathEle = grabMathElement ( formulaNode ) ; formulaId = mathEle . getAttribute ( "id" ) ; if ( formulaId . equals ( "" ) ) { try { Element applyNode = ( Element ) XMLHelper . getElementB ( formulaNode , xPath . compile ( "//m:apply" ) ) ; formulaId = applyNode . getAttribute ( "id" ) ; } catch ( Exception e ) { logger . trace ( "can not find apply node " , e ) ; } } formulaName = mathEle . getAttribute ( "name" ) ; rawMathML = transformMML ( mathEle , content ) ; } else if ( content == Content . latex ) { rawMathML = convertLatex ( formulaNode . getTextContent ( ) ) ; } else { throw new MathConverterException ( "formula contains unknown or not recognized content" ) ; } return verifyMathML ( canonicalize ( rawMathML ) ) ; } | This method will scan the formula node extract necessary information and transform is into a well formatted MathML string containing the desired pMML and cMML semantics . |
38,539 | String verifyMathML ( String canMathML ) throws MathConverterException { try { Document tempDoc = XMLHelper . string2Doc ( canMathML , true ) ; Content content = scanFormulaNode ( ( Element ) tempDoc . getFirstChild ( ) ) ; if ( content == Content . mathml ) { return canMathML ; } else { throw new MathConverterException ( "could not verify produced mathml, content was: " + content . name ( ) ) ; } } catch ( Exception e ) { logger . error ( "could not verify mathml" , e ) ; throw new MathConverterException ( "could not verify mathml" ) ; } } | Just a quick scan over . |
38,540 | private Element grabMathElement ( Element formulaNode ) throws XPathExpressionException , MathConverterException { Element mathEle = Optional . ofNullable ( ( Element ) XMLHelper . getElementB ( formulaNode , xPath . compile ( "./*[1]" ) ) ) . orElseThrow ( ( ) -> new MathConverterException ( "no math element found" ) ) ; if ( mathEle . getNodeName ( ) . toLowerCase ( ) . contains ( "math" ) ) { return mathEle ; } throw new MathConverterException ( "no math element found" ) ; } | Tries to get the math element which should be next child following the formula node . |
38,541 | Element consolidateMathMLNamespace ( Element mathNode ) throws MathConverterException { try { Document tempDoc ; if ( isNsAware ( mathNode ) ) { tempDoc = mathNode . getOwnerDocument ( ) ; } else { tempDoc = XMLHelper . string2Doc ( XMLHelper . printDocument ( mathNode ) , true ) ; } new XmlNamespaceTranslator ( ) . setDefaultNamespace ( DEFAULT_NAMESPACE ) . addTranslation ( "m" , "http://www.w3.org/1998/Math/MathML" ) . addTranslation ( "mml" , "http://www.w3.org/1998/Math/MathML" ) . translateNamespaces ( tempDoc , "" ) ; Element root = ( Element ) tempDoc . getFirstChild ( ) ; removeAttribute ( root , "xmlns:mml" ) ; removeAttribute ( root , "xmlns:m" ) ; return root ; } catch ( Exception e ) { logger . error ( "namespace consolidation failed" , e ) ; throw new MathConverterException ( "namespace consolidation failed" ) ; } } | Should consolidate onto the default MathML namespace . |
38,542 | Content scanFormulaNode ( Element formulaNode ) throws Exception { Boolean containsSemantic = XMLHelper . getElementB ( formulaNode , xPath . compile ( "//m:semantics" ) ) != null ; Element annotationNode = ( Element ) XMLHelper . getElementB ( formulaNode , xPath . compile ( "//m:annotation-xml" ) ) ; Boolean containsCMML = annotationNode != null && annotationNode . getAttribute ( "encoding" ) . equals ( "MathML-Content" ) ; Boolean containsPMML = annotationNode != null && annotationNode . getAttribute ( "encoding" ) . equals ( "MathML-Presentation" ) ; NonWhitespaceNodeList applyNodes = new NonWhitespaceNodeList ( XMLHelper . getElementsB ( formulaNode , xPath . compile ( "//m:apply" ) ) ) ; containsCMML |= applyNodes . getLength ( ) > 0 ; NonWhitespaceNodeList mrowNodes = new NonWhitespaceNodeList ( XMLHelper . getElementsB ( formulaNode , xPath . compile ( "//m:mrow" ) ) ) ; containsPMML |= mrowNodes . getLength ( ) > 0 ; if ( containsSemantic ) { return containsCMML || containsPMML ? Content . mathml : Content . unknown ; } else { if ( containsCMML && containsPMML ) { return Content . unknown ; } else if ( containsCMML ) { return Content . cmml ; } else if ( containsPMML ) { return Content . pmml ; } } Element child = ( Element ) XMLHelper . getElementB ( formulaNode , "./*[1]" ) ; if ( child == null && StringUtils . isNotEmpty ( formulaNode . getTextContent ( ) ) ) { return Content . latex ; } return Content . unknown ; } | Tries to scan and interpret a formula node and guess its content format . |
38,543 | public static String canonicalize ( String mathml ) throws IOException , JDOMException , XMLStreamException , ModuleException { InputStream input = IOUtils . toInputStream ( mathml , StandardCharsets . UTF_8 . toString ( ) ) ; final ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; CANONICALIZER . canonicalize ( input , output ) ; String result = output . toString ( StandardCharsets . UTF_8 . toString ( ) ) ; result = result . replaceAll ( "\\r\\n|\\r|\\n" , System . getProperty ( "line.separator" ) ) ; return result ; } | Canonicalize an input MathML string . Line separators are system dependant . |
38,544 | @ SuppressWarnings ( "JavaDoc" ) public static Multiset < String > getIdentifiersFrom ( String mathml ) { Multiset < String > list = HashMultiset . create ( ) ; Pattern p = Pattern . compile ( "<((m:)?[mc][ion])(.*?)>(.{1,4}?)</\\1>" , Pattern . DOTALL ) ; Matcher m = p . matcher ( mathml ) ; while ( m . find ( ) ) { String identifier = m . group ( 4 ) ; list . add ( identifier ) ; } return list ; } | Returns a list of unique identifiers from a MathML string . This function searches for all mi - or ci - tags within the string . |
38,545 | public static Node getMainElement ( Document xml ) { NodeList expr = xml . getElementsByTagName ( "mws:expr" ) ; if ( expr . getLength ( ) > 0 ) { return new NonWhitespaceNodeList ( expr ) . item ( 0 ) ; } Node node = getContentMathMLNode ( xml ) ; if ( node != null ) { return node ; } expr = xml . getElementsByTagNameNS ( "*" , "semantics" ) ; if ( expr . getLength ( ) > 0 ) { return new NonWhitespaceNodeList ( expr ) . item ( 0 ) ; } expr = xml . getElementsByTagName ( "math" ) ; if ( expr . getLength ( ) > 0 ) { return new NonWhitespaceNodeList ( expr ) . item ( 0 ) ; } return null ; } | Returns the main element for which to begin generating the XQuery |
38,546 | private static String preLatexmlFixes ( String rawTex ) { Matcher matcher = LTXML_PATTERN . matcher ( rawTex ) ; if ( matcher . find ( ) ) { rawTex = "{" + rawTex + "}" ; } return rawTex ; } | LaTeXML Bug if there is \ math command at the beginning of the tex expression it needs to be wrapped in curly brackets . |
38,547 | public LaTeXMLServiceResponse parseAsService ( String latex ) { try { latex = UriComponentsBuilder . newInstance ( ) . queryParam ( "tex" , latex ) . build ( ) . encode ( StandardCharsets . UTF_8 . toString ( ) ) . getQuery ( ) ; } catch ( UnsupportedEncodingException ignore ) { LOG . warn ( "encoding not supported" , ignore ) ; } String serviceArguments = config . buildServiceRequest ( ) ; String payload = serviceArguments + "&" + latex ; RestTemplate restTemplate = new RestTemplate ( ) ; try { LaTeXMLServiceResponse rep = restTemplate . postForObject ( config . getUrl ( ) , payload , LaTeXMLServiceResponse . class ) ; LOG . debug ( String . format ( "LaTeXMLServiceResponse:\n" + "statusCode: %s\nstatus: %s\nlog: %s\nresult: %s" , rep . getStatusCode ( ) , rep . getStatus ( ) , rep . getLog ( ) , rep . getResult ( ) ) ) ; return rep ; } catch ( HttpClientErrorException e ) { LOG . error ( e . getResponseBodyAsString ( ) ) ; throw e ; } } | Call a LaTeXML service . |
38,548 | private static InputSource stringToSource ( String str ) { InputSource is = new InputSource ( new StringReader ( str ) ) ; is . setEncoding ( "UTF-8" ) ; return is ; } | Convert a string to an InputSource object |
38,549 | public static DocumentBuilderFactory getStandardDocumentBuilderFactory ( boolean validating ) { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; try { dbf . setValidating ( validating ) ; dbf . setFeature ( "http://xml.org/sax/features/validation" , validating ) ; dbf . setFeature ( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar" , validating ) ; dbf . setFeature ( "http://apache.org/xml/features/nonvalidating/load-external-dtd" , validating ) ; dbf . setFeature ( "http://apache.org/xml/features/validation/schema" , true ) ; dbf . setFeature ( "http://xml.org/sax/features/namespaces" , true ) ; dbf . setFeature ( "http://apache.org/xml/features/dom/include-ignorable-whitespace" , false ) ; } catch ( ParserConfigurationException pce ) { throw new RuntimeException ( "Cannot load standard DocumentBuilderFactory. " + pce . getMessage ( ) , pce ) ; } dbf . setNamespaceAware ( true ) ; dbf . setIgnoringComments ( true ) ; dbf . setExpandEntityReferences ( true ) ; return dbf ; } | This method creates a DocumentBuilderFactory that we will always need . |
38,550 | public final List < NtcirPattern > extractPatterns ( ) throws XPathExpressionException { final XPath xpath = XMLHelper . namespaceAwareXpath ( "t" , NS_NII ) ; final XPathExpression xNum = xpath . compile ( "./t:num" ) ; final XPathExpression xFormula = xpath . compile ( "./t:query/t:formula" ) ; final NonWhitespaceNodeList topicList = new NonWhitespaceNodeList ( topics . getElementsByTagNameNS ( NS_NII , "topic" ) ) ; for ( final Node node : topicList ) { final String num = xNum . evaluate ( node ) ; final NonWhitespaceNodeList formulae = new NonWhitespaceNodeList ( ( NodeList ) xFormula . evaluate ( node , XPathConstants . NODESET ) ) ; for ( final Node formula : formulae ) { final String id = formula . getAttributes ( ) . getNamedItem ( "id" ) . getTextContent ( ) ; final Node mathMLNode = NonWhitespaceNodeList . getFirstChild ( formula ) ; queryGenerator . setMainElement ( NonWhitespaceNodeList . getFirstChild ( mathMLNode ) ) ; patterns . add ( new NtcirPattern ( num , id , queryGenerator . toString ( ) , mathMLNode ) ) ; } } return patterns ; } | Splits the given NTCIR query file into individual queries converts each query into an XQuery using QVarXQueryGenerator and returns the result as a list of NtcirPatterns for each individual query . |
38,551 | public static ArrayList < Element > getChildElements ( Node node ) { ArrayList < Element > childElements = new ArrayList < > ( ) ; NodeList childNodes = node . getChildNodes ( ) ; for ( int i = 0 ; i < childNodes . getLength ( ) ; i ++ ) { if ( childNodes . item ( i ) instanceof Element ) { childElements . add ( ( Element ) childNodes . item ( i ) ) ; } } return childElements ; } | Only return child nodes that are elements - text nodes are ignored . |
38,552 | private void generateQvarConstraints ( ) { final StringBuilder qvarConstrBuilder = new StringBuilder ( ) ; final StringBuilder qvarMapStrBuilder = new StringBuilder ( ) ; final Iterator < Map . Entry < String , ArrayList < String > > > entryIterator = qvar . entrySet ( ) . iterator ( ) ; if ( entryIterator . hasNext ( ) ) { qvarMapStrBuilder . append ( "declare function local:qvarMap($x) {\n map {" ) ; while ( entryIterator . hasNext ( ) ) { final Map . Entry < String , ArrayList < String > > currentEntry = entryIterator . next ( ) ; final Iterator < String > valueIterator = currentEntry . getValue ( ) . iterator ( ) ; final String firstValue = valueIterator . next ( ) ; qvarMapStrBuilder . append ( '"' ) . append ( currentEntry . getKey ( ) ) . append ( '"' ) . append ( " : (data($x" ) . append ( firstValue ) . append ( "/@xml:id)" ) ; if ( valueIterator . hasNext ( ) ) { if ( qvarConstrBuilder . length ( ) > 0 ) { qvarConstrBuilder . append ( "\n and " ) ; } while ( valueIterator . hasNext ( ) ) { final String currentValue = valueIterator . next ( ) ; qvarMapStrBuilder . append ( ",data($x" ) . append ( currentValue ) . append ( "/@xml-id)" ) ; qvarConstrBuilder . append ( "$x" ) . append ( firstValue ) . append ( " = $x" ) . append ( currentValue ) ; if ( valueIterator . hasNext ( ) ) { qvarConstrBuilder . append ( " and " ) ; } } } qvarMapStrBuilder . append ( ')' ) ; if ( entryIterator . hasNext ( ) ) { qvarMapStrBuilder . append ( ',' ) ; } } qvarMapStrBuilder . append ( "}\n};" ) ; } qvarMapVariable = qvarMapStrBuilder . toString ( ) ; qvarConstraint = qvarConstrBuilder . toString ( ) ; } | Uses the qvar map to generate a XQuery string containing qvar constraints and the qvar map variable which maps qvar names to their respective formula ID s in the result . |
38,553 | public static double computeEarthMoverAbsoluteDistance ( Map < String , Double > h1 , Map < String , Double > h2 ) { Signature s1 = EarthMoverDistanceWrapper . histogramToSignature ( h1 ) ; Signature s2 = EarthMoverDistanceWrapper . histogramToSignature ( h2 ) ; return JFastEMD . distance ( s1 , s2 , 0.0 ) ; } | probably only makes sense to compute this on CI |
38,554 | private String generateSimpleConstraints ( Node node , boolean isRoot ) { int childElementIndex = 0 ; final StringBuilder out = new StringBuilder ( ) ; boolean queryHasText = false ; final NonWhitespaceNodeList nodeList = new NonWhitespaceNodeList ( node . getChildNodes ( ) ) ; for ( final Node child : nodeList ) { if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) { childElementIndex ++ ; boolean wasSpecialElement = handleSpecialElements ( child , childElementIndex ) ; if ( wasSpecialElement ) { continue ; } boolean annotationNode = child . getLocalName ( ) != null && XMLHelper . ANNOTATION_XML_PATTERN . matcher ( child . getLocalName ( ) ) . matches ( ) ; if ( ! annotationNode ) { if ( queryHasText ) { out . append ( " and " ) ; } else { queryHasText = true ; } if ( ! isRoot ) { out . append ( "*[" ) . append ( childElementIndex ) . append ( "]/name() = '" ) . append ( child . getLocalName ( ) ) . append ( "'" ) ; } if ( child . hasChildNodes ( ) ) { if ( ! isRoot ) { setRelativeXPath ( getRelativeXPath ( ) + "/*[" + childElementIndex + "]" ) ; out . append ( " and *[" ) . append ( childElementIndex ) . append ( "]" ) ; } final String constraint = generateSimpleConstraints ( child ) ; if ( ! constraint . isEmpty ( ) ) { out . append ( "[" ) . append ( constraint ) . append ( "]" ) ; } } } } else if ( child . getNodeType ( ) == Node . TEXT_NODE ) { out . append ( "./text() = '" ) . append ( child . getNodeValue ( ) . trim ( ) ) . append ( "'" ) ; } } if ( ! isRoot && isRestrictLength ( ) ) { setLengthConstraint ( ( getLengthConstraint ( ) . isEmpty ( ) ? "" : getLengthConstraint ( ) + "\n and " ) + "fn:count($x" + getRelativeXPath ( ) + "/*) = " + childElementIndex ) ; } if ( ! getRelativeXPath ( ) . isEmpty ( ) ) { String tmpRelativeXPath = getRelativeXPath ( ) . substring ( 0 , getRelativeXPath ( ) . lastIndexOf ( "/" ) ) ; setRelativeXPath ( tmpRelativeXPath ) ; } return out . toString ( ) ; } | Generates qvar map length constraint and returns exact match XQuery query for all child nodes of the given node . Called recursively to generate the query for the entire query document . |
38,555 | void copyIdField ( Element readNode ) { String newId = readNode . getAttribute ( "data-semantic-id" ) ; if ( ! StringUtils . isEmpty ( newId ) ) { readNode . setAttribute ( "id" , "p" + newId ) ; } for ( Node child : new NonWhitespaceNodeList ( readNode . getChildNodes ( ) ) ) { if ( child instanceof Element ) { copyIdField ( ( Element ) child ) ; } } } | Copy the data - semantic - id attribute to id if it does not exist . Will recursively go over every child . |
38,556 | public String convert ( String input , String type ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . APPLICATION_FORM_URLENCODED ) ; MultiValueMap < String , String > map = new LinkedMultiValueMap < > ( ) ; map . add ( "q" , input ) ; if ( ! type . isEmpty ( ) ) { map . add ( "type" , type ) ; } HttpEntity < MultiValueMap < String , String > > request = new HttpEntity < > ( map , headers ) ; try { String rep = new RestTemplate ( ) . postForObject ( mathoidConfig . getUrl ( ) , request , String . class ) ; logger . info ( rep ) ; return rep ; } catch ( HttpClientErrorException e ) { logger . error ( e . getResponseBodyAsString ( ) ) ; throw e ; } } | Request against Mathoid to receive an enriched MathML . Input format can be chosen . |
38,557 | public boolean isReachable ( ) { try { URL url = new URL ( mathoidConfig . getUrl ( ) + "/mml" ) ; SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory ( ) ; ClientHttpRequest req = factory . createRequest ( url . toURI ( ) , HttpMethod . POST ) ; req . execute ( ) ; return true ; } catch ( Exception e ) { return false ; } } | Returns true if the Mathoid service is reachable otherwise false . |
38,558 | public static JsonGouldiBean readGoldFile ( Path pathToSingleGoldFile ) throws IOException { File f = pathToSingleGoldFile . toFile ( ) ; ObjectMapper mapper = new ObjectMapper ( ) ; return mapper . readValue ( f , JsonGouldiBean . class ) ; } | Reads a gold file in json format from the given path . It will be stored as Java objects . |
38,559 | public static void writeGoldFile ( Path outputPath , JsonGouldiBean goldEntry ) { try { try { Files . createFile ( outputPath ) ; } catch ( FileAlreadyExistsException e ) { LOG . warn ( "File already exists!" ) ; } try ( Writer out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( outputPath . toFile ( ) ) , "UTF-8" ) ) ) { out . write ( goldEntry . toString ( ) ) ; } } catch ( IOException e ) { LOG . error ( e ) ; throw new RuntimeException ( e ) ; } } | Writes a gouldi entry to the given path . Note that if the file already exists it will be overwritten and logging a warning message . |
38,560 | @ SuppressWarnings ( "unchecked" ) @ JsonProperty ( "definitions" ) private void deserializeDefinitionsField ( Map < String , Object > defs ) { definitionsBean = new JsonGouldiDefinitionsBean ( ) ; LinkedList < JsonGouldiIdentifierDefinienBean > list = new LinkedList < > ( ) ; definitionsBean . setIdentifierDefiniens ( list ) ; for ( String key : defs . keySet ( ) ) { JsonGouldiIdentifierDefinienBean bean = new JsonGouldiIdentifierDefinienBean ( ) ; ArrayList < JsonGouldiWikidataDefinienBean > arrList = new ArrayList < > ( ) ; bean . setName ( key ) ; ArrayList < Object > identifierList = ( ArrayList < Object > ) defs . get ( key ) ; for ( Object obj : identifierList ) { if ( obj instanceof String ) { JsonGouldiTextDefinienBean textBean = new JsonGouldiTextDefinienBean ( ) ; textBean . setDiscription ( ( String ) obj ) ; arrList . add ( textBean ) ; } else { Map < String , String > qidMappings = ( Map < String , String > ) obj ; for ( String qID : qidMappings . keySet ( ) ) { JsonGouldiWikidataDefinienBean wikidefbean = new JsonGouldiWikidataDefinienBean ( ) ; wikidefbean . setWikiID ( qID ) ; wikidefbean . setDiscription ( qidMappings . get ( qID ) ) ; arrList . add ( wikidefbean ) ; } } } JsonGouldiWikidataDefinienBean [ ] arr = new JsonGouldiWikidataDefinienBean [ arrList . size ( ) ] ; arr = arrList . toArray ( arr ) ; bean . setDefiniens ( arr ) ; list . add ( bean ) ; } } | Provide a custom deserialization for definitions |
38,561 | public void highlightConsecutiveIdentifiers ( List < Integer > hashes , boolean backward ) { final int startPos = highlightFirstIdentifier ( hashes . get ( 0 ) , backward ) ; if ( startPos >= 0 ) { highlightRemainingIdentifiers ( hashes . subList ( 1 , hashes . size ( ) ) , startPos ) ; } } | Highlights consecutive occurrences of identifiers . |
38,562 | public List < Match > getSimilarities ( MathNode refTree , MathNode compTree , boolean onlyOperators ) { List < Match > similarities = new ArrayList < > ( ) ; findSimilarities ( refTree , compTree , similarities , false , onlyOperators ) ; return similarities ; } | Get a list of similarities between the reference and comparison tree . |
38,563 | boolean findSimilarities ( MathNode refTree , MathNode comTree , List < Match > similarities , boolean holdRefTree , boolean onlyOperators ) { if ( isIdenticalTree ( refTree , comTree ) ) { comTree . setMarked ( ) ; similarities . add ( new Match ( refTree , comTree , type ) ) ; return true ; } for ( MathNode compChild : comTree . getChildren ( ) ) { if ( compChild . isMarked ( ) || onlyOperators && compChild . isLeaf ( ) ) { continue ; } if ( findSimilarities ( refTree , compChild , similarities , true , onlyOperators ) ) { return true ; } } if ( ! holdRefTree ) { for ( MathNode refChild : refTree . getChildren ( ) ) { if ( onlyOperators && refChild . isLeaf ( ) ) { continue ; } findSimilarities ( refChild , comTree , similarities , false , onlyOperators ) ; } } return false ; } | Recursive method that goes along every node of the reference tree and tries to find identical subtree with the comparison tree . |
38,564 | boolean isIdenticalTree ( MathNode aTree , MathNode bTree ) { if ( aTree . equals ( bTree ) && aTree . getChildren ( ) . size ( ) == bTree . getChildren ( ) . size ( ) ) { if ( aTree . isOrderSensitive ( ) ) { for ( int i = 0 ; i < aTree . getChildren ( ) . size ( ) ; i ++ ) { if ( ! isIdenticalTree ( aTree . getChildren ( ) . get ( i ) , bTree . getChildren ( ) . get ( i ) ) ) { return false ; } } } else { List < MathNode > bChildren = new ArrayList < > ( bTree . getChildren ( ) ) ; OUTER : for ( MathNode aChild : aTree . getChildren ( ) ) { for ( MathNode bChild : filterSameChildren ( aChild , bChildren ) ) { if ( isIdenticalTree ( aChild , bChild ) ) { bChildren . remove ( bChild ) ; continue OUTER ; } } return false ; } } return true ; } return false ; } | Are aTree and bTree identical subtrees? If the root node is equal all subsequent children will be compared . |
38,565 | public static double getCoverage ( List < MathNode > refLeafs , List < MathNode > compLeafs ) { if ( compLeafs . size ( ) == 0 ) { return 1. ; } HashMultiset < MathNode > tmp = HashMultiset . create ( ) ; tmp . addAll ( compLeafs ) ; tmp . removeAll ( refLeafs ) ; return 1 - ( double ) tmp . size ( ) / ( double ) compLeafs . size ( ) ; } | Calculate the coverage factor between two trees whereas only their leafs are considered . Leafs are typically identifiers or constants . |
38,566 | public static String printMathNode ( MathNode node , String indent ) { StringBuilder sb = new StringBuilder ( indent + node . toString ( ) + "\n" ) ; node . getChildren ( ) . forEach ( n -> sb . append ( printMathNode ( n , indent + " " ) ) ) ; return sb . toString ( ) ; } | Converts a MathNode into a an simplistic indented tree representation of itself . |
38,567 | public static Map < String , Object > compareOriginalFactors ( String refMathML , String compMathML ) throws XPathExpressionException { try { CMMLInfo refDoc = new CMMLInfo ( refMathML ) ; CMMLInfo compDoc = new CMMLInfo ( compMathML ) ; final Integer depth = compDoc . getDepth ( refDoc . getXQuery ( ) ) ; final Double coverage = compDoc . getCoverage ( refDoc . getElements ( ) ) ; Boolean formula = compDoc . isEquation ( true ) ; Boolean structMatch = compDoc . toStrictCmml ( ) . abstract2CDs ( ) . isMatch ( refDoc . toStrictCmml ( ) . abstract2CDs ( ) . getXQuery ( ) ) ; Boolean dataMatch = new CMMLInfo ( compMathML ) . toStrictCmml ( ) . abstract2DTs ( ) . isMatch ( new CMMLInfo ( refMathML ) . toStrictCmml ( ) . abstract2DTs ( ) . getXQuery ( ) ) ; HashMap < String , Object > result = new HashMap < > ( ) ; result . put ( "depth" , depth ) ; result . put ( "coverage" , coverage ) ; result . put ( "structureMatch" , structMatch ) ; result . put ( "dataMatch" , dataMatch ) ; result . put ( "isEquation" , formula ) ; return result ; } catch ( Exception e ) { logger . error ( String . format ( "mathml comparison failed (refMathML: %s) (compMathML: %s)" , refMathML , compMathML ) , e ) ; throw e ; } } | Compare two MathML formulas . The return value is a map of similarity factors like matching depth element coverage indicator for structural or data match and if the comparison formula holds an equation . |
38,568 | public NativeResponse exec ( long timeoutMs , Level logLevel ) { return exec ( timeoutMs , TimeUnit . MILLISECONDS , logLevel ) ; } | Execute with a given timeout and sets the log level for the error output stream . |
38,569 | public NativeResponse exec ( long timeout , TimeUnit unit , Level logLevel ) { return internalexec ( timeout , unit , logLevel ) ; } | Combination of everything before . |
38,570 | private void safetyExit ( Process process ) throws IOException { process . getErrorStream ( ) . close ( ) ; process . getInputStream ( ) . close ( ) ; process . getOutputStream ( ) . close ( ) ; } | Has to be done in the end manually . Close all streams manually . |
38,571 | public static boolean commandCheck ( String nativeCommand ) { CommandExecutor executor = new CommandExecutor ( "DefinitionCheck" , "which" , nativeCommand ) ; NativeResponse res = executor . exec ( 100 ) ; return res . getStatusCode ( ) == 0 ; } | Checks if the given native command exists . No error will be thrown . The program waits for 100 milliseconds . That s enough to find out if the program exists or not . |
38,572 | public static String latexPreProcessing ( String latex ) { LOG . debug ( " Pre-Processing for: " + latex ) ; if ( latex . contains ( "subarray" ) ) { latex = latex . replaceAll ( "subarray" , "array" ) ; LOG . trace ( " Eval replacement of subarray: " + latex ) ; } latex = latex . replaceAll ( POM_BUG_AVOIDANCE_UNDERSCORE , "_{$1}" ) ; LOG . trace ( "Surround underscore: " + latex ) ; latex = latex . replaceAll ( SINGLE_AND , TMP_SINGLE_AND ) ; latex = HtmlEscape . unescapeHtml ( latex ) ; latex = latex . replaceAll ( TMP_SINGLE_AND , " & " ) ; LOG . trace ( "HTML Unescaped: " + latex ) ; latex = latex . replaceAll ( LATEX_COMMENTED_LINEBREAK , "" ) ; LOG . trace ( "Commented linebreaks: " + latex ) ; latex = latex . replaceAll ( ELEMINATE_ENDINGS , "" ) ; latex = latex . replaceAll ( ELEMINATE_STARTS , "" ) ; latex = latex . replaceAll ( ELEMINATE_SIMPLE_STARTS , "" ) ; latex = latex . replaceAll ( ELEMINATE_SIMPLE_ENDS , "" ) ; LOG . trace ( "Replace bad end/start:" + latex ) ; LOG . debug ( "Finalize Pre-Processing for POM-Tagger: " + latex ) ; return latex ; } | Pre processing mathematical latex expressions with several methods . |
38,573 | public static void save ( CommandLine commandLine , Root root ) { if ( commandLine . hasOption ( "dryrun" ) ) { return ; } FileOutputStream fileOutputStream = null ; BufferedOutputStream bufferedOutputStream = null ; try { JAXBContext contextObj = JAXBContext . newInstance ( Root . class ) ; Marshaller marshaller = contextObj . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , true ) ; if ( commandLine . hasOption ( "docencoding" ) ) { marshaller . setProperty ( Marshaller . JAXB_ENCODING , commandLine . getOptionValue ( "docencoding" ) ) ; } String filename = "javadoc.xml" ; if ( commandLine . hasOption ( "filename" ) ) { filename = commandLine . getOptionValue ( "filename" ) ; } if ( commandLine . hasOption ( "d" ) ) { filename = commandLine . getOptionValue ( "d" ) + File . separator + filename ; } fileOutputStream = new FileOutputStream ( filename ) ; bufferedOutputStream = new BufferedOutputStream ( fileOutputStream , 1024 * 1024 ) ; marshaller . marshal ( root , bufferedOutputStream ) ; bufferedOutputStream . flush ( ) ; fileOutputStream . flush ( ) ; } catch ( JAXBException e ) { log . error ( e . getMessage ( ) , e ) ; } catch ( FileNotFoundException e ) { log . error ( e . getMessage ( ) , e ) ; } catch ( IOException e ) { log . error ( e . getMessage ( ) , e ) ; } finally { try { if ( bufferedOutputStream != null ) { bufferedOutputStream . close ( ) ; } if ( fileOutputStream != null ) { fileOutputStream . close ( ) ; } } catch ( IOException e ) { log . error ( e . getMessage ( ) , e ) ; } } } | Save XML object model to a file via JAXB . |
38,574 | public static CommandLine parseCommandLine ( String [ ] [ ] optionsArrayArray ) { try { List < String > argumentList = new ArrayList < String > ( ) ; for ( String [ ] optionsArray : optionsArrayArray ) { argumentList . addAll ( Arrays . asList ( optionsArray ) ) ; } CommandLineParser commandLineParser = new BasicParser ( ) { protected void processOption ( final String arg , @ SuppressWarnings ( "rawtypes" ) final ListIterator iter ) throws ParseException { boolean hasOption = getOptions ( ) . hasOption ( arg ) ; if ( hasOption ) { super . processOption ( arg , iter ) ; } } } ; CommandLine commandLine = commandLineParser . parse ( options , argumentList . toArray ( new String [ ] { } ) ) ; return commandLine ; } catch ( ParseException e ) { LoggingOutputStream loggingOutputStream = new LoggingOutputStream ( log , LoggingLevelEnum . INFO ) ; PrintWriter printWriter = new PrintWriter ( loggingOutputStream ) ; HelpFormatter helpFormatter = new HelpFormatter ( ) ; helpFormatter . printHelp ( printWriter , 74 , "javadoc -doclet " + XmlDoclet . class . getName ( ) + " [options]" , null , options , 1 , 3 , null , false ) ; return null ; } } | Parse the given options . |
38,575 | public Root parseRootDoc ( RootDoc rootDoc ) { Root rootNode = objectFactory . createRoot ( ) ; for ( ClassDoc classDoc : rootDoc . classes ( ) ) { PackageDoc packageDoc = classDoc . containingPackage ( ) ; Package packageNode = packages . get ( packageDoc . name ( ) ) ; if ( packageNode == null ) { packageNode = parsePackage ( packageDoc ) ; packages . put ( packageDoc . name ( ) , packageNode ) ; rootNode . getPackage ( ) . add ( packageNode ) ; } if ( classDoc instanceof AnnotationTypeDoc ) { packageNode . getAnnotation ( ) . add ( parseAnnotationTypeDoc ( ( AnnotationTypeDoc ) classDoc ) ) ; } else if ( classDoc . isEnum ( ) ) { packageNode . getEnum ( ) . add ( parseEnum ( classDoc ) ) ; } else if ( classDoc . isInterface ( ) ) { packageNode . getInterface ( ) . add ( parseInterface ( classDoc ) ) ; } else { packageNode . getClazz ( ) . add ( parseClass ( classDoc ) ) ; } } return rootNode ; } | The entry point into parsing the javadoc . |
38,576 | protected Annotation parseAnnotationTypeDoc ( AnnotationTypeDoc annotationTypeDoc ) { Annotation annotationNode = objectFactory . createAnnotation ( ) ; annotationNode . setName ( annotationTypeDoc . name ( ) ) ; annotationNode . setQualified ( annotationTypeDoc . qualifiedName ( ) ) ; String comment = annotationTypeDoc . commentText ( ) ; if ( comment . length ( ) > 0 ) { annotationNode . setComment ( comment ) ; } annotationNode . setIncluded ( annotationTypeDoc . isIncluded ( ) ) ; annotationNode . setScope ( parseScope ( annotationTypeDoc ) ) ; for ( AnnotationTypeElementDoc annotationTypeElementDoc : annotationTypeDoc . elements ( ) ) { annotationNode . getElement ( ) . add ( parseAnnotationTypeElementDoc ( annotationTypeElementDoc ) ) ; } for ( AnnotationDesc annotationDesc : annotationTypeDoc . annotations ( ) ) { annotationNode . getAnnotation ( ) . add ( parseAnnotationDesc ( annotationDesc , annotationTypeDoc . qualifiedName ( ) ) ) ; } for ( Tag tag : annotationTypeDoc . tags ( ) ) { annotationNode . getTag ( ) . add ( parseTag ( tag ) ) ; } return annotationNode ; } | Parse an annotation . |
38,577 | protected AnnotationElement parseAnnotationTypeElementDoc ( AnnotationTypeElementDoc annotationTypeElementDoc ) { AnnotationElement annotationElementNode = objectFactory . createAnnotationElement ( ) ; annotationElementNode . setName ( annotationTypeElementDoc . name ( ) ) ; annotationElementNode . setQualified ( annotationTypeElementDoc . qualifiedName ( ) ) ; annotationElementNode . setType ( parseTypeInfo ( annotationTypeElementDoc . returnType ( ) ) ) ; AnnotationValue value = annotationTypeElementDoc . defaultValue ( ) ; if ( value != null ) { annotationElementNode . setDefault ( value . toString ( ) ) ; } return annotationElementNode ; } | Parse the elements of an annotation |
38,578 | protected AnnotationInstance parseAnnotationDesc ( AnnotationDesc annotationDesc , String programElement ) { AnnotationInstance annotationInstanceNode = objectFactory . createAnnotationInstance ( ) ; try { AnnotationTypeDoc annotTypeInfo = annotationDesc . annotationType ( ) ; annotationInstanceNode . setName ( annotTypeInfo . name ( ) ) ; annotationInstanceNode . setQualified ( annotTypeInfo . qualifiedTypeName ( ) ) ; } catch ( ClassCastException castException ) { log . error ( "Unable to obtain type data about an annotation found on: " + programElement ) ; log . error ( "Add to the classpath the class/jar that defines this annotation." ) ; } for ( AnnotationDesc . ElementValuePair elementValuesPair : annotationDesc . elementValues ( ) ) { AnnotationArgument annotationArgumentNode = objectFactory . createAnnotationArgument ( ) ; annotationArgumentNode . setName ( elementValuesPair . element ( ) . name ( ) ) ; Type annotationArgumentType = elementValuesPair . element ( ) . returnType ( ) ; annotationArgumentNode . setType ( parseTypeInfo ( annotationArgumentType ) ) ; annotationArgumentNode . setPrimitive ( annotationArgumentType . isPrimitive ( ) ) ; annotationArgumentNode . setArray ( annotationArgumentType . dimension ( ) . length ( ) > 0 ) ; Object objValue = elementValuesPair . value ( ) . value ( ) ; if ( objValue instanceof AnnotationValue [ ] ) { for ( AnnotationValue annotationValue : ( AnnotationValue [ ] ) objValue ) { if ( annotationValue . value ( ) instanceof AnnotationDesc ) { AnnotationDesc annoDesc = ( AnnotationDesc ) annotationValue . value ( ) ; annotationArgumentNode . getAnnotation ( ) . add ( parseAnnotationDesc ( annoDesc , programElement ) ) ; } else { annotationArgumentNode . getValue ( ) . add ( annotationValue . value ( ) . toString ( ) ) ; } } } else if ( objValue instanceof FieldDoc ) { annotationArgumentNode . getValue ( ) . add ( ( ( FieldDoc ) objValue ) . name ( ) ) ; } else if ( objValue instanceof ClassDoc ) { annotationArgumentNode . getValue ( ) . add ( ( ( ClassDoc ) objValue ) . qualifiedTypeName ( ) ) ; } else { annotationArgumentNode . getValue ( ) . add ( objValue . toString ( ) ) ; } annotationInstanceNode . getArgument ( ) . add ( annotationArgumentNode ) ; } return annotationInstanceNode ; } | Parses annotation instances of an annotable program element |
38,579 | protected EnumConstant parseEnumConstant ( FieldDoc fieldDoc ) { EnumConstant enumConstant = objectFactory . createEnumConstant ( ) ; enumConstant . setName ( fieldDoc . name ( ) ) ; String comment = fieldDoc . commentText ( ) ; if ( comment . length ( ) > 0 ) { enumConstant . setComment ( comment ) ; } for ( AnnotationDesc annotationDesc : fieldDoc . annotations ( ) ) { enumConstant . getAnnotation ( ) . add ( parseAnnotationDesc ( annotationDesc , fieldDoc . qualifiedName ( ) ) ) ; } for ( Tag tag : fieldDoc . tags ( ) ) { enumConstant . getTag ( ) . add ( parseTag ( tag ) ) ; } return enumConstant ; } | Parses an enum type definition |
38,580 | protected TypeParameter parseTypeParameter ( TypeVariable typeVariable ) { TypeParameter typeParameter = objectFactory . createTypeParameter ( ) ; typeParameter . setName ( typeVariable . typeName ( ) ) ; for ( Type bound : typeVariable . bounds ( ) ) { typeParameter . getBound ( ) . add ( bound . qualifiedTypeName ( ) ) ; } return typeParameter ; } | Parse type variables for generics |
38,581 | protected String parseScope ( ProgramElementDoc doc ) { if ( doc . isPrivate ( ) ) { return "private" ; } else if ( doc . isProtected ( ) ) { return "protected" ; } else if ( doc . isPublic ( ) ) { return "public" ; } return "" ; } | Returns string representation of scope |
38,582 | protected < I extends AdminToolValidationInterceptor < O > > void sortInterceptors ( List < I > interceptors ) { if ( ! CollectionUtils . isEmpty ( interceptors ) ) { int amount = interceptors != null ? interceptors . size ( ) : 0 ; LOGGER . debug ( amount + " interceptors configured for " + getMessageArea ( ) ) ; Collections . sort ( interceptors , new Comparator < I > ( ) { public int compare ( I o1 , I o2 ) { return Integer . compare ( o1 . getPrecedence ( ) , o2 . getPrecedence ( ) ) ; } } ) ; for ( AdminToolValidationInterceptor < O > interceptor : interceptors ) { LOGGER . debug ( " precedence: " + interceptor . getPrecedence ( ) + ", class: " + interceptor . getClass ( ) . getSimpleName ( ) ) ; } } } | sorts the interceptors against its precedence |
38,583 | protected < I extends AdminToolValidationInterceptor < O > > void intercept ( List < I > interceptors , O user , Set < ATError > errors ) { if ( ! CollectionUtils . isEmpty ( interceptors ) ) { for ( AdminToolValidationInterceptor < O > interceptor : interceptors ) { LOGGER . trace ( "calling validation interceptor's validate for: " + interceptor . getClass ( ) ) ; interceptor . validate ( user , errors , this ) ; } } } | calls the validate method on interceptors if not empty |
38,584 | protected < S extends Serializable > void validateDomainObject ( S domainObject , Set < ATError > errors ) { Set < ConstraintViolation < S > > constraintViolations = validator . validate ( domainObject ) ; if ( CollectionUtils . isEmpty ( constraintViolations ) ) { return ; } for ( ConstraintViolation < S > violation : constraintViolations ) { String type = violation . getConstraintDescriptor ( ) . getAnnotation ( ) . annotationType ( ) . getSimpleName ( ) ; String attrPath = violation . getPropertyPath ( ) . toString ( ) ; String msgKey = attrPath + "." + type ; if ( null != violation . getMessage ( ) && violation . getMessage ( ) . startsWith ( MSG_KEY_PREFIX ) ) { msgKey = violation . getMessage ( ) ; } errors . add ( new ATError ( ( attrPath + "." + type ) , getMessage ( msgKey , new Object [ ] { attrPath } , violation . getMessage ( ) ) , attrPath ) ) ; } } | validates a domain object with javax . validation annotations |
38,585 | public List < AdminComponent > getComponents ( ) { List < AdminComponent > result = new ArrayList < > ( ) ; for ( AdminComponent adminComponent : adminTool . getComponents ( ) ) { if ( null != adminComponent . getMainMenu ( ) ) { Stream < MenuEntry > nonHiddenMenues = adminComponent . getMainMenu ( ) . flattened ( ) . filter ( me -> ! me . isHide ( ) ) ; if ( nonHiddenMenues . count ( ) == 0L ) { LOGGER . trace ( "all menu entries hidden for component: " + adminComponent . getDisplayName ( ) ) ; continue ; } result . add ( adminComponent ) ; } } return result ; } | collects the components from adminTool |
38,586 | public String getMenuName ( HttpServletRequest request , String overrideName ) { if ( ! StringUtils . isEmpty ( overrideName ) ) { return overrideName ; } String name = request . getRequestURI ( ) . replaceFirst ( AdminTool . ROOTCONTEXT , "" ) ; if ( ! StringUtils . isEmpty ( request . getContextPath ( ) ) ) { name = name . replaceFirst ( request . getContextPath ( ) , "" ) ; } if ( name . startsWith ( "/" ) ) { name = name . substring ( 1 , name . length ( ) ) ; } return name ; } | retuns the menu name for given requestUrl or the overrideName if set . |
38,587 | public boolean isActiveInMenuTree ( MenuEntry activeMenu , MenuEntry actualEntry ) { return actualEntry . flattened ( ) . anyMatch ( entry -> checkForNull ( entry , activeMenu ) ? entry . getName ( ) . equals ( activeMenu . getName ( ) ) : false ) ; } | checks if actualEntry contains the activeMenuName in entry itself and its sub entries |
38,588 | public List < MenuEntry > getBreadcrumbList ( MenuEntry actualEntry ) { List < MenuEntry > result = new LinkedList < > ( ) ; if ( null != actualEntry ) { actualEntry . reverseFlattened ( ) . collect ( toListReversed ( ) ) . forEach ( entry -> { if ( null != entry ) result . add ( entry ) ; } ) ; } return result ; } | returns a linked list of reverse resolution o menu structure |
38,589 | public boolean hasMenuEntry ( AdminComponent component , MenuEntry activeMenue ) { if ( null != component && null != component . getMainMenu ( ) ) { Optional < MenuEntry > result = component . getMainMenu ( ) . flattened ( ) . filter ( menu -> checkForNull ( menu , activeMenue ) ? menu . getName ( ) . equals ( activeMenue . getName ( ) ) : false ) . findFirst ( ) ; return result . isPresent ( ) ; } return false ; } | checks if the activeMenue is part of given component |
38,590 | protected String formatFileSize ( BigInteger fileLength , BigInteger divisor , String unit ) { BigDecimal size = new BigDecimal ( fileLength ) ; size = size . setScale ( config . getFileSizeDisplayScale ( ) ) . divide ( new BigDecimal ( divisor ) , BigDecimal . ROUND_HALF_EVEN ) ; return String . format ( "%s %s" , size . doubleValue ( ) , unit ) ; } | calculates the and formats files size |
38,591 | protected boolean isAllowed ( File path , boolean write ) throws IOException { return isAllowedInternal ( path , write , config . isReadOnly ( ) ) ; } | checks if file is allowed for access |
38,592 | public void addExamples ( ExampleStatements exampleStatements ) { this . statements . put ( exampleStatements . getDatasourceName ( ) , exampleStatements . getClusters ( ) ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "converted json object" + new JSONObject ( statements ) ) ; } } | vendor must be set |
38,593 | public Collection < Logger > getParentLoggers ( ) { LoggerContext ctx = ( LoggerContext ) LogManager . getContext ( false ) ; List < Logger > loggers = new ArrayList < > ( ctx . getLoggers ( ) ) ; Map < String , Logger > parentMap = new HashMap < > ( ) ; try { for ( Logger logger : loggers ) { if ( null != logger . getParent ( ) && parentMap . get ( logger . getParent ( ) . getName ( ) ) == null ) { parentMap . put ( logger . getParent ( ) . getName ( ) , logger . getParent ( ) ) ; } } List < Logger > parents = new ArrayList < > ( parentMap . values ( ) ) ; Collections . sort ( parents , LOGGER_COMP ) ; return parents ; } finally { loggers . clear ( ) ; parentMap . clear ( ) ; } } | returns all parent loggers |
38,594 | public Collection < Logger > getLoggers ( ) { LoggerContext ctx = ( LoggerContext ) LogManager . getContext ( false ) ; List < Logger > loggers = new ArrayList < > ( ctx . getLoggers ( ) ) ; Collections . sort ( loggers , LOGGER_COMP ) ; return loggers ; } | returns all loggers |
38,595 | public Collection < String > getAllLoggerNames ( ) { Set < String > loggerNames = new TreeSet < > ( ) ; for ( Logger logger : getParentLoggers ( ) ) { loggerNames . add ( logger . getName ( ) ) ; } for ( Logger logger : getLoggers ( ) ) { loggerNames . add ( logger . getName ( ) ) ; } if ( ! customLoggers . isEmpty ( ) ) { for ( Entry < LoggerConfig , String > entry : customLoggers . entrySet ( ) ) { loggerNames . add ( entry . getKey ( ) . getName ( ) ) ; } } if ( ! customParentLoggers . isEmpty ( ) ) { for ( Entry < LoggerConfig , String > entry : customParentLoggers . entrySet ( ) ) { loggerNames . add ( entry . getKey ( ) . getName ( ) ) ; } } return loggerNames ; } | returns all logger names including custom loggers |
38,596 | public void changeLogger ( final String name , final String levelStr , boolean parent ) throws IllegalArgumentException { Level level = getLevel ( levelStr ) ; changeLogger ( name , level , parent ) ; } | changes the level of an logger |
38,597 | public String createOutputStreamAppender ( String name , String pattern , String encoding , Collection < String > loggerNames , String levelStr , boolean recursive , boolean overrideLogLevel ) { Level level = getLevel ( levelStr ) ; String encodingToUse = StringUtils . isEmpty ( encoding ) ? "UTF-8" : encoding ; PatternLayout layout = PatternLayout . newBuilder ( ) . withPattern ( StringUtils . isEmpty ( pattern ) ? DEFAULT_PATTERN : pattern ) . withCharset ( Charset . forName ( encodingToUse ) ) . build ( ) ; String appenderName = StringUtils . isEmpty ( name ) ? UUID . randomUUID ( ) . toString ( ) : name ; AdminToolLog4j2OutputStream baos = new AdminToolLog4j2OutputStream ( 4096 , encodingToUse ) ; outputStreams . put ( appenderName , baos ) ; OutputStreamAppender appender = OutputStreamAppender . newBuilder ( ) . setName ( appenderName ) . setTarget ( baos ) . setLayout ( layout ) . setFollow ( false ) . build ( ) ; appender . start ( ) ; final LoggerContext ctx = ( LoggerContext ) LogManager . getContext ( false ) ; final Configuration config = ctx . getConfiguration ( ) ; config . addAppender ( appender ) ; Collection < String > parentLoggerNames = getParentLoggerNames ( ) ; Map < String , LoggerConfig > configs = getRecursiveLoggerConfigs ( loggerNames , recursive , config ) ; configs . entrySet ( ) . forEach ( configEntry -> { configEntry . getValue ( ) . addAppender ( appender , level , null ) ; if ( overrideLogLevel ) { baos . addOriginalLevel ( configEntry . getKey ( ) , configEntry . getValue ( ) . getLevel ( ) ) ; changeLogger ( configEntry . getKey ( ) , level , parentLoggerNames . contains ( configEntry . getKey ( ) ) ) ; } } ) ; ctx . updateLoggers ( ) ; return appenderName ; } | creates the custom output steam appender and returns the name |
38,598 | public String getStringOutput ( String appenderName , String encoding ) throws UnsupportedEncodingException { AdminToolLog4j2OutputStream baos = outputStreams . get ( appenderName ) ; String output = "" ; if ( null != baos ) { output = baos . getAndReset ( encoding ) ; } return output . trim ( ) . isEmpty ( ) ? null : output ; } | returns the log messages from custom appenders output stream |
38,599 | public void closeOutputStreamAppender ( String appenderName ) throws IOException { if ( null == appenderName ) { return ; } final LoggerContext ctx = ( LoggerContext ) LogManager . getContext ( false ) ; final Configuration config = ctx . getConfiguration ( ) ; AdminToolLog4j2OutputStream baos = outputStreams . get ( appenderName ) ; if ( null != config && null != config . getAppenders ( ) ) { OutputStreamAppender appender = config . getAppender ( appenderName ) ; if ( null != appender ) { appender . stop ( ) ; Collection < String > parentLoggerNames = getParentLoggerNames ( ) ; for ( String configuredLoggerName : getAllLoggerNames ( ) ) { LoggerConfig loggerConfig = config . getLoggerConfig ( configuredLoggerName ) ; loggerConfig . removeAppender ( appender . getName ( ) ) ; if ( null != baos . getOriginalLevel ( configuredLoggerName ) ) { changeLogger ( configuredLoggerName , baos . getOriginalLevel ( configuredLoggerName ) , parentLoggerNames . contains ( configuredLoggerName ) ) ; } } removeAppender ( appender , getParentLoggers ( ) ) ; removeAppender ( appender , getLoggers ( ) ) ; appender . getManager ( ) . getByteBuffer ( ) . clear ( ) ; ctx . updateLoggers ( ) ; } } if ( null != baos ) { try { baos . close ( ) ; baos . clearOriginalLevels ( ) ; } catch ( Exception ignore ) { } finally { outputStreams . remove ( appenderName ) ; } } } | closes output stream and removes appender from loggers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.