idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
38,900 | private EntityContainer getEntityContainer ( ) throws ODataRenderException { EntityContainer entityContainer = entityDataModel . getEntityContainer ( ) ; if ( entityContainer == null ) { String message = "EntityContainer should not be null" ; LOG . error ( message ) ; throw new ODataRenderException ( message ) ; } return entityContainer ; } | Returns entity container if it exists in entity data model otherwise throws ODataRenderException . |
38,901 | public void ensureCollection ( StructuredType entityType ) throws ODataException { List < String > missingCollectionPropertyName = new ArrayList < > ( ) ; entityType . getStructuralProperties ( ) . stream ( ) . filter ( property -> ( property . isCollection ( ) ) && ! ( property instanceof NavigationProperty ) && ! property . isNullable ( ) ) . forEach ( property -> { LOG . debug ( "Validating non-nullable collection property : {}" , property . getName ( ) ) ; if ( ! fields . containsKey ( property . getName ( ) ) ) { missingCollectionPropertyName . add ( property . getName ( ) ) ; } } ) ; if ( missingCollectionPropertyName . size ( ) != 0 ) { StringJoiner joiner = new StringJoiner ( "," ) ; missingCollectionPropertyName . forEach ( joiner :: add ) ; throw new ODataUnmarshallingException ( "The request does not specify the non-nullable collections: '" + joiner . toString ( ) + "." ) ; } } | Ensure that non nullable collection are present . |
38,902 | public void ensureNavigationProperties ( StructuredType entityType ) throws ODataException { List < String > missingNavigationPropertyNames = new ArrayList < > ( ) ; entityType . getStructuralProperties ( ) . stream ( ) . filter ( property -> ( property instanceof NavigationProperty ) && ! property . isNullable ( ) ) . forEach ( property -> { LOG . debug ( "Validating non-nullable NavigationProperty property : {}" , property . getName ( ) ) ; if ( ! links . containsKey ( property . getName ( ) ) ) { missingNavigationPropertyNames . add ( property . getName ( ) ) ; } } ) ; if ( missingNavigationPropertyNames . size ( ) != 0 ) { StringJoiner joiner = new StringJoiner ( "," ) ; missingNavigationPropertyNames . forEach ( joiner :: add ) ; throw new ODataUnmarshallingException ( "The request does not specify the navigation links for '" + joiner . toString ( ) + "." ) ; } } | Ensure that non nullable navigation properties are present . |
38,903 | public URLConnectionRequestPropertiesBuilder withCookie ( String cookieName , String cookieValue ) { if ( requestProperties . containsKey ( "Cookie" ) ) { final String cookies = requestProperties . get ( "Cookie" ) ; requestProperties . put ( "Cookie" , cookies + COOKIES_SEPARATOR + buildCookie ( cookieName , cookieValue ) ) ; } else { requestProperties . put ( "Cookie" , buildCookie ( cookieName , cookieValue ) ) ; } return this ; } | Add provided cookie to Cookie request property . |
38,904 | public static < T > Class < T > wrap ( Class < T > type ) { if ( type == null ) { throw new IllegalArgumentException ( ) ; } Class < T > wrapped = ( Class < T > ) PRIMITIVE_TO_WRAP . get ( type ) ; return ( wrapped == null ) ? type : wrapped ; } | Guava wrap alternative . |
38,905 | public static < T > Class < T > unwrap ( Class < T > type ) { if ( type == null ) { throw new IllegalArgumentException ( ) ; } Class < T > unwrapped = ( Class < T > ) WRAP_TO_PRIMITIVE . get ( type ) ; return ( unwrapped == null ) ? type : unwrapped ; } | Guava unwrap alternative . |
38,906 | public static EndpointCaller initializeEndpointCaller ( Properties properties ) { EndpointCaller ec ; try { LOG . debug ( "Initializing endpoint caller. Checking whether '{}' is in classpath." , TRACING_ENDPOINT_CALLER_CLASSNAME ) ; Class < ? > tracingEndpointCallerClass = Class . forName ( TRACING_ENDPOINT_CALLER_CLASSNAME ) ; Constructor < ? > tracingEndpointCallerConstructor = tracingEndpointCallerClass . getConstructor ( Properties . class ) ; ec = ( EndpointCaller ) tracingEndpointCallerConstructor . newInstance ( properties ) ; LOG . debug ( "Using '{}' instance as endpoint caller object." , TRACING_ENDPOINT_CALLER_CLASSNAME ) ; } catch ( Exception e ) { ec = new BasicEndpointCaller ( properties ) ; LOG . debug ( "Using '{}' instance as endpoint caller object." , BasicEndpointCaller . class . getName ( ) ) ; } return ec ; } | If the TracingEndpointCaller class is in a classpath - use it otherwise use BasicEndpointCaller . |
38,907 | public void addFunctionImport ( Class < ? > cls ) { EdmFunctionImport functionImportAnnotation = cls . getAnnotation ( EdmFunctionImport . class ) ; FunctionImportImpl . Builder functionImportBuilder = new FunctionImportImpl . Builder ( ) . setEntitySetName ( functionImportAnnotation . entitySet ( ) ) . setFunctionName ( functionImportAnnotation . namespace ( ) + "." + functionImportAnnotation . function ( ) ) . setIncludeInServiceDocument ( functionImportAnnotation . includeInServiceDocument ( ) ) . setName ( functionImportAnnotation . name ( ) ) . setJavaClass ( cls ) ; functionImportBuilders . add ( functionImportBuilder ) ; } | Add function import to builder of this factory by specified class . |
38,908 | public Iterable < FunctionImport > build ( FactoryLookup lookup ) { List < FunctionImport > builder = new ArrayList < > ( ) ; for ( FunctionImportImpl . Builder functionImportBuilder : functionImportBuilders ) { EntitySet entitySet = lookup . getEntitySet ( functionImportBuilder . getEntitySetName ( ) ) ; Function function = lookup . getFunction ( functionImportBuilder . getFunctionName ( ) ) ; if ( entitySet == null && function . isBound ( ) ) { throw new IllegalArgumentException ( "Could not find EntitySet with name: " + functionImportBuilder . getEntitySetName ( ) ) ; } functionImportBuilder . setEntitySet ( entitySet ) ; functionImportBuilder . setFunction ( function ) ; builder . add ( functionImportBuilder . build ( ) ) ; } return Collections . unmodifiableList ( builder ) ; } | Returns built function imports using passed lookup for searching entity sets and functions for appropriate function import . |
38,909 | public static String getFullyQualifiedFunctionImportName ( EdmFunctionImport functionImportAnnotation , Class < ? > functionImportClass ) { String name = getTypeName ( functionImportAnnotation , functionImportClass ) ; String namespace = getNamespace ( functionImportAnnotation , functionImportClass ) ; return namespace + "." + name ; } | Returns fully qualified function import name by function import annotation and class . |
38,910 | protected void validateProperties ( final Object entity , final EntityDataModel edm ) throws ODataException { final Type type = edm . getType ( entity . getClass ( ) ) ; if ( ! ( type instanceof StructuredType ) ) { return ; } visitProperties ( edm , ( StructuredType ) type , property -> { Object value = getPropertyValue ( property , entity ) ; if ( value == null ) { if ( ! property . isNullable ( ) ) { throw new ODataBadRequestException ( "The property '" + property . getName ( ) + "' is required to be non-empty in an entity of type: " + type . getFullyQualifiedName ( ) ) ; } } else if ( ! ( property instanceof NavigationProperty ) ) { validateProperties ( value , edm ) ; } } ) ; } | Checks if all non - nullable properties of an entity are non - empty . |
38,911 | public String buildJson ( ) throws ODataRenderException { LOG . debug ( "Start building Json service root document" ) ; try ( ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ) { JsonGenerator jsonGenerator = JSON_FACTORY . createGenerator ( stream , JsonEncoding . UTF8 ) ; jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeStringField ( CONTEXT , getContextURL ( uri , entityDataModel ) ) ; jsonGenerator . writeArrayFieldStart ( VALUE ) ; List < EntitySet > entities = entityDataModel . getEntityContainer ( ) . getEntitySets ( ) ; for ( EntitySet entity : entities ) { if ( entity . isIncludedInServiceDocument ( ) ) { writeObject ( jsonGenerator , entity ) ; } } List < Singleton > singletons = entityDataModel . getEntityContainer ( ) . getSingletons ( ) ; for ( Singleton singleton : singletons ) { writeObject ( jsonGenerator , singleton ) ; } jsonGenerator . writeEndArray ( ) ; jsonGenerator . writeEndObject ( ) ; jsonGenerator . close ( ) ; return stream . toString ( StandardCharsets . UTF_8 . name ( ) ) ; } catch ( IOException e ) { throw new ODataRenderException ( "It is unable to render service document" , e ) ; } } | The main method for Writer . It builds the service root document according to spec . |
38,912 | private void writeName ( JsonGenerator jsonGenerator , Object entity ) throws IOException { jsonGenerator . writeFieldName ( NAME ) ; if ( entity instanceof EntitySet ) { jsonGenerator . writeObject ( ( ( EntitySet ) entity ) . getName ( ) ) ; } else { jsonGenerator . writeObject ( ( ( Singleton ) entity ) . getName ( ) ) ; } } | Writes the name of the entity It is a MUST element . |
38,913 | private void writeKind ( JsonGenerator jsonGenerator , Object entity ) throws IOException { jsonGenerator . writeFieldName ( KIND ) ; if ( entity instanceof EntitySet ) { jsonGenerator . writeObject ( ENTITY_SET ) ; } else { jsonGenerator . writeObject ( SINGLETON ) ; } } | Writes the kind of the entity . |
38,914 | private void writeURL ( JsonGenerator jsonGenerator , Object entity ) throws IOException { jsonGenerator . writeFieldName ( URL ) ; if ( entity instanceof EntitySet ) { jsonGenerator . writeObject ( ( ( EntitySet ) entity ) . getName ( ) ) ; } else { jsonGenerator . writeObject ( ( ( Singleton ) entity ) . getName ( ) ) ; } } | Writes the url of the entity It is a MUST element . |
38,915 | public static String buildContextUrlFromOperationCall ( ODataUri oDataUri , EntityDataModel entityDataModel , boolean isPrimitive ) { String serviceRoot = oDataUri . serviceRoot ( ) ; String returnType = ODataUriUtil . getOperationReturnType ( oDataUri , entityDataModel ) ; return serviceRoot + "/" + METADATA + "#" + returnType + ( isPrimitive ? "" : "/$entity" ) ; } | Builds the Context URL when the request is an action or function call . |
38,916 | public static < T > T checkNotNull ( T reference , String message , Object ... args ) { if ( reference == null ) { throw new IllegalArgumentException ( String . format ( message , args ) ) ; } return reference ; } | Check if the reference is not null . This differs from Guava that throws Illegal Argument Exception + message . |
38,917 | public static boolean isForceExpandParamSet ( ODataUri oDataUri ) { if ( isFunctionCallUri ( oDataUri ) ) { Option < scala . collection . immutable . Map < String , String > > params = getFunctionCallParameters ( oDataUri ) ; if ( params . isDefined ( ) && ! params . get ( ) . isEmpty ( ) ) { Map < String , String > parametersMap = JavaConverters . mapAsJavaMap ( params . get ( ) ) ; if ( parametersMap . containsKey ( FORCE_EXPAND_PARAM ) ) { return Boolean . parseBoolean ( parametersMap . get ( FORCE_EXPAND_PARAM ) ) ; } } } return false ; } | Checks if we are trying to force expand all Nav properties for function calls by looking at expand parameter . |
38,918 | public static < T extends Annotation > T checkAnnotationPresent ( AnnotatedElement annotatedType , Class < T > annotationClass ) { return getAnnotation ( annotatedType , annotationClass ) ; } | Check if the annotation is present and if not throws an exception this is just an overload for more clear naming . |
38,919 | public int score ( ODataRequestContext requestContext , QueryResult data ) { if ( data . getType ( ) == QueryResult . ResultType . NOTHING || data . getType ( ) != QueryResult . ResultType . EXCEPTION ) { return DEFAULT_SCORE ; } if ( data . getData ( ) instanceof ODataBatchException ) { return MAXIMUM_FORMAT_SCORE ; } List < MediaType > accept = requestContext . getRequest ( ) . getAccept ( ) ; int batchAcceptScore = scoreByMediaType ( accept , MediaType . MULTIPART ) ; int contentTypeScore = scoreByContentType ( requestContext , MULTIPART ) ; int resultScore = max ( batchAcceptScore , contentTypeScore ) ; return resultScore > 0 ? ( resultScore + ERROR_EXTRA_SCORE ) : DEFAULT_SCORE ; } | Batch score mechanism exists not only for simple rendering but also for computing batch error scores . |
38,920 | public List < ProcessorResult > handleWrite ( ) throws ODataException { LOG . info ( "Handling transactional operations per each odata request." ) ; List < ProcessorResult > resultList = new ArrayList < > ( ) ; try { for ( ChangeSetEntity changeSetEntity : changeSetEntities ) { ODataRequestContext odataRequestContext = changeSetEntity . getRequestContext ( ) ; ODataUri requestUri = odataRequestContext . getUri ( ) ; ODataRequest . Method method = odataRequestContext . getRequest ( ) . getMethod ( ) ; ProcessorResult result = null ; if ( method == ODataRequest . Method . POST ) { result = handlePOST ( odataRequestContext , requestUri , changeSetEntity ) ; } else if ( method == ODataRequest . Method . PUT || method == ODataRequest . Method . PATCH ) { result = handlePutAndPatch ( odataRequestContext , requestUri , changeSetEntity ) ; } else if ( method == ODataRequest . Method . DELETE ) { result = handleDelete ( odataRequestContext , requestUri , changeSetEntity ) ; } resultList . add ( result ) ; } commitTransactions ( ) ; } catch ( ODataException e ) { LOG . error ( "Transaction could not be processed, rolling back" , e ) ; rollbackTransactions ( ) ; throw e ; } return resultList ; } | Handles transactional operations for each parsed odata request . |
38,921 | private Type getRequestType ( ODataRequest oDataRequest , ODataUri oDataUri ) throws ODataTargetTypeException { TargetType targetType = WriteMethodUtil . getTargetType ( oDataRequest , entityDataModel , oDataUri ) ; return entityDataModel . getType ( targetType . typeName ( ) ) ; } | Returns request type for the given odata uri . |
38,922 | private TransactionalDataSource getTransactionalDataSource ( ODataRequestContext odataRequestContext , Type type ) throws ODataException { DataSource dataSource = dataSourceFactory . getDataSource ( odataRequestContext , type . getFullyQualifiedName ( ) ) ; String dataSourceKey = dataSource . getClass ( ) . toString ( ) ; if ( dataSourceMap . containsKey ( dataSourceKey ) ) { return dataSourceMap . get ( dataSourceKey ) ; } else { TransactionalDataSource transactionalDataSource = dataSource . startTransaction ( ) ; dataSourceMap . put ( dataSourceKey , transactionalDataSource ) ; return transactionalDataSource ; } } | If it s the first batch request call - start transaction . |
38,923 | public static Integer getIntegerProperty ( Properties properties , String key ) { String property = getStringProperty ( properties , key ) ; if ( property == null ) { return null ; } Integer value ; try { value = Integer . parseInt ( property ) ; } catch ( RuntimeException e ) { throw new ODataClientRuntimeException ( "Unable to parse property. " + property , e ) ; } return value ; } | Get an integer property from the properties . |
38,924 | public static String getStringProperty ( Properties properties , String key ) { String property = properties . getProperty ( key ) ; return property != null && property . trim ( ) . isEmpty ( ) ? null : property ; } | Get a string property from the properties . |
38,925 | public static Long getLongProperty ( String property ) { if ( property == null ) { return null ; } Long propertyLong = null ; try { propertyLong = Long . valueOf ( property ) ; } catch ( NumberFormatException e ) { LOG . warn ( "Cannot convert string value into number" , e ) ; } return propertyLong ; } | Get a long property from properties . |
38,926 | public static XMLStreamWriter startDocument ( ByteArrayOutputStream outputStream , String prefix , String documentRootName , String nameSpaceURI ) throws XMLStreamException { XMLStreamWriter writer = XML_OUTPUT_FACTORY . createXMLStreamWriter ( outputStream , UTF_8 . name ( ) ) ; if ( isNullOrEmpty ( prefix ) ) { writer . writeStartElement ( documentRootName ) ; writer . setDefaultNamespace ( nameSpaceURI ) ; writer . writeDefaultNamespace ( nameSpaceURI ) ; } else { writer . writeStartElement ( prefix , documentRootName , nameSpaceURI ) ; writer . writeNamespace ( prefix , nameSpaceURI ) ; } return writer ; } | Creates document root with given name . |
38,927 | public static void writePrimitiveValue ( Object primitiveValue , JsonGenerator jsonGenerator ) throws IOException { Class < ? > primitiveClass = PrimitiveUtil . wrap ( primitiveValue . getClass ( ) ) ; if ( String . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeString ( String . valueOf ( primitiveValue ) ) ; } else if ( Byte . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeObject ( primitiveValue ) ; } else if ( Short . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeNumber ( ( short ) primitiveValue ) ; } else if ( Integer . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeNumber ( ( int ) primitiveValue ) ; } else if ( Float . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeNumber ( ( float ) primitiveValue ) ; } else if ( Double . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeNumber ( ( double ) primitiveValue ) ; } else if ( Long . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeNumber ( ( long ) primitiveValue ) ; } else if ( Boolean . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeBoolean ( ( boolean ) primitiveValue ) ; } else if ( UUID . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeString ( primitiveValue . toString ( ) ) ; } else if ( BigDecimal . class . isAssignableFrom ( primitiveClass ) ) { jsonGenerator . writeNumber ( ( BigDecimal ) primitiveValue ) ; } else { jsonGenerator . writeObject ( primitiveValue . toString ( ) ) ; } } | Write the given primitive value to the JSON stream by using the given JSON generator . |
38,928 | public Function build ( Class < ? > cls ) { EdmFunction edmFunction = cls . getAnnotation ( EdmFunction . class ) ; EdmReturnType edmReturnType = cls . getAnnotation ( EdmReturnType . class ) ; if ( edmReturnType == null ) { throw new IllegalArgumentException ( "The class must have EdmReturnType: " + cls . getName ( ) ) ; } Set < Parameter > parameters = new HashSet < > ( ) ; for ( Field field : cls . getDeclaredFields ( ) ) { EdmParameter parameterAnnotation = field . getAnnotation ( EdmParameter . class ) ; if ( parameterAnnotation != null ) { String parameterName = isNullOrEmpty ( parameterAnnotation . name ( ) ) ? field . getName ( ) : parameterAnnotation . name ( ) ; String parameterType = isNullOrEmpty ( parameterAnnotation . type ( ) ) ? field . getType ( ) . getSimpleName ( ) : parameterAnnotation . type ( ) ; parameters . add ( new ParameterImpl . Builder ( ) . setMaxLength ( parameterAnnotation . maxLength ( ) ) . setName ( parameterName ) . setNullable ( parameterAnnotation . nullable ( ) ) . setPrecision ( parameterAnnotation . precision ( ) ) . setScale ( parameterAnnotation . scale ( ) ) . setSRID ( parameterAnnotation . srid ( ) ) . setType ( parameterType ) . setUnicode ( parameterAnnotation . unicode ( ) ) . setJavaField ( field ) . build ( ) ) ; } } return new FunctionImpl . Builder ( ) . setBound ( edmFunction . isBound ( ) ) . setComposable ( edmFunction . isComposable ( ) ) . setEntitySetPath ( edmFunction . entitySetPath ( ) ) . setName ( edmFunction . name ( ) ) . setParameters ( parameters ) . setReturnType ( edmReturnType . type ( ) ) . setNamespace ( edmFunction . namespace ( ) ) . setJavaClass ( cls ) . build ( ) ; } | Method to build Function implementation with parameters by class . |
38,929 | public static String getFullyQualifiedFunctionName ( EdmFunction functionAnnotation , Class < ? > functionClass ) { String name = getTypeName ( functionAnnotation , functionClass ) ; String namespace = getNamespace ( functionAnnotation , functionClass ) ; return namespace + "." + name ; } | Returned fully qualified function name using function annotation and class . |
38,930 | protected boolean isRightMethodForUnmarshall ( ODataRequest request ) { ODataRequest . Method method = request . getMethod ( ) ; return isPostMethod ( method ) || isPatchMethod ( method ) || isPutMethod ( method ) ; } | This method checks request method is PUT or POST or PATCH . |
38,931 | protected int score ( MediaType contentTypeFromRequest , MediaType ... expectedTypes ) { if ( contentTypeFromRequest == null ) { return DEFAULT_SCORE ; } for ( MediaType expected : expectedTypes ) { if ( contentTypeFromRequest . matches ( expected ) ) { return MAXIMUM_FORMAT_SCORE ; } } return DEFAULT_SCORE ; } | Calculates score based on given media type . |
38,932 | public Result index ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "access granted to index" ) ; } DemoUser user = ( DemoUser ) ctx ( ) . args . get ( SecureSocial . USER_KEY ) ; return ok ( index . render ( user , SecureSocial . env ( ) ) ) ; } | This action only gets called if the user is logged in . |
38,933 | public Future < Option < BasicProfile > > find ( String providerId , String userId ) { return toScala ( doFind ( providerId , userId ) . thenApply ( Scala :: Option ) ) ; } | Finds an Identity that maches the specified id |
38,934 | public Future < Option < BasicProfile > > findByEmailAndProvider ( String email , String providerId ) { return toScala ( doFindByEmailAndProvider ( email , providerId ) . thenApply ( Scala :: Option ) ) ; } | Finds an Identity by email and provider id . |
38,935 | public Future < U > save ( BasicProfile user , SaveMode mode ) { return toScala ( doSave ( user , mode ) ) ; } | Saves the Identity . This method gets called when a user logs in . This is your chance to save the user information in your backing store . |
38,936 | public Future < U > link ( U current , BasicProfile to ) { return toScala ( doLink ( current , to ) ) ; } | Links the current user Identity to another |
38,937 | public Future < MailToken > saveToken ( MailToken mailToken ) { return toScala ( doSaveToken ( Token . fromScala ( mailToken ) ) . thenApply ( Token :: toScala ) ) ; } | Saves a token . This is needed for users that are creating an account in the system instead of using one in a 3rd party system . |
38,938 | public Future < Option < MailToken > > findToken ( String tokenId ) { return toScala ( doFindToken ( tokenId ) . thenApply ( this :: toMailToken ) ) ; } | Finds a token |
38,939 | public Future < scala . Option < MailToken > > deleteToken ( String tokenId ) { return toScala ( doDeleteToken ( tokenId ) . thenApply ( this :: toMailToken ) ) ; } | Deletes a token |
38,940 | protected Tuple2 < String , Seq < Object > > toScalaTuple ( String message , List < Object > params ) { return new Tuple2 < String , Seq < Object > > ( message , JavaConverters . collectionAsScalaIterableConverter ( params ) . asScala ( ) . toSeq ( ) ) ; } | A helper method to create the tuple expected by PasswordValidator from a Java String and List objects . |
38,941 | private void validate ( ) { if ( isValid != null ) { return ; } ParsingValidator v = new ParsingValidator ( useSchema ? Languages . W3C_XML_SCHEMA_NS_URI : Languages . XML_DTD_NS_URI ) ; List < Source > schemaSourceList = new ArrayList < Source > ( ) ; if ( systemId != null ) { schemaSourceList . add ( new StreamSource ( systemId ) ) ; } addSchemaSources ( schemaSource , schemaSourceList ) ; v . setSchemaSources ( schemaSourceList . toArray ( new Source [ 0 ] ) ) ; try { ValidationResult r = v . validateInstance ( new SAXSource ( validationInputSource ) ) ; isValid = r . isValid ( ) ? Boolean . TRUE : Boolean . FALSE ; for ( ValidationProblem p : r . getProblems ( ) ) { validationProblem ( p ) ; } } catch ( org . xmlunit . ConfigurationException e ) { throw new ConfigurationException ( e . getCause ( ) ) ; } catch ( org . xmlunit . XMLUnitException e ) { throw new XMLUnitRuntimeException ( e . getMessage ( ) , e . getCause ( ) ) ; } if ( usingDoctypeReader && isValid == Boolean . FALSE ) { try { messages . append ( "\nContent was: " ) . append ( getOriginalContent ( validationInputSource ) ) ; } catch ( IOException e ) { } } } | Actually perform validation . |
38,942 | private void invalidate ( String message ) { isValid = Boolean . FALSE ; messages . append ( message ) . append ( ' ' ) ; } | Set the validation status flag to false and capture the message for use later . |
38,943 | private StringBuilder getXSLTBase ( ) { StringBuilder result = new StringBuilder ( XML_DECLARATION ) . append ( XMLUnit . getXSLTStart ( ) ) ; String tmp = result . toString ( ) ; int close = tmp . lastIndexOf ( '>' ) ; if ( close == - 1 ) { close = tmp . length ( ) ; } result . insert ( close , getNamespaceDeclarations ( ) ) ; return result ; } | What every XSL transform needs |
38,944 | private void performTransform ( String xslt , Document document , Result result ) throws TransformerException , ConfigurationException , XpathException { try { StreamSource source = new StreamSource ( new StringReader ( xslt ) ) ; TransformerFactory tf = XMLUnit . newTransformerFactory ( ) ; ErrorListener el = new ErrorListener ( ) { public void error ( TransformerException ex ) throws TransformerException { throw ex ; } public void fatalError ( TransformerException ex ) throws TransformerException { throw ex ; } public void warning ( TransformerException ex ) { ex . printStackTrace ( ) ; } } ; tf . setErrorListener ( el ) ; Transformer transformer = tf . newTransformer ( source ) ; if ( transformer == null ) { throw new XpathException ( "failed to obtain an XSLT transformer" + " for XPath expression." ) ; } transformer . setErrorListener ( el ) ; transformer . transform ( new DOMSource ( document ) , result ) ; } catch ( javax . xml . transform . TransformerConfigurationException ex ) { throw new ConfigurationException ( ex ) ; } } | Perform the actual transformation work required |
38,945 | protected Node getXPathResultNode ( String select , Document document ) throws ConfigurationException , TransformerException , XpathException { return getXPathResultAsDocument ( select , document ) . getDocumentElement ( ) ; } | Testable method to execute the copy - of transform and return the root node of the resulting Document . |
38,946 | protected Document getXPathResultAsDocument ( String select , Document document ) throws ConfigurationException , TransformerException , XpathException { DOMResult result = new DOMResult ( ) ; performTransform ( getCopyTransformation ( select ) , document , result ) ; return ( Document ) result . getNode ( ) ; } | Execute the copy - of transform and return the resulting Document . Used for XMLTestCase comparison |
38,947 | private String getNamespaceDeclarations ( ) { StringBuilder nsDecls = new StringBuilder ( ) ; String quoteStyle = "'" ; for ( Iterator keys = ctx . getPrefixes ( ) ; keys . hasNext ( ) ; ) { String prefix = ( String ) keys . next ( ) ; String uri = ctx . getNamespaceURI ( prefix ) ; if ( uri == null ) { continue ; } if ( prefix == null ) { prefix = "" ; } if ( uri . indexOf ( '\'' ) != - 1 ) { quoteStyle = "\"" ; } nsDecls . append ( ' ' ) . append ( XMLNS_PREFIX ) ; if ( prefix . length ( ) > 0 ) { nsDecls . append ( ':' ) ; } nsDecls . append ( prefix ) . append ( '=' ) . append ( quoteStyle ) . append ( uri ) . append ( quoteStyle ) . append ( ' ' ) ; } return nsDecls . toString ( ) ; } | returns namespace declarations for all namespaces known to the current context . |
38,948 | protected boolean similar ( Text control , Text test ) { if ( control == null ) { return test == null ; } else if ( test == null ) { return false ; } return control . getNodeValue ( ) . equals ( test . getNodeValue ( ) ) ; } | Determine whether the text nodes contain similar values |
38,949 | protected Text extractText ( Element fromElement ) { fromElement . normalize ( ) ; NodeList fromNodeList = fromElement . getChildNodes ( ) ; Node currentNode ; for ( int i = 0 ; i < fromNodeList . getLength ( ) ; ++ i ) { currentNode = fromNodeList . item ( i ) ; if ( currentNode . getNodeType ( ) == Node . TEXT_NODE ) { return ( Text ) currentNode ; } } return null ; } | Extract the normalized text from within an element |
38,950 | public static DifferenceEvaluator first ( final DifferenceEvaluator ... evaluators ) { return new DifferenceEvaluator ( ) { public ComparisonResult evaluate ( Comparison comparison , ComparisonResult orig ) { for ( DifferenceEvaluator ev : evaluators ) { ComparisonResult evaluated = ev . evaluate ( comparison , orig ) ; if ( evaluated != orig ) { return evaluated ; } } return orig ; } } ; } | Combines multiple DifferenceEvaluators so that the first one that changes the outcome wins . |
38,951 | public static DifferenceEvaluator chain ( final DifferenceEvaluator ... evaluators ) { return new DifferenceEvaluator ( ) { public ComparisonResult evaluate ( Comparison comparison , ComparisonResult orig ) { ComparisonResult finalResult = orig ; for ( DifferenceEvaluator ev : evaluators ) { ComparisonResult evaluated = ev . evaluate ( comparison , finalResult ) ; finalResult = evaluated ; } return finalResult ; } } ; } | Combines multiple DifferenceEvaluators so that the result of the first Evaluator will be passed to the next Evaluator . |
38,952 | public static String getMergedNestedText ( Node n ) { StringBuilder sb = new StringBuilder ( ) ; for ( Node child : new IterableNodeList ( n . getChildNodes ( ) ) ) { if ( child instanceof Text || child instanceof CDATASection ) { String s = child . getNodeValue ( ) ; if ( s != null ) { sb . append ( s ) ; } } } return sb . toString ( ) ; } | Tries to merge all direct Text and CDATA children of the given Node and concatenates their value . |
38,953 | public static Map < QName , String > getAttributes ( Node n ) { Map < QName , String > map = new LinkedHashMap < QName , String > ( ) ; NamedNodeMap m = n . getAttributes ( ) ; if ( m != null ) { final int len = m . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { Attr a = ( Attr ) m . item ( i ) ; map . put ( getQName ( a ) , a . getValue ( ) ) ; } } return map ; } | Obtains an element s attributes as Map . |
38,954 | private static void handleWsRec ( Node n , boolean normalize ) { if ( n instanceof CharacterData || n instanceof ProcessingInstruction ) { String s = n . getNodeValue ( ) . trim ( ) ; if ( normalize ) { s = normalize ( s ) ; } n . setNodeValue ( s ) ; } List < Node > toRemove = new LinkedList < Node > ( ) ; for ( Node child : new IterableNodeList ( n . getChildNodes ( ) ) ) { handleWsRec ( child , normalize ) ; if ( ! ( n instanceof Attr ) && ( child instanceof Text || child instanceof CDATASection ) && child . getNodeValue ( ) . length ( ) == 0 ) { toRemove . add ( child ) ; } } for ( Node child : toRemove ) { n . removeChild ( child ) ; } NamedNodeMap attrs = n . getAttributes ( ) ; if ( attrs != null ) { final int len = attrs . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { handleWsRec ( attrs . item ( i ) , normalize ) ; } } } | Trims textual content of this node removes empty text and CDATA children recurses into its child nodes . |
38,955 | static String normalize ( String s ) { StringBuilder sb = new StringBuilder ( ) ; boolean changed = false ; boolean lastCharWasWS = false ; final int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = s . charAt ( i ) ; if ( Character . isWhitespace ( c ) ) { if ( ! lastCharWasWS ) { sb . append ( SPACE ) ; changed |= c != SPACE ; } else { changed = true ; } lastCharWasWS = true ; } else { sb . append ( c ) ; lastCharWasWS = false ; } } return changed ? sb . toString ( ) : s ; } | Normalize a string . |
38,956 | public static void assertXMLEqual ( String msg , Diff diff , boolean assertion ) { if ( assertion != diff . similar ( ) ) { fail ( getFailMessage ( msg , diff ) ) ; } } | Assert that the result of an XML comparison is or is not similar . |
38,957 | public static void assertXMLIdentical ( String msg , Diff diff , boolean assertion ) { if ( assertion != diff . identical ( ) ) { fail ( getFailMessage ( msg , diff ) ) ; } } | Assert that the result of an XML comparison is or is not identical |
38,958 | public static void assertXpathsEqual ( String controlXpath , String testXpath , Document document ) throws XpathException { assertXpathsEqual ( controlXpath , document , testXpath , document ) ; } | Assert that the node lists of two Xpaths in the same document are equal |
38,959 | public static void assertXpathsEqual ( String controlXpath , Document controlDocument , String testXpath , Document testDocument ) throws XpathException { assertXpathEquality ( controlXpath , controlDocument , testXpath , testDocument , true ) ; } | Assert that the node lists of two Xpaths in two documents are equal |
38,960 | public static void assertXpathsNotEqual ( String controlXpath , String testXpath , Document document ) throws XpathException { assertXpathsNotEqual ( controlXpath , document , testXpath , document ) ; } | Assert that the node lists of two Xpaths in the same document are NOT equal |
38,961 | public static void assertXpathsNotEqual ( String controlXpath , InputSource controlDocument , String testXpath , InputSource testDocument ) throws SAXException , IOException , XpathException { assertXpathsNotEqual ( controlXpath , XMLUnit . buildControlDocument ( controlDocument ) , testXpath , XMLUnit . buildTestDocument ( testDocument ) ) ; } | Assert that the node lists of two Xpaths in two XML strings are NOT equal |
38,962 | public static void assertXpathsNotEqual ( String controlXpath , Document controlDocument , String testXpath , Document testDocument ) throws XpathException { assertXpathEquality ( controlXpath , controlDocument , testXpath , testDocument , false ) ; } | Assert that the node lists of two Xpaths in two documents are NOT equal |
38,963 | private static void assertXpathEquality ( String controlXpath , Document controlDocument , String testXpath , Document testDocument , boolean equal ) throws XpathException { XpathEngine xpath = XMLUnit . newXpathEngine ( ) ; Diff diff = new Diff ( asXpathResultDocument ( XMLUnit . newControlParser ( ) , xpath . getMatchingNodes ( controlXpath , controlDocument ) ) , asXpathResultDocument ( XMLUnit . newTestParser ( ) , xpath . getMatchingNodes ( testXpath , testDocument ) ) ) ; assertXMLEqual ( diff , equal ) ; } | Assert that the node lists of two Xpaths in two documents are equal or not . |
38,964 | public static void assertXpathValuesEqual ( String controlXpath , String testXpath , Document document ) throws XpathException { assertXpathValuesEqual ( controlXpath , document , testXpath , document ) ; } | Assert that the evaluation of two Xpaths in the same document are equal |
38,965 | public static void assertXpathValuesEqual ( String controlXpath , Document controlDocument , String testXpath , Document testDocument ) throws XpathException { XpathEngine xpath = XMLUnit . newXpathEngine ( ) ; assertEquals ( xpath . evaluate ( controlXpath , controlDocument ) , xpath . evaluate ( testXpath , testDocument ) ) ; } | Assert that the evaluation of two Xpaths in two documents are equal |
38,966 | public static void assertXpathValuesNotEqual ( String controlXpath , String testXpath , Document document ) throws XpathException { assertXpathValuesNotEqual ( controlXpath , document , testXpath , document ) ; } | Assert that the evaluation of two Xpaths in the same document are NOT equal |
38,967 | public static void assertXpathValuesNotEqual ( String controlXpath , Document controlDocument , String testXpath , Document testDocument ) throws XpathException { XpathEngine xpath = XMLUnit . newXpathEngine ( ) ; String control = xpath . evaluate ( controlXpath , controlDocument ) ; String test = xpath . evaluate ( testXpath , testDocument ) ; if ( control != null ) { if ( control . equals ( test ) ) { fail ( "Expected test value NOT to be equal to control but both were " + test ) ; } } else if ( test == null ) { fail ( "Expected test value NOT to be equal to control but both were empty" ) ; } } | Assert that the evaluation of two Xpaths in two documents are NOT equal |
38,968 | public static void assertXpathEvaluatesTo ( String expectedValue , String xpathExpression , InputSource control ) throws SAXException , IOException , XpathException { Document document = XMLUnit . buildControlDocument ( control ) ; assertXpathEvaluatesTo ( expectedValue , xpathExpression , document ) ; } | Assert the value of an Xpath expression in an XML document . |
38,969 | public static void assertXpathNotExists ( String xPathExpression , Document inDocument ) throws XpathException { XpathEngine simpleXpathEngine = XMLUnit . newXpathEngine ( ) ; NodeList nodeList = simpleXpathEngine . getMatchingNodes ( xPathExpression , inDocument ) ; int matches = nodeList . getLength ( ) ; assertEquals ( "Should be zero matches for Xpath " + xPathExpression , 0 , matches ) ; } | Assert that a specific XPath does NOT exist in some given XML |
38,970 | private void provideSystemIdIfRequired ( Source source ) { if ( source != null && ( source . getSystemId ( ) == null || source . getSystemId ( ) . length ( ) == 0 ) ) { source . setSystemId ( getDefaultSystemId ( ) ) ; } } | Ensure that the source has a systemId |
38,971 | protected void transformTo ( final Result result ) throws TransformerException { withExceptionHandling ( new Trans < Object > ( ) { public Object transform ( ) { transformation . transformTo ( result ) ; return null ; } } ) ; } | Perform the actual transformation |
38,972 | public void setOutputProperties ( Properties outputProperties ) { for ( Enumeration e = outputProperties . propertyNames ( ) ; e . hasMoreElements ( ) ; ) { Object key = e . nextElement ( ) ; if ( key != null ) { String name = key . toString ( ) ; String value = outputProperties . getProperty ( name ) ; if ( value != null ) { setOutputProperty ( name , value ) ; } } } } | Override output properties specified in the transformation stylesheet |
38,973 | public void setParameter ( String name , Object value ) { parameters . put ( name , value ) ; transformation . addParameter ( name , value ) ; } | Add a parameter for the transformation |
38,974 | private void ensureContentAvailable ( ) throws IOException { if ( nodeContentBytes . size ( ) > 0 ) { return ; } try { Transform serializeTransform = new Transform ( rootNode ) ; if ( outputProperties != null ) { serializeTransform . setOutputProperties ( outputProperties ) ; } StreamResult byteResult = new StreamResult ( nodeContentBytes ) ; serializeTransform . transformTo ( byteResult ) ; } catch ( Exception e ) { throw new IOException ( "Unable to serialize document to outputstream: " + e . toString ( ) ) ; } } | Do the actual work of serializing the node to bytes |
38,975 | public int read ( char [ ] cbuf , int off , int len ) throws IOException { int startPos = off ; int currentlyRead ; while ( off - startPos < len && ( currentlyRead = read ( ) ) != - 1 ) { cbuf [ off ++ ] = ( char ) currentlyRead ; } return off == startPos && len != 0 ? - 1 : off - startPos ; } | Read DOCTYPE - replaced content from the wrapped Reader |
38,976 | public void setNamespaceContext ( Map < String , String > prefix2uri ) { this . prefix2uri = prefix2uri == null ? Collections . < String , String > emptyMap ( ) : Collections . unmodifiableMap ( prefix2uri ) ; } | Establish a namespace context that will be used in for the XPath . |
38,977 | private void appendDifference ( StringBuilder appendTo , Difference difference ) { appendTo . append ( ' ' ) . append ( difference ) . append ( '\n' ) ; } | Append a meaningful message to the buffer of messages |
38,978 | public StringBuffer appendMessage ( StringBuffer toAppendTo ) { compare ( ) ; if ( messages . length ( ) == 0 ) { messages . append ( "[identical]" ) ; } return toAppendTo . append ( messages . toString ( ) ) ; } | Append the message from the result of this Diff instance to a specified StringBuffer |
38,979 | private DifferenceEngineContract getDifferenceEngine ( ) { if ( differenceEngine == null ) { if ( XMLUnit . getIgnoreAttributeOrder ( ) && ( ! usesUnknownElementQualifier ( ) || XMLUnit . getCompareUnmatched ( ) ) ) { return new NewDifferenceEngine ( this , matchTrackerDelegate ) ; } return new DifferenceEngine ( this , matchTrackerDelegate ) ; } return differenceEngine ; } | Lazily initializes the difference engine if it hasn t been set via a constructor . |
38,980 | public SingleNodeAssert hasAttribute ( String attributeName ) { isNotNull ( ) ; final Map . Entry < QName , String > entry = attributeForName ( attributeName ) ; if ( entry == null ) { throwAssertionError ( shouldHaveAttribute ( actual . getNodeName ( ) , attributeName ) ) ; } return this ; } | Verifies that node has attribute with given name . |
38,981 | public SingleNodeAssert hasAttribute ( String attributeName , String attributeValue ) { isNotNull ( ) ; final Map . Entry < QName , String > attribute = attributeForName ( attributeName ) ; if ( attribute == null || ! attribute . getValue ( ) . equals ( attributeValue ) ) { throwAssertionError ( shouldHaveAttributeWithValue ( actual . getNodeName ( ) , attributeName , attributeValue ) ) ; } return this ; } | Verifies that node has attribute with given name and value . |
38,982 | public SingleNodeAssert doesNotHaveAttribute ( String attributeName ) { isNotNull ( ) ; final Map . Entry < QName , String > entry = attributeForName ( attributeName ) ; if ( entry != null ) { throwAssertionError ( shouldNotHaveAttribute ( actual . getNodeName ( ) , attributeName ) ) ; } return this ; } | Verifies that node has not attribute with given name . |
38,983 | protected final ComparisonState compare ( Comparison comp ) { Object controlValue = comp . getControlDetails ( ) . getValue ( ) ; Object testValue = comp . getTestDetails ( ) . getValue ( ) ; boolean equal = controlValue == null ? testValue == null : controlValue . equals ( testValue ) ; ComparisonResult initial = equal ? ComparisonResult . EQUAL : ComparisonResult . DIFFERENT ; ComparisonResult altered = getDifferenceEvaluator ( ) . evaluate ( comp , initial ) ; listeners . fireComparisonPerformed ( comp , altered ) ; return altered != ComparisonResult . EQUAL && getComparisonController ( ) . stopDiffing ( new Difference ( comp , altered ) ) ? new FinishedComparisonState ( altered ) : new OngoingComparisonState ( altered ) ; } | Compares the detail values for object equality lets the difference evaluator and comparison controller evaluate the result notifies all listeners and returns the outcome . |
38,984 | public static void setIgnoreWhitespace ( boolean ignore ) { ignoreWhitespace = ignore ; getControlDocumentBuilderFactory ( ) . setIgnoringElementContentWhitespace ( ignore ) ; getTestDocumentBuilderFactory ( ) . setIgnoringElementContentWhitespace ( ignore ) ; } | Whether to ignore whitespace when comparing node values . |
38,985 | public static Document buildControlDocument ( String fromXML ) throws SAXException , IOException { return buildDocument ( newControlParser ( ) , new StringReader ( fromXML ) ) ; } | Utility method to build a Document using the control DocumentBuilder to parse the specified String . |
38,986 | public static Document buildDocument ( DocumentBuilder withBuilder , Reader fromReader ) throws SAXException , IOException { return buildDocument ( withBuilder , new InputSource ( fromReader ) ) ; } | Utility method to build a Document using a specific DocumentBuilder and reading characters from a specific Reader . |
38,987 | public static Document buildDocument ( DocumentBuilder withBuilder , InputSource fromSource ) throws IOException , SAXException { return withBuilder . parse ( fromSource ) ; } | Utility method to build a Document using a specific DocumentBuilder and a specific InputSource |
38,988 | public static void setURIResolver ( URIResolver resolver ) { if ( uriResolver != resolver ) { uriResolver = resolver ; transformerFactory = null ; getTransformerFactory ( ) ; } } | Sets the URIResolver to use during transformations . |
38,989 | public static SAXParserFactory getSAXParserFactory ( ) { if ( saxParserFactory == null ) { saxParserFactory = SAXParserFactory . newInstance ( ) ; saxParserFactory . setNamespaceAware ( true ) ; } return saxParserFactory ; } | Get the SAX parser to use in tests . |
38,990 | public static Document getWhitespaceStrippedDocument ( Document forDoc ) { String factory = getTransformerFactory ( ) . getClass ( ) . getName ( ) ; if ( XSLTConstants . JAVA5_XSLTC_FACTORY_NAME . equals ( factory ) ) { return stripWhiteSpaceWithoutXSLT ( forDoc ) ; } else { return stripWhiteSpaceUsingXSLT ( forDoc ) ; } } | Returns a new Document instance that is identical to the one passed in with element content whitespace removed . |
38,991 | public static Diff compareXML ( InputSource control , InputSource test ) throws SAXException , IOException { return new Diff ( control , test ) ; } | Compare XML documents provided by two InputSource classes |
38,992 | public static Diff compareXML ( String control , String test ) throws SAXException , IOException { return new Diff ( control , test ) ; } | Compare two XML documents provided as strings |
38,993 | public static XpathEngine newXpathEngine ( ) { XpathEngine eng = new org . custommonkey . xmlunit . jaxp13 . Jaxp13XpathEngine ( ) ; if ( namespaceContext != null ) { eng . setNamespaceContext ( namespaceContext ) ; } return eng ; } | Obtains an XpathEngine to use in XPath tests . |
38,994 | public static void setIgnoreDiffBetweenTextAndCDATA ( boolean b ) { ignoreDiffBetweenTextAndCDATA = b ; getControlDocumentBuilderFactory ( ) . setCoalescing ( b ) ; getTestDocumentBuilderFactory ( ) . setCoalescing ( b ) ; } | Whether CDATA sections and Text nodes should be considered the same . |
38,995 | public static void setXSLTVersion ( String s ) { try { Number n = NumberFormat . getInstance ( Locale . US ) . parse ( s ) ; if ( n . doubleValue ( ) < 0 ) { throw new ConfigurationException ( s + " doesn't reperesent a" + " positive number." ) ; } } catch ( ParseException e ) { throw new ConfigurationException ( e ) ; } xsltVersion = s ; } | Sets the XSLT version to set on stylesheets used internally . |
38,996 | public static void setExpandEntityReferences ( boolean b ) { expandEntities = b ; getControlDocumentBuilderFactory ( ) . setExpandEntityReferences ( b ) ; getTestDocumentBuilderFactory ( ) . setExpandEntityReferences ( b ) ; } | Whether the parser shall be instructed to expand entity references . |
38,997 | public ValidationAssert isValid ( ) { ValidationResult validationResult = validate ( ) ; if ( ! validationResult . isValid ( ) ) { throwAssertionError ( shouldBeValid ( actual . getSystemId ( ) , validationResult . getProblems ( ) ) ) ; } return this ; } | Verifies that actual value is valid against given schema |
38,998 | public void isInvalid ( ) { ValidationResult validateResult = validate ( ) ; if ( validateResult . isValid ( ) ) { throwAssertionError ( shouldBeInvalid ( actual . getSystemId ( ) ) ) ; } } | Verifies that actual value is not valid against given schema |
38,999 | protected boolean equalsNamespace ( Node control , Node test ) { String controlNS = control . getNamespaceURI ( ) ; String testNS = test . getNamespaceURI ( ) ; if ( controlNS == null ) { return testNS == null ; } return controlNS . equals ( testNS ) ; } | Determine whether two nodes are defined by the same namespace URI |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.