idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
38,800
private void pushInput ( byte [ ] inputBytes ) throws Exception { buf . write ( inputBytes ) ; while ( buf . size ( ) >= 4 ) { byte [ ] bytes = buf . toByteArray ( ) ; int size = 0 ; size = ( size << 8 ) + byteToInt ( bytes [ 0 ] ) ; size = ( size << 8 ) + byteToInt ( bytes [ 1 ] ) ; size = ( size << 8 ) + byteToInt ( bytes [ 2 ] ) ; size = ( size << 8 ) + byteToInt ( bytes [ 3 ] ) ; if ( bytes . length >= 4 + size ) { String message = new PlistManager ( ) . plistBinaryToXml ( Arrays . copyOfRange ( bytes , 4 , size + 4 ) ) ; handler . handle ( message ) ; buf = new ByteArrayOutputStream ( ) ; buf . write ( bytes , 4 + size , bytes . length - size - 4 ) ; } else { break ; } } }
reads the messages from the AUT .
38,801
protected void read ( ) throws Exception { InputStream is = socket . getInputStream ( ) ; while ( is . available ( ) > 0 ) { byte [ ] bytes = new byte [ 1024 * 1024 ] ; int read = is . read ( bytes ) ; byte [ ] actuallyRead = new byte [ read ] ; System . arraycopy ( bytes , 0 , actuallyRead , 0 , read ) ; pushInput ( actuallyRead ) ; } }
listen for a complete message .
38,802
public static String extractMessage ( Throwable e ) { String msg = e . getMessage ( ) ; return msg == null ? "" : ( e instanceof WebDriverException ) ? msg . split ( "\n" ) [ 0 ] : msg ; }
Webdriver exception have debug info for the client . polluting server side .
38,803
public void setKeyboardOptions ( ) { File folder = new File ( contentAndSettingsFolder + "/Library/Preferences/" ) ; File preferenceFile = new File ( folder , "com.apple.Preferences.plist" ) ; try { JSONObject preferences = new JSONObject ( ) ; preferences . put ( "KeyboardAutocapitalization" , false ) ; preferences . put ( "KeyboardAutocorrection" , false ) ; preferences . put ( "KeyboardCapsLock" , false ) ; preferences . put ( "KeyboardCheckSpelling" , false ) ; writeOnDisk ( preferences , preferenceFile ) ; } catch ( Exception e ) { throw new WebDriverException ( "cannot set options in " + preferenceFile . getAbsolutePath ( ) , e ) ; } }
the default keyboard options aren t good for automation . For instance it automatically capitalize the first letter of sentences etc . Getting rid of all that to have the keyboard execute requests without changing them .
38,804
public void setAccessibilityOptions ( ) { File folder = new File ( contentAndSettingsFolder + "/Library/Preferences/" ) ; File preferenceFile = new File ( folder , "com.apple.Accessibility.plist" ) ; try { JSONObject preferences = new JSONObject ( ) ; if ( instrumentsVersion . getMajor ( ) < 6 ) { preferences . put ( "ApplicationAccessibilityEnabled" , true ) ; } else { preferences . put ( "ApplicationAccessibilityEnabled" , 1 ) ; } writeOnDisk ( preferences , preferenceFile ) ; } catch ( Exception e ) { throw new WebDriverException ( "cannot set options in " + preferenceFile . getAbsolutePath ( ) , e ) ; } }
Set the Accessibility preferences . Overrides the values in com . apple . Accessibility . plist file .
38,805
public void resetContentAndSettings ( ) { if ( instrumentsVersion . getMajor ( ) < 6 ) { if ( hasContentAndSettingsFolder ( ) ) { boolean ok = deleteRecursive ( getContentAndSettingsFolder ( ) ) ; if ( ! ok ) { System . err . println ( "cannot delete content and settings folder " + contentAndSettingsFolder ) ; } } String deviceLogDir = System . getProperty ( "user.home" ) + "/Library/Logs/iOS Simulator/" + exactSdkVersion + ( ( is64bit ) ? "-64" : "" ) ; File deviceLog = new File ( deviceLogDir , "system.log" ) ; if ( deviceLog . exists ( ) ) { deviceLog . delete ( ) ; } boolean ok = contentAndSettingsFolder . mkdirs ( ) ; if ( ! ok ) { System . err . println ( "couldn't re-create: " + contentAndSettingsFolder ) ; } } else { if ( ! eraseSimulator ( ) ) { log . info ( "Erase contents and settings failed on this device: " + deviceUUID ) ; tryToEraseSimulator ( ) ; } } }
Does what IOS Simulator - Reset content and settings menu does by deleting the files on disk . The simulator shouldn t be running when that is done .
38,806
private File extract ( InstrumentsVersion version ) { if ( version . getBuild ( ) == null ) { throw new WebDriverException ( "you are running a version of XCode that is too old " + version ) ; } extractFromJar ( "instruments" ) ; extractFromJar ( "InstrumentsShim.dylib" ) ; extractFromJar ( "ScriptAgentShim.dylib" ) ; if ( version . getMajor ( ) >= 6 ) { extractFromJar ( "DTMobileISShim.dylib" ) ; } extractFromJar ( "SimShim.dylib" ) ; extractFromJar ( "README" ) ; File instruments = new File ( workingDirectory , "instruments" ) ; instruments . setExecutable ( true ) ; return instruments ; }
extract the binaries for the specified version of instruments .
38,807
private void processVersionLine ( String log ) { log = log . replace ( start , "" ) ; String [ ] pieces = log . split ( " \\(" ) ; if ( pieces . length == 2 ) { version = pieces [ 0 ] ; build = pieces [ 1 ] . replace ( ")" , "" ) ; } else { version = pieces [ 0 ] ; build = null ; } }
string parsing to get the version out .
38,808
public static < T > T augment ( WebDriver driver ) { Augmenter augmenter = new Augmenter ( ) ; augmenter . addDriverAugmentation ( IOSCapabilities . CONFIGURABLE , new AddConfigurable ( ) ) ; augmenter . addDriverAugmentation ( IOSCapabilities . ELEMENT_TREE , new AddLogElementTree ( ) ) ; augmenter . addDriverAugmentation ( IOSCapabilities . IOS_SEARCH_CONTEXT , new AddIOSSearchContext ( ) ) ; augmenter . addDriverAugmentation ( IOSCapabilities . IOS_TOUCH_SCREEN , new AddIOSTouchScreen ( ) ) ; return ( T ) augmenter . augment ( driver ) ; }
Add all the IOS specific interfaces ios - driver supports .
38,809
public static File extractAppFromURL ( URL url ) throws IOException { String fileName = url . toExternalForm ( ) . substring ( url . toExternalForm ( ) . lastIndexOf ( '/' ) + 1 ) ; File tmpDir = createTmpDir ( "iosd" ) ; log . fine ( "tmpDir: " + tmpDir . getAbsolutePath ( ) ) ; File downloadedFile = new File ( tmpDir , fileName ) ; FileUtils . copyURLToFile ( url , downloadedFile ) ; if ( fileName . endsWith ( ".ipa" ) ) return downloadedFile ; unzip ( downloadedFile , tmpDir ) ; for ( File file : tmpDir . listFiles ( ) ) { if ( file . getName ( ) . endsWith ( ".app" ) ) { return file ; } } throw new WebDriverException ( "cannot extract .app/.ipa from " + url ) ; }
Downloads zip from from url extracts it into tmp dir and returns path to extracted directory
38,810
private void forceWebViewToReloadManually ( int retry ) { boolean ok = false ; setMode ( WorkingMode . Native ) ; for ( int i = 0 ; i < retry ; i ++ ) { try { WebElement b = getNativeDriver ( ) . findElement ( By . xpath ( "//UIAWindow/UIAScrollView/UIAButton" ) ) ; b . click ( ) ; ok = true ; } catch ( WebDriverException e ) { sleep ( 2000 ) ; log . fine ( "about:blank button gone, proceeding" ) ; break ; } } if ( ! ok ) { log . warning ( "Couldn't find button after " + retry + "retries." ) ; throw new RecoverableCrashException ( "coudln't find the about:blank button after " + retry + " retries." ) ; } setMode ( WorkingMode . Web ) ; }
the webview doesn t refresh correctly if it hasn t been loaded at lease once .
38,811
public static WebElement createObject ( RemoteWebDriver driver , Map < String , Object > ro ) { String ref = ro . get ( "ELEMENT" ) . toString ( ) ; String type = ( String ) ro . get ( "type" ) ; if ( type != null ) { String remoteObjectName = "org.uiautomation.ios.client.uiamodels.impl.Remote" + type ; if ( "UIAElementNil" . equals ( type ) ) { return null ; } boolean isArray = false ; Object [ ] args = null ; Class < ? > [ ] argsClass = null ; if ( isArray ) { } else { args = new Object [ ] { driver , ref } ; argsClass = new Class [ ] { RemoteWebDriver . class , String . class } ; } try { Class < ? > clazz = Class . forName ( remoteObjectName ) ; Constructor < ? > c = clazz . getConstructor ( argsClass ) ; Object o = c . newInstance ( args ) ; RemoteWebElement element = ( RemoteWebElement ) o ; element . setFileDetector ( driver . getFileDetector ( ) ) ; element . setParent ( driver ) ; element . setId ( ref ) ; return ( RemoteIOSObject ) o ; } catch ( Exception e ) { throw new WebDriverException ( "error casting" , e ) ; } } else { RemoteWebElement element = new RemoteWebElement ( ) ; element . setFileDetector ( driver . getFileDetector ( ) ) ; element . setId ( ref ) ; element . setParent ( driver ) ; return element ; } }
Uses reflection to instanciate a remote object implementing the correct interface .
38,812
public Response handle ( ) throws Exception { Object p = getRequest ( ) . getPayload ( ) . get ( "id" ) ; if ( JSONObject . NULL . equals ( p ) ) { getWebDriver ( ) . getContext ( ) . setCurrentFrame ( null , null , null ) ; } else { RemoteWebElement iframe ; if ( p instanceof String ) { iframe = getIframe ( ( String ) p ) ; } else if ( p instanceof Integer ) { iframe = getIframe ( ( Integer ) p ) ; } else if ( p instanceof JSONObject ) { String id = ( ( JSONObject ) p ) . getString ( "ELEMENT" ) ; iframe = getWebDriver ( ) . createElement ( id ) ; } else { throw new UnsupportedCommandException ( "not supported : frame selection by " + p . getClass ( ) ) ; } RemoteWebElement document = iframe . getContentDocument ( ) ; RemoteWebElement window = iframe . getContentWindow ( ) ; getWebDriver ( ) . getContext ( ) . setCurrentFrame ( iframe , document , window ) ; } Response res = new Response ( ) ; res . setSessionId ( getSession ( ) . getSessionId ( ) ) ; res . setStatus ( 0 ) ; res . setValue ( new JSONObject ( ) ) ; return res ; }
NoSuchFrame - If the frame specified by id cannot be found .
38,813
private ImmutableList < LanguageDictionary > loadDictionaries ( ) { Map < String , LanguageDictionary > languageNameMap = new HashMap < > ( ) ; for ( File f : LanguageDictionary . getL10NFiles ( app ) ) { String name = LanguageDictionary . extractLanguageName ( f ) ; LanguageDictionary res = languageNameMap . get ( name ) ; if ( res == null ) { res = new LanguageDictionary ( name ) ; languageNameMap . put ( name , res ) ; } try { JSONObject content = res . readContentFromBinaryFile ( f ) ; res . addJSONContent ( content ) ; } catch ( Exception e ) { log . warning ( "Error loading content for l10n for file: " + f . getAbsolutePath ( ) + ", exception: " + e . getMessage ( ) + "\n" + Arrays . asList ( e . getStackTrace ( ) ) ) ; } } List < LanguageDictionary > dicts = new ArrayList < > ( languageNameMap . values ( ) ) ; Collections . sort ( dicts , new Comparator < LanguageDictionary > ( ) { public int compare ( LanguageDictionary o1 , LanguageDictionary o2 ) { return o1 . getLanguage ( ) . compareTo ( o2 . getLanguage ( ) ) ; } } ) ; return ImmutableList . copyOf ( dicts ) ; }
Load all the dictionaries for the application .
38,814
public Map < String , String > getResources ( ) { Map < String , String > resourceByResourceName = new HashMap < > ( ) ; String metadata = getMetadata ( ICON ) ; if ( metadata . equals ( "" ) ) { metadata = getFirstIconFile ( BUNDLE_ICONS ) ; } resourceByResourceName . put ( ICON , metadata ) ; return resourceByResourceName ; }
the list of resources to publish via http .
38,815
public JSONObject readContentFromBinaryFile ( File binaryFile ) throws Exception { PlistFileUtils util = new PlistFileUtils ( binaryFile ) ; return util . toJSON ( ) ; }
load the content of the binary file and returns it as a json object .
38,816
private JSONObject getCriteria ( JSONObject payload ) throws JSONException { if ( payload . has ( "criteria" ) ) { JSONObject json = payload . getJSONObject ( "criteria" ) ; return json ; } else if ( payload . has ( "using" ) ) { return getCriteriaFromWebDriverSelector ( payload ) ; } else { throw new InvalidSelectorException ( "wrong format for the findElement command " + payload ) ; } }
create the criteria for the request . If the request follows the webdriver protocol maps it to a criteria ios - driver understands .
38,817
private JSONObject getCriteriaFromWebDriverSelector ( JSONObject payload ) throws JSONException { String using = payload . getString ( "using" ) ; String value = payload . getString ( "value" ) ; if ( "tag name" . equals ( using ) || "class name" . equals ( using ) ) { try { Package p = UIAElement . class . getPackage ( ) ; Criteria c = new TypeCriteria ( Class . forName ( p . getName ( ) + "." + value ) ) ; return c . stringify ( ) ; } catch ( ClassNotFoundException e ) { throw new InvalidSelectorException ( value + " is not a recognized type." ) ; } } else if ( "name" . equals ( using ) || "id" . equals ( using ) ) { Criteria c = new NameCriteria ( getAUT ( ) . applyL10N ( value ) ) ; return c . stringify ( ) ; } else if ( "link text" . equals ( using ) || "partial link text" . equals ( using ) ) { return createGenericCriteria ( using , value ) ; } else { throw new InvalidSelectorException ( using + "is not a valid selector for the native part of ios-driver." ) ; } }
handles the mapping from the webdriver using to a criteria .
38,818
public void setCurrentFrame ( RemoteWebElement iframe , RemoteWebElement document , RemoteWebElement window ) { this . iframe = iframe ; this . document = document ; this . window = window ; if ( iframe != null ) { isOnMainFrame = false ; } else { isOnMainFrame = true ; } if ( iframe == null && document == null ) { this . document = mainDocument ; this . window = mainWindow ; } if ( iframe == null && document != null ) { mainDocument = document ; mainWindow = window ; } isReady = true ; }
breaks the nodeId reference .
38,819
public void start ( ) { if ( log . isLoggable ( Level . FINE ) ) { log . fine ( String . format ( "Starting command: %s" , commandString ( ) ) ) ; } ProcessBuilder builder = new ProcessBuilder ( args ) ; if ( workingDir != null ) { builder . directory ( workingDir ) ; } if ( ! environment . isEmpty ( ) ) { Map < String , String > env = builder . environment ( ) ; env . putAll ( environment ) ; } try { process = builder . start ( ) ; } catch ( IOException e ) { throw new WebDriverException ( "failed to start process " + args , e ) ; } threads . add ( listen ( process . getInputStream ( ) , out , true ) ) ; threads . add ( listen ( process . getErrorStream ( ) , err , false ) ) ; }
Starts the command . Doesn t wait for it to finish . Doesn t wait for stdout and stderr either .
38,820
public < T > T execute ( WebDriverLikeRequest request ) { Response response = null ; long total = 0 ; try { HttpClient client = newHttpClientWithTimeout ( ) ; String url = remoteURL + request . getPath ( ) ; BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest ( request . getMethod ( ) , url ) ; if ( request . hasPayload ( ) ) { r . setEntity ( new StringEntity ( request . getPayload ( ) . toString ( ) , "UTF-8" ) ) ; } HttpHost h = new HttpHost ( remoteURL . getHost ( ) , remoteURL . getPort ( ) ) ; long start = System . currentTimeMillis ( ) ; HttpResponse res = client . execute ( h , r ) ; total = System . currentTimeMillis ( ) - start ; response = Helper . exctractResponse ( res ) ; } catch ( Exception e ) { throw new WebDriverException ( e ) ; } response = errorHandler . throwIfResponseFailed ( response , total ) ; try { return cast ( response . getValue ( ) ) ; } catch ( ClassCastException e ) { log . warning ( e . getMessage ( ) + " for " + response . getValue ( ) ) ; throw e ; } }
send the request to the remote server for execution .
38,821
public Subscription subscribe ( String applicationName , String eventName , String consumerGroup ) throws IOException { return subscription ( applicationName , eventName ) . withConsumerGroup ( consumerGroup ) . subscribe ( ) ; }
Create a subscription for a single event type .
38,822
public SubscriptionBuilder subscription ( String applicationName , String eventName ) throws IOException { return new SubscriptionBuilder ( this , applicationName , Collections . singleton ( eventName ) ) ; }
Build a subscription for a single event type .
38,823
public SubscriptionBuilder subscription ( String applicationName , Set < String > eventNames ) throws IOException { return new SubscriptionBuilder ( this , applicationName , eventNames ) ; }
Build a subscription for multiple event types .
38,824
public void deleteSubscription ( String subscriptionId ) throws IOException { checkArgument ( ! subscriptionId . isEmpty ( ) , "Subscription ID cannot be empty." ) ; final URI uri = baseUri . resolve ( String . format ( "/subscriptions/%s" , subscriptionId ) ) ; final Request request = clientHttpRequestFactory . createRequest ( uri , "DELETE" ) ; request . getHeaders ( ) . setContentType ( ContentType . APPLICATION_JSON ) ; try ( final Response response = request . execute ( ) ) { final int status = response . getStatusCode ( ) ; if ( status == 204 ) { LOG . debug ( "Successfully deleted subscription [{}]" , subscriptionId ) ; } } }
Delete subscription based on subscription ID .
38,825
private HttpURLConnection openConnection ( URL url ) throws IOException { URLConnection urlConnection = url . openConnection ( ) ; if ( ! ( urlConnection instanceof HttpURLConnection ) ) { throw new IllegalStateException ( "Connection should be an HttpURLConnection" ) ; } return ( HttpURLConnection ) urlConnection ; }
Opens and returns a connection to the given URL .
38,826
public StreamParameters withCommitTimeout ( int commitTimeout ) { return new StreamParameters ( batchLimit , streamLimit , batchFlushTimeout , streamTimeout , streamKeepAliveLimit , maxUncommittedEvents , commitTimeout ) ; }
Maximum amount of seconds that nakadi will be waiting for commit after sending a batch to a client . If the commit does not come within this timeout nakadi will initialize stream termination no new data will be sent . Partitions from this stream will be assigned to other streams .
38,827
private void initializeProcessor ( JsonProcessor processor ) throws ODataUnmarshallingException { LOG . info ( "Trying to initialize processor: {}" , processor . getClass ( ) . getSimpleName ( ) ) ; processor . initialize ( ) ; fields = processor . getValues ( ) ; odataValues = processor . getODataValues ( ) ; links = processor . getLinks ( ) ; }
Initialize processor ready for for unmarshalling entity .
38,828
private String getEntityName ( ) throws ODataUnmarshallingException { String odataType = odataValues . get ( JsonConstants . TYPE ) ; if ( isNullOrEmpty ( odataType ) ) { TargetType targetType = getTargetType ( ) ; if ( targetType == null ) { throw new ODataUnmarshallingException ( "Could not find entity name" ) ; } return targetType . typeName ( ) ; } else { if ( odataType . startsWith ( "#" ) ) { odataType = odataType . substring ( 1 ) ; } return odataType ; } }
Gets the entity type name .
38,829
protected void setEntityNavigationProperties ( Object entity , StructuredType entityType ) throws ODataException { for ( Map . Entry < String , Object > entry : links . entrySet ( ) ) { String propertyName = entry . getKey ( ) ; Object entryLinks = entry . getValue ( ) ; LOG . debug ( "Found link for navigation property: {}" , propertyName ) ; StructuralProperty property = entityType . getStructuralProperty ( propertyName ) ; if ( ! ( property instanceof NavigationProperty ) ) { throw new ODataUnmarshallingException ( "The request contains a navigation link '" + propertyName + "' but the entity type '" + entityType + "' does not contain a navigation property " + "with this name." ) ; } if ( isWriteOperation ( ) ) { if ( entryLinks instanceof List ) { List < String > linksList = ( List < String > ) entryLinks ; for ( String link : linksList ) { Object referencedEntity = getReferencedEntity ( link , propertyName ) ; LOG . debug ( "Referenced entity: {}" , referencedEntity ) ; saveReferencedEntity ( entity , propertyName , property , referencedEntity ) ; } } else { Object referencedEntity = getReferencedEntity ( ( String ) entryLinks , propertyName ) ; LOG . debug ( "Referenced entity: {}" , referencedEntity ) ; saveReferencedEntity ( entity , propertyName , property , referencedEntity ) ; } } } }
Sets the given entity with navigation links .
38,830
public void writeStartFeed ( String requestContextURL , Map < String , Object > meta ) throws ODataRenderException { this . contextURL = checkNotNull ( requestContextURL ) ; try { startFeed ( false ) ; if ( ODataUriUtil . hasCountOption ( oDataUri ) && meta != null && meta . containsKey ( "count" ) ) { metadataWriter . writeCount ( meta . get ( "count" ) ) ; } metadataWriter . writeFeedId ( null , null ) ; metadataWriter . writeTitle ( ) ; metadataWriter . writeUpdate ( dateTime ) ; metadataWriter . writeFeedLink ( null , null ) ; } catch ( XMLStreamException | ODataEdmException e ) { LOG . error ( "Not possible to marshall feed stream XML" ) ; throw new ODataRenderException ( "Not possible to marshall feed stream XML: " , e ) ; } }
Write start feed to the XML stream .
38,831
public void writeBodyFeed ( List < ? > entities ) throws ODataRenderException { checkNotNull ( entities ) ; try { for ( Object entity : entities ) { writeEntry ( entity , true ) ; } } catch ( XMLStreamException | IllegalAccessException | NoSuchFieldException | ODataEdmException e ) { LOG . error ( "Not possible to marshall feed stream XML" ) ; throw new ODataRenderException ( "Not possible to marshall feed stream XML: " , e ) ; } }
Write feed body .
38,832
public String getXml ( ) { try { return ( ( ByteArrayOutputStream ) outputStream ) . toString ( StandardCharsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { return outputStream . toString ( ) ; } }
Get the generated XML .
38,833
public static void closeIfNecessary ( Closeable closeable ) throws ODataClientException { if ( closeable != null ) { try { closeable . close ( ) ; } catch ( IOException e ) { throw new ODataClientException ( "Could not close '" + closeable . getClass ( ) . getSimpleName ( ) + "'" , e ) ; } } }
Close closable objects if it is necessary . Mostly used to close connections .
38,834
public static Map < String , String > populateRequestProperties ( Map < String , String > requestProperties , int bodyLength , MediaType contentType , MediaType acceptType ) { Map < String , String > properties ; if ( requestProperties == null || requestProperties . isEmpty ( ) ) { properties = new HashMap < > ( ) ; } else { properties = new HashMap < > ( requestProperties ) ; } if ( acceptType != null ) { properties . put ( HeaderNames . ACCEPT , acceptType . toString ( ) ) ; } if ( contentType != null ) { properties . put ( HeaderNames . CONTENT_TYPE , contentType . toString ( ) ) ; } if ( bodyLength > - 1 ) { properties . put ( HeaderNames . CONTENT_LENGTH , String . valueOf ( bodyLength ) ) ; } return properties ; }
Util method for first populating request properties before execution .
38,835
public Object getAction ( ) throws ODataException { Option < String > actionNameOption = ODataUriUtil . getActionCallName ( odataUri ) ; if ( actionNameOption . isDefined ( ) ) { LOG . debug ( "The operation is supposed to be an action" ) ; String actionName = actionNameOption . get ( ) ; return parseAction ( actionName ) ; } Option < String > actionImportNameOption = ODataUriUtil . getActionImportCallName ( odataUri ) ; if ( actionImportNameOption . isDefined ( ) ) { LOG . debug ( "The operation is supposed to be an action import" ) ; String actionImportName = actionImportNameOption . get ( ) ; return parseActionImport ( actionImportName ) ; } throw new ODataUnmarshallingException ( "Not able to parse action / action import" ) ; }
Returns the instance of Action with all parameters provided by request .
38,836
public void addActionImport ( Class < ? > cls ) { EdmActionImport actionImportAnnotation = cls . getAnnotation ( EdmActionImport . class ) ; ActionImportImpl . Builder actionImportBuilder = new ActionImportImpl . Builder ( ) . setEntitySetName ( actionImportAnnotation . entitySet ( ) ) . setActionName ( actionImportAnnotation . namespace ( ) + "." + actionImportAnnotation . action ( ) ) . setName ( actionImportAnnotation . name ( ) ) . setJavaClass ( cls ) ; actionImportBuilders . add ( actionImportBuilder ) ; }
Adds an action import to factory .
38,837
public Iterable < ActionImport > build ( FactoryLookup lookup ) { List < ActionImport > actionImports = new ArrayList < > ( ) ; for ( ActionImportImpl . Builder actionImportBuilder : actionImportBuilders ) { actionImportBuilder . setEntitySet ( lookup . getEntitySet ( actionImportBuilder . getEntitySetName ( ) ) ) ; actionImportBuilder . setAction ( lookup . getAction ( actionImportBuilder . getActionName ( ) ) ) ; actionImports . add ( actionImportBuilder . build ( ) ) ; } return Collections . unmodifiableList ( actionImports ) ; }
Builds action import objects based on registered classes .
38,838
public String getJsonError ( ODataException exception ) throws ODataRenderException { checkNotNull ( exception ) ; LOG . debug ( "Start building Json error document" ) ; ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; try { JsonGenerator jsonGenerator = JSON_FACTORY . createGenerator ( outputStream , JsonEncoding . UTF8 ) ; jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeObjectFieldStart ( ERROR ) ; jsonGenerator . writeStringField ( CODE , String . valueOf ( exception . getCode ( ) . getCode ( ) ) ) ; jsonGenerator . writeStringField ( MESSAGE , String . valueOf ( exception . getMessage ( ) ) ) ; if ( exception . getTarget ( ) != null ) { jsonGenerator . writeStringField ( TARGET , String . valueOf ( exception . getTarget ( ) ) . replace ( "\"" , "'" ) ) ; } jsonGenerator . writeEndObject ( ) ; jsonGenerator . close ( ) ; return outputStream . toString ( ) ; } catch ( IOException e ) { LOG . error ( "Not possible to write error JSON." ) ; throw new ODataRenderException ( "Not possible to write error JSON: " , e ) ; } }
Gets the json error output according to ODataException .
38,839
public void writeData ( Object entity , EntityType entityType ) throws XMLStreamException , ODataRenderException { xmlWriter . writeStartElement ( ODATA_CONTENT ) ; xmlWriter . writeAttribute ( TYPE , XML . toString ( ) ) ; xmlWriter . writeStartElement ( METADATA , ODATA_PROPERTIES , "" ) ; marshall ( entity , entityType ) ; xmlWriter . writeEndElement ( ) ; xmlWriter . writeEndElement ( ) ; }
Write the data for a given entity .
38,840
private void marshallPrimitive ( Object value , PrimitiveType primitiveType ) throws XMLStreamException { LOG . trace ( "Primitive value: {} of type: {}" , value , primitiveType ) ; if ( value != null ) { xmlWriter . writeCharacters ( value . toString ( ) ) ; } }
Marshall a primitive value .
38,841
public void endDocument ( ) throws ODataRenderException { try { xmlWriter . writeEndDocument ( ) ; xmlWriter . flush ( ) ; } catch ( XMLStreamException e ) { LOG . error ( "Not possible to end stream XML" ) ; throw new ODataRenderException ( "Not possible to end stream XML: " , e ) ; } }
End the XML stream document .
38,842
public void writeMetadataDocument ( ) throws ODataRenderException { try { xmlWriter . writeStartElement ( EDMX_NS , EDMX ) ; xmlWriter . writeNamespace ( EDMX_PREFIX , EDMX_NS ) ; xmlWriter . writeAttribute ( VERSION , ODATA_VERSION ) ; xmlWriter . writeStartElement ( EDMX_NS , EDMX_DATA_SERVICES ) ; boolean entityContinerWritten = false ; for ( Schema schema : entityDataModel . getSchemas ( ) ) { xmlWriter . writeStartElement ( SCHEMA ) ; xmlWriter . writeDefaultNamespace ( EDM_NS ) ; xmlWriter . writeAttribute ( NAMESPACE , schema . getNamespace ( ) ) ; for ( Type type : schema . getTypes ( ) ) { switch ( type . getMetaType ( ) ) { case ENTITY : entityTypeWriter . write ( ( EntityType ) type ) ; break ; case COMPLEX : complexTypeWriter . write ( ( ComplexType ) type ) ; break ; case ENUM : enumTypeWriter . write ( ( EnumType ) type ) ; break ; default : LOG . error ( "Unexpected type: {}" , type . getFullyQualifiedName ( ) ) ; throw new ODataRenderException ( "Unexpected type: " + type . getFullyQualifiedName ( ) ) ; } } if ( ! entityContinerWritten ) { writeEntityContainer ( entityDataModel . getEntityContainer ( ) ) ; entityContinerWritten = true ; } xmlWriter . writeEndElement ( ) ; } xmlWriter . writeEndElement ( ) ; } catch ( XMLStreamException e ) { LOG . error ( "Not possible to start stream XML" ) ; throw new ODataRenderException ( "Not possible to start stream XML: " , e ) ; } }
Write the Metadata Document .
38,843
public static Type getAndCheckType ( EntityDataModel entityDataModel , Class < ? > javaType ) { Type type = entityDataModel . getType ( javaType ) ; if ( type == null ) { throw new ODataSystemException ( "No type found in the entity data model for Java type: " + javaType . getName ( ) ) ; } return type ; }
Gets the OData type for a Java type and throws an exception if there is no OData type for the Java type .
38,844
public static PrimitiveType checkIsPrimitiveType ( Type type ) { if ( ! isPrimitiveType ( type ) ) { throw new ODataSystemException ( "A primitive type is required, but '" + type . getFullyQualifiedName ( ) + "' is not a primitive type: " + type . getMetaType ( ) ) ; } return ( PrimitiveType ) type ; }
Checks if the specified OData type is a primitive type and throws an exception if it is not .
38,845
public static PrimitiveType getAndCheckPrimitiveType ( EntityDataModel entityDataModel , String typeName ) { return checkIsPrimitiveType ( getAndCheckType ( entityDataModel , typeName ) ) ; }
Gets the OData type with a specified name and checks if the OData type is a primitive type ; throws an exception if the OData type is not a primitive type .
38,846
public static StructuredType checkIsStructuredType ( Type type ) { if ( ! isStructuredType ( type ) ) { throw new ODataSystemException ( "A structured type is required, but '" + type . getFullyQualifiedName ( ) + "' is not a structured type: " + type . getMetaType ( ) ) ; } return ( StructuredType ) type ; }
Checks if the specified OData type is a structured type and throws an exception if it is not .
38,847
public static StructuredType getAndCheckStructuredType ( EntityDataModel entityDataModel , String typeName ) { return checkIsStructuredType ( getAndCheckType ( entityDataModel , typeName ) ) ; }
Gets the OData type with a specified name and checks if the OData type is a structured type ; throws an exception if the OData type is not a structured type .
38,848
public static StructuredType getAndCheckStructuredType ( EntityDataModel entityDataModel , Class < ? > javaType ) { return checkIsStructuredType ( getAndCheckType ( entityDataModel , javaType ) ) ; }
Gets the OData type for a Java type and checks if the OData type is a structured type ; throws an exception if the OData type is not a structured type .
38,849
public static EntityType checkIsEntityType ( Type type ) { if ( ! isEntityType ( type ) ) { throw new ODataSystemException ( "An entity type is required, but '" + type . getFullyQualifiedName ( ) + "' is not an entity type: " + type . getMetaType ( ) ) ; } return ( EntityType ) type ; }
Checks if the specified OData type is an entity type and throws an exception if it is not .
38,850
public static EntityType getAndCheckEntityType ( EntityDataModel entityDataModel , String typeName ) { return checkIsEntityType ( getAndCheckType ( entityDataModel , typeName ) ) ; }
Gets the OData type with a specified name and checks if the OData type is an entity type ; throws an exception if the OData type is not an entity type .
38,851
public static EntityType getAndCheckEntityType ( EntityDataModel entityDataModel , Class < ? > javaType ) { return checkIsEntityType ( getAndCheckType ( entityDataModel , javaType ) ) ; }
Gets the OData type for a Java type and checks if the OData type is an entity type ; throws an exception if the OData type is not an entity type .
38,852
public static ComplexType checkIsComplexType ( Type type ) { if ( ! isComplexType ( type ) ) { throw new ODataSystemException ( "A complex type is required, but '" + type . getFullyQualifiedName ( ) + "' is not a complex type: " + type . getMetaType ( ) ) ; } return ( ComplexType ) type ; }
Checks if the specified OData type is a complex type and throws an exception if it is not .
38,853
public static ComplexType getAndCheckComplexType ( EntityDataModel entityDataModel , Class < ? > javaType ) { return checkIsComplexType ( getAndCheckType ( entityDataModel , javaType ) ) ; }
Gets the OData type for a Java type and checks if the OData type is a complex type ; throws an exception if the OData type is not a complex type .
38,854
public static String getPropertyTypeName ( StructuralProperty property ) { return property . isCollection ( ) ? property . getElementTypeName ( ) : property . getTypeName ( ) ; }
Gets the OData type name of the property ; if the property is a collection gets the OData type name of the elements of the collection .
38,855
public static Type getPropertyType ( EntityDataModel entityDataModel , StructuralProperty property ) { return getAndCheckType ( entityDataModel , getPropertyTypeName ( property ) ) ; }
Gets the OData type of the property ; if the property is a collection gets the OData type of the elements of the collection .
38,856
public static StructuralProperty getStructuralProperty ( EntityDataModel entityDataModel , StructuredType structuredType , String propertyName ) { StructuralProperty structuralProperty = structuredType . getStructuralProperty ( propertyName ) ; if ( structuralProperty != null ) { return structuralProperty ; } else { String baseTypeName = structuredType . getBaseTypeName ( ) ; if ( ! isNullOrEmpty ( baseTypeName ) ) { Type baseType = entityDataModel . getType ( baseTypeName ) ; if ( baseType != null && baseType instanceof StructuredType ) { return getStructuralProperty ( entityDataModel , ( StructuredType ) baseType , propertyName ) ; } } } return null ; }
Get the Structural Property from the given Entity Data Model and Structured Type looking up all the base types recursively .
38,857
public static Set < String > getKeyPropertyNames ( EntityType entityType ) { Set < String > keyPropertyNames = entityType . getKey ( ) . getPropertyRefs ( ) . stream ( ) . map ( PropertyRef :: getPath ) . collect ( Collectors . toSet ( ) ) ; return keyPropertyNames ; }
Gets the names of the properties that are part of the key of an entity type .
38,858
public static Map < String , Object > getKeyPropertyValues ( EntityType entityType , Object entity ) { Map < String , Object > keyPropertyValues = new HashMap < > ( ) ; for ( PropertyRef propertyRef : entityType . getKey ( ) . getPropertyRefs ( ) ) { String propertyName = propertyRef . getPath ( ) ; Object propertyValue = getPropertyValue ( entityType . getStructuralProperty ( propertyName ) , entity ) ; keyPropertyValues . put ( propertyName , propertyValue ) ; } return keyPropertyValues ; }
Gets the values of the properties that part of the key of an entity type .
38,859
public static EntitySet getAndCheckEntitySet ( EntityDataModel entityDataModel , String entitySetName ) { EntitySet entitySet = entityDataModel . getEntityContainer ( ) . getEntitySet ( entitySetName ) ; if ( entitySet == null ) { throw new ODataSystemException ( "Entity set not found in the entity data model: " + entitySetName ) ; } return entitySet ; }
Gets the entity set with the specified name throws an exception if no entity set with the specified name exists .
38,860
public static EntitySet getEntitySetByEntityTypeName ( EntityDataModel entityDataModel , String entityTypeName ) throws ODataEdmException { for ( EntitySet entitySet : entityDataModel . getEntityContainer ( ) . getEntitySets ( ) ) { if ( entitySet . getTypeName ( ) . equals ( entityTypeName ) ) { return entitySet ; } } throw new ODataSystemException ( "Entity set not found in the entity data model for type: " + entityTypeName ) ; }
Get the Entity Set for a given Entity Type name through the Entity Data Model .
38,861
public static String getEntityNameByEntityTypeName ( EntityDataModel entityDataModel , String entityTypeName ) throws ODataEdmException { for ( EntitySet entitySet : entityDataModel . getEntityContainer ( ) . getEntitySets ( ) ) { if ( entitySet . getTypeName ( ) . equals ( entityTypeName ) ) { return entitySet . getName ( ) ; } } for ( Singleton singleton : entityDataModel . getEntityContainer ( ) . getSingletons ( ) ) { if ( singleton . getTypeName ( ) . equals ( entityTypeName ) ) { return singleton . getName ( ) ; } } throw new ODataSystemException ( "Entity name not found in the entity data model for type: " + entityTypeName ) ; }
Get the Entity Name for a given Entity Type name through the Entity Data Model . This looks for entity in both EntitySets and Singletons in the container
38,862
public static EntitySet getEntitySetByEntity ( EntityDataModel entityDataModel , Object entity ) throws ODataEdmException { return getEntitySetByEntityTypeName ( entityDataModel , getAndCheckEntityType ( entityDataModel , entity . getClass ( ) ) . getFullyQualifiedName ( ) ) ; }
Get the Entity Set of a given entity through the Entity Data Model .
38,863
public static boolean isSingletonEntity ( EntityDataModel entityDataModel , Object entity ) throws ODataEdmException { EntityType entityType = getAndCheckEntityType ( entityDataModel , entity . getClass ( ) ) ; boolean isSingletonEntity = false ; for ( Singleton singleton : entityDataModel . getEntityContainer ( ) . getSingletons ( ) ) { if ( singleton . getTypeName ( ) . equals ( entityType . getFullyQualifiedName ( ) ) ) { isSingletonEntity = true ; break ; } } return isSingletonEntity ; }
Check if the given entity is a Singleton entity .
38,864
public static String getEntityName ( EntityDataModel entityDataModel , Object entity ) throws ODataEdmException { EntityType entityType = getAndCheckEntityType ( entityDataModel , entity . getClass ( ) ) ; String entityName = null ; for ( EntitySet entitySet : entityDataModel . getEntityContainer ( ) . getEntitySets ( ) ) { if ( entitySet . getTypeName ( ) . equals ( entityType . getFullyQualifiedName ( ) ) ) { entityName = entitySet . getName ( ) ; break ; } } if ( entityName == null ) { for ( Singleton singleton : entityDataModel . getEntityContainer ( ) . getSingletons ( ) ) { if ( singleton . getTypeName ( ) . equals ( entityType . getFullyQualifiedName ( ) ) ) { entityName = singleton . getName ( ) ; break ; } } if ( entityName == null ) { throw new ODataSystemException ( "Entity not found in the entity data model for type: " + entityType . getFullyQualifiedName ( ) ) ; } } return entityName ; }
Get the entity name in the entity data model for the given entity .
38,865
public static Singleton getAndCheckSingleton ( EntityDataModel entityDataModel , String singletonName ) { Singleton singleton = entityDataModel . getEntityContainer ( ) . getSingleton ( singletonName ) ; if ( singleton == null ) { throw new ODataSystemException ( "Singleton not found in the entity data model: " + singletonName ) ; } return singleton ; }
Gets the singleton with the specified name throws an exception if no singleton with the specified name exists .
38,866
public static FunctionImport getAndCheckFunctionImport ( EntityDataModel entityDataModel , String functionImportName ) { FunctionImport functionImport = entityDataModel . getEntityContainer ( ) . getFunctionImport ( functionImportName ) ; if ( functionImport == null ) { throw new ODataSystemException ( "Function import not found in the entity data model: " + functionImportName ) ; } return functionImport ; }
Gets the function import by the specified name throw an exception if no function import with the specified name exists .
38,867
public static ActionImport getAndCheckActionImport ( EntityDataModel entityDataModel , String actionImportName ) { ActionImport actionImport = entityDataModel . getEntityContainer ( ) . getActionImport ( actionImportName ) ; if ( actionImport == null ) { throw new ODataSystemException ( "Action import not found in the entity data model: " + actionImportName ) ; } return actionImport ; }
Gets the action import by the specified name throw an exception if no action import with the specified name exists .
38,868
public static Action getAndCheckAction ( EntityDataModel entityDataModel , String actionName ) { int namespaceLastIndex = actionName . lastIndexOf ( '.' ) ; String namespace = actionName . substring ( 0 , namespaceLastIndex ) ; String simpleActionName = actionName . substring ( namespaceLastIndex + 1 ) ; Schema schema = entityDataModel . getSchema ( namespace ) ; if ( schema == null ) { throw new ODataSystemException ( "Could not find schema in entity data model with namespace: " + namespace ) ; } Action action = schema . getAction ( simpleActionName ) ; if ( action == null ) { throw new ODataSystemException ( "Action not found in entity data model: " + actionName ) ; } return action ; }
Gets the action by the specified name throw an exception if no action with the specified name exists .
38,869
public static boolean isCollection ( EntityDataModel entityDataModel , String typeName ) { EntitySet entitySet = entityDataModel . getEntityContainer ( ) . getEntitySet ( typeName ) ; if ( entitySet != null ) { return true ; } try { if ( Collection . class . isAssignableFrom ( Class . forName ( typeName ) ) || COLLECTION_PATTERN . matcher ( typeName ) . matches ( ) ) { return true ; } } catch ( ClassNotFoundException e ) { LOG . debug ( "Not possible to find class for type name: {}" , typeName ) ; } return false ; }
Checks if the specified typeName is a collection .
38,870
public static String formatEntityKey ( EntityDataModel entityDataModel , Object entity ) throws ODataEdmException { Key entityKey = getAndCheckEntityType ( entityDataModel , entity . getClass ( ) ) . getKey ( ) ; List < PropertyRef > keyPropertyRefs = entityKey . getPropertyRefs ( ) ; try { if ( keyPropertyRefs . size ( ) == 1 ) { return getKeyValueFromPropertyRef ( entityDataModel , entity , keyPropertyRefs . get ( 0 ) ) ; } else if ( keyPropertyRefs . size ( ) > 1 ) { List < String > processedKeys = new ArrayList < > ( ) ; for ( PropertyRef propertyRef : keyPropertyRefs ) { processedKeys . add ( String . format ( "%s=%s" , propertyRef . getPath ( ) , getKeyValueFromPropertyRef ( entityDataModel , entity , propertyRef ) ) ) ; } return processedKeys . stream ( ) . map ( Object :: toString ) . collect ( Collectors . joining ( "," ) ) ; } else { LOG . error ( "Not possible to retrieve entity key for entity " + entity ) ; throw new ODataEdmException ( "Entity key is not found for " + entity ) ; } } catch ( IllegalAccessException e ) { LOG . error ( "Not possible to retrieve entity key for entity " + entity ) ; throw new ODataEdmException ( "Not possible to retrieve entity key for entity " + entity , e ) ; } }
Get the entity key for a given entity by inspecting the Entity Data Model .
38,871
public static String pluralize ( String word ) { if ( word == null ) { throw new IllegalArgumentException ( ) ; } final String lowerCaseWord = word . toLowerCase ( ) ; if ( endsWithAny ( lowerCaseWord , "s" , "sh" , "o" ) ) { return word + "es" ; } if ( lowerCaseWord . endsWith ( "y" ) && ! lowerCaseWord . endsWith ( "ay" ) || endsWithAny ( lowerCaseWord , "ey" , "oy" , "uy" ) ) { return word . substring ( 0 , word . length ( ) - 1 ) + "ies" ; } else { return word + "s" ; } }
Get the plural for the given English word .
38,872
protected int scoreServiceDocument ( ODataRequestContext requestContext , MediaType requiredMediaType ) { if ( isServiceDocument ( requestContext . getUri ( ) ) ) { int scoreByFormat = scoreByFormat ( getFormatOption ( requestContext . getUri ( ) ) , requiredMediaType ) ; int scoreByMediaType = scoreByMediaType ( requestContext . getRequest ( ) . getAccept ( ) , requiredMediaType ) ; return max ( scoreByFormat , scoreByMediaType ) ; } else { return DEFAULT_SCORE ; } }
Calculate a score for a Service Document Renderer based on a given OData request context and required media type .
38,873
public void initialize ( ) throws ODataUnmarshallingException { LOG . info ( "Parser is initializing" ) ; try { JsonParser jsonParser = JSON_FACTORY . createParser ( inputJson ) ; while ( jsonParser . nextToken ( ) != JsonToken . END_OBJECT ) { String token = jsonParser . getCurrentName ( ) ; if ( token != null ) { if ( token . startsWith ( ODATA ) ) { processSpecialTags ( jsonParser ) ; } else if ( token . endsWith ( ODATA_BIND ) ) { processLinks ( jsonParser ) ; } else { process ( jsonParser ) ; } } } } catch ( IOException e ) { throw new ODataUnmarshallingException ( "It is unable to unmarshall" , e ) ; } }
Initialize processor automatically scanning the input JSON .
38,874
private void process ( JsonParser jsonParser ) throws IOException , ODataUnmarshallingException { if ( jsonParser . getCurrentToken ( ) == JsonToken . FIELD_NAME ) { LOG . info ( "Starting to parse {} token" , jsonParser . getCurrentName ( ) ) ; String key = jsonParser . getCurrentName ( ) ; jsonParser . nextToken ( ) ; JsonToken token = jsonParser . getCurrentToken ( ) ; if ( token == JsonToken . START_ARRAY ) { if ( JsonConstants . VALUE . equals ( key ) ) { throw new ODataUnmarshallingException ( "Feed is not supported" ) ; } values . put ( key , getCollectionValue ( jsonParser ) ) ; } else if ( token == JsonToken . START_OBJECT ) { values . put ( key , getEmbeddedObject ( jsonParser ) ) ; } else { if ( token . equals ( JsonToken . VALUE_NULL ) ) { values . put ( key , null ) ; } else { values . put ( key , jsonParser . getText ( ) ) ; } } } }
Process all things that do not contain special ODataTags .
38,875
private List < Object > getCollectionValue ( JsonParser jsonParser ) throws IOException { LOG . info ( "Start parsing {} array" , jsonParser . getCurrentName ( ) ) ; List < Object > list = new ArrayList < > ( ) ; while ( jsonParser . nextToken ( ) != JsonToken . END_ARRAY ) { if ( jsonParser . getCurrentToken ( ) == JsonToken . START_OBJECT ) { Object embedded = getEmbeddedObject ( jsonParser ) ; list . add ( embedded ) ; } if ( ! "}" . equals ( jsonParser . getText ( ) ) ) { list . add ( jsonParser . getText ( ) ) ; } else { LOG . info ( "Array is over." ) ; } } return list ; }
Parse the complex values .
38,876
private Object getEmbeddedObject ( JsonParser jsonParser ) throws IOException { LOG . info ( "Start parsing an embedded object." ) ; Map < String , Object > embeddedMap = new HashMap < > ( ) ; while ( jsonParser . nextToken ( ) != JsonToken . END_OBJECT ) { String key = jsonParser . getText ( ) ; jsonParser . nextToken ( ) ; JsonToken token = jsonParser . getCurrentToken ( ) ; if ( token == JsonToken . START_ARRAY ) { Object embeddedArray = getCollectionValue ( jsonParser ) ; embeddedMap . put ( key , embeddedArray ) ; } else if ( token == JsonToken . START_OBJECT ) { Object embeddedObject = getEmbeddedObject ( jsonParser ) ; embeddedMap . put ( key , embeddedObject ) ; } else { if ( token . equals ( JsonToken . VALUE_NULL ) ) { embeddedMap . put ( key , null ) ; } else { embeddedMap . put ( key , jsonParser . getText ( ) ) ; } } } return embeddedMap ; }
Process an embedded object .
38,877
private void processLinks ( JsonParser jsonParser ) throws IOException { LOG . info ( "@odata.bind tag found - start parsing" ) ; final String fullLinkFieldName = jsonParser . getText ( ) ; final String key = fullLinkFieldName . substring ( 0 , fullLinkFieldName . indexOf ( ODATA_BIND ) ) ; JsonToken token = jsonParser . nextToken ( ) ; if ( token != JsonToken . START_ARRAY ) { links . put ( key , processLink ( jsonParser ) ) ; } else { final List < String > linksList = new ArrayList < > ( ) ; while ( jsonParser . nextToken ( ) != JsonToken . END_ARRAY ) { linksList . add ( processLink ( jsonParser ) ) ; } this . links . put ( key , linksList ) ; } }
Process OData links .
38,878
private String processLink ( JsonParser jsonParser ) throws IOException { final String link = jsonParser . getText ( ) ; if ( link . contains ( SVC_EXTENSION ) ) { return link . substring ( link . indexOf ( SVC_EXTENSION ) + SVC_EXTENSION . length ( ) ) ; } return link ; }
Process OData link .
38,879
public void fillUpdatedObjectProperty ( Object entity , Object currentNode , StructuralProperty property , Field field , String node , Map < String , Object > map ) throws ODataException { for ( Map . Entry < String , Object > entry : ( ( Map < String , Object > ) currentNode ) . entrySet ( ) ) { if ( findAppropriateElement ( entity , property , field , node , map , entry ) ) { break ; } } }
Populates the embedded object property with the relevant field values .
38,880
public void fillUpdatedCollectionProperty ( Object entity , Object currentNode , StructuralProperty property , Field field , String node , Map < String , Object > map ) throws ODataException { Collection < Object > valueSet ; if ( field . getType ( ) . isAssignableFrom ( Set . class ) ) { valueSet = new HashSet < > ( ) ; } else { valueSet = new ArrayList < > ( ) ; } Object current = ( currentNode instanceof Map ) ? currentNode : map . get ( currentNode ) ; for ( Object subValue : ( Iterable ) ( ( Map ) current ) . get ( node ) ) { Object value = getFieldValueByType ( property . getElementTypeName ( ) , subValue , map , true ) ; if ( value != null ) { valueSet . add ( value ) ; } } setFieldValue ( field , entity , valueSet ) ; }
Populates the collection property with the relevant field values .
38,881
public void fillPrimitiveProperty ( Object entity , Set < String > keySet , StructuralProperty property , Field field , String node , Map < String , Object > map ) throws ODataException { for ( String target : keySet ) { if ( node . equalsIgnoreCase ( target ) ) { Object value = getFieldValueByType ( property . getTypeName ( ) , target , map , false ) ; if ( value != null ) { setFieldValue ( field , entity , value ) ; break ; } else { LOG . warn ( "There is no element with name '{}'" , node ) ; } } } }
Populates the primitive property of the entity with the relevant field value .
38,882
public void fillCollectionProperty ( Object entity , Set < String > keySet , StructuralProperty property , Field field , String node , Map < String , Object > map ) throws ODataException { for ( String target : keySet ) { if ( node . equalsIgnoreCase ( target ) ) { Iterable subValues = ( Iterable ) map . get ( target ) ; List < Object > valueList = new ArrayList < > ( ) ; for ( Object subValue : subValues ) { Object value = getFieldValueByType ( property . getElementTypeName ( ) , subValue , map , true ) ; if ( value != null ) { valueList . add ( value ) ; } } setFieldValue ( field , entity , valueList ) ; break ; } } }
Populates the collection property of the entity with field values .
38,883
protected Object getFieldValueByType ( String typeName , Object targetNode , Map < String , Object > map , boolean isExtracted ) throws ODataException { Object fieldValue = null ; LOG . debug ( "Type is {}" , typeName ) ; Type type = entityDataModel . getType ( typeName ) ; if ( type == null ) { throw new ODataUnmarshallingException ( "OData type not found: " + typeName ) ; } switch ( type . getMetaType ( ) ) { case ENUM : case PRIMITIVE : if ( isExtracted ) { fieldValue = getAppropriateFieldValue ( type . getJavaType ( ) , String . valueOf ( targetNode ) ) ; } else { if ( map . get ( targetNode ) != null ) { fieldValue = getAppropriateFieldValue ( type . getJavaType ( ) , String . valueOf ( map . get ( targetNode ) ) ) ; } } break ; case ENTITY : case COMPLEX : fieldValue = unmarshallEntityByName ( typeName , map , targetNode ) ; break ; default : LOG . warn ( "Unsupported type {}." , type . getMetaType ( ) . name ( ) ) ; throw new UnsupportedOperationException ( "Unsupported type: " + typeName ) ; } return fieldValue ; }
Gets the field value for the property type .
38,884
private Object unmarshallEntityByName ( String entityName , Map < String , Object > map , Object currentNode ) throws ODataException { LOG . debug ( "Entity '{}' created." , entityName ) ; if ( ! isNullOrEmpty ( entityName ) ) { Object entity = loadEntity ( entityName ) ; setEntityProperties ( entity , JsonParserUtils . getStructuredType ( entityName , entityDataModel ) , map , currentNode ) ; LOG . debug ( "Entity '{}' properties mapped successfully." , entityName ) ; return entity ; } else { throw new ODataUnmarshallingException ( "Unmarshalling Entity name should be null !!!!..." ) ; } }
Unmarsall a named entity .
38,885
public Object loadEntity ( String entityName ) throws ODataUnmarshallingException { Object entity = null ; if ( entityName != null ) { try { StructuredType entityType = JsonParserUtils . getStructuredType ( entityName , entityDataModel ) ; if ( entityType != null ) { entity = entityType . getJavaType ( ) . newInstance ( ) ; } else { LOG . warn ( "Given entity '{}' is not found in entity data model" , entityName ) ; throw new ODataUnmarshallingException ( "Couldn't initiate entity because given entity [" + entityName + "] is not found in entity data model." ) ; } } catch ( InstantiationException | IllegalAccessException e ) { throw new ODataUnmarshallingException ( "Cannot instantiate entity" , e ) ; } } return entity ; }
Creates the an entity based on its name .
38,886
public void setEntityProperties ( Object entity , StructuredType entityType , Map < String , Object > map , Object currentNode ) throws ODataException { Set < String > keySet = map . keySet ( ) ; for ( StructuralProperty property : getAllProperties ( entityType , entityDataModel ) ) { Field field = property . getJavaField ( ) ; String node = property . getName ( ) ; LOG . debug ( "Property Name is {}" , node ) ; if ( property . isCollection ( ) ) { if ( currentNode == null ) { fillCollectionProperty ( entity , keySet , property , field , node , map ) ; } else { fillUpdatedCollectionProperty ( entity , currentNode , property , field , node , map ) ; } } else { if ( currentNode == null ) { fillPrimitiveProperty ( entity , keySet , property , field , node , map ) ; } else { if ( currentNode instanceof String ) { fillEntryFeed ( entity , currentNode , property , field , node , map ) ; } else { fillUpdatedObjectProperty ( entity , currentNode , property , field , node , map ) ; } } } } }
Sets the given entity with structural properties from the fields .
38,887
public ProcessorResult handleWrite ( Object entity ) throws ODataException { if ( ODataUriUtil . isRefPathUri ( getoDataUri ( ) ) ) { return processLink ( ( ODataLink ) entity ) ; } else { if ( entity != null ) { throw new ODataBadRequestException ( "The body of a DELETE request must be empty." ) ; } return processEntity ( ) ; } }
This method delete entity .
38,888
private ProcessorResult processEntity ( ) throws ODataException { TargetType targetType = getTargetType ( ) ; if ( ! targetType . isCollection ( ) ) { Option < String > singletonName = ODataUriUtil . getSingletonName ( getoDataUri ( ) ) ; if ( singletonName . isDefined ( ) ) { throw new ODataBadRequestException ( "The URI refers to the singleton '" + singletonName . get ( ) + "'. Singletons cannot be deleted." ) ; } Type type = getEntityDataModel ( ) . getType ( targetType . typeName ( ) ) ; DataSource dataSource = getDataSource ( type . getFullyQualifiedName ( ) ) ; log . debug ( "Data source found for entity type '{}'" , type . getFullyQualifiedName ( ) ) ; dataSource . delete ( getoDataUri ( ) , getEntityDataModel ( ) ) ; return new ProcessorResult ( NO_CONTENT ) ; } else { throw new ODataBadRequestException ( "The URI for a DELETE request should refer to the single entity " + "to be deleted, not to a collection of entities." ) ; } }
This method finds correct data source based on target type and executes delete operation on data source .
38,889
public String writeRawJson ( final String json , final String contextUrl ) throws ODataRenderException { this . contextURL = checkNotNull ( contextUrl ) ; try { final ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; jsonGenerator = JSON_FACTORY . createGenerator ( stream , JsonEncoding . UTF8 ) ; jsonGenerator . writeRaw ( json ) ; jsonGenerator . close ( ) ; return stream . toString ( StandardCharsets . UTF_8 . name ( ) ) ; } catch ( final IOException e ) { throw new ODataRenderException ( "Not possible to write raw json to stream JSON: " , e ) ; } }
Writes raw json to the JSON stream .
38,890
private String writeJson ( Object data , Map < String , Object > meta ) throws IOException , NoSuchFieldException , IllegalAccessException , ODataEdmException , ODataRenderException { ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; jsonGenerator = JSON_FACTORY . createGenerator ( stream , JsonEncoding . UTF8 ) ; jsonGenerator . writeStartObject ( ) ; entitySet = ( data instanceof List ) ? getEntitySet ( ( List < ? > ) data ) : getEntitySet ( data ) ; jsonGenerator . writeStringField ( CONTEXT , contextURL ) ; if ( hasCountOption ( odataUri ) && data instanceof List && meta != null && meta . containsKey ( "count" ) ) { long count ; Object countObj = meta . get ( "count" ) ; if ( countObj instanceof Integer ) { count = ( ( Integer ) countObj ) . longValue ( ) ; } else { count = ( long ) countObj ; } jsonGenerator . writeNumberField ( COUNT , count ) ; } if ( ! ( data instanceof List ) ) { if ( entitySet != null ) { jsonGenerator . writeStringField ( ID , String . format ( "%s(%s)" , getEntityName ( entityDataModel , data ) , formatEntityKey ( entityDataModel , data ) ) ) ; } else { jsonGenerator . writeStringField ( ID , String . format ( "%s" , getEntityName ( entityDataModel , data ) ) ) ; } } if ( data instanceof List ) { marshallEntities ( ( List < ? > ) data ) ; } else { marshall ( data , this . entityDataModel . getType ( data . getClass ( ) ) ) ; } jsonGenerator . writeEndObject ( ) ; jsonGenerator . close ( ) ; return stream . toString ( StandardCharsets . UTF_8 . name ( ) ) ; }
Write the given data to the JSON stream . The data to write will be either a single entity or a feed depending on whether it is a single object or list .
38,891
public Action build ( Class < ? > cls ) { EdmAction edmAction = cls . getAnnotation ( EdmAction . class ) ; EdmReturnType edmReturnType = cls . getAnnotation ( EdmReturnType . class ) ; 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 ActionImpl . Builder ( ) . setName ( getTypeName ( edmAction , cls ) ) . setNamespace ( getNamespace ( edmAction , cls ) ) . setBound ( edmAction . isBound ( ) ) . setEntitySetPath ( edmAction . entitySetPath ( ) ) . setParameters ( parameters ) . setReturnType ( edmReturnType . type ( ) ) . setJavaClass ( cls ) . build ( ) ; }
Builds an action instance from given class .
38,892
protected boolean isEntityQuery ( ODataUri uri , EntityDataModel entityDataModel ) { return getTargetType ( uri , entityDataModel ) . map ( t -> t . getMetaType ( ) == MetaType . ENTITY ) . orElse ( false ) ; }
Check if the parsed OData URI is a query and it results in an entity or a collection of entities .
38,893
protected String buildContextURL ( ODataRequestContext requestContext , Object data ) throws ODataRenderException { ODataUri oDataUri = requestContext . getUri ( ) ; if ( ODataUriUtil . isActionCallUri ( oDataUri ) || ODataUriUtil . isFunctionCallUri ( oDataUri ) ) { return buildContextUrlFromOperationCall ( oDataUri , requestContext . getEntityDataModel ( ) , isListOrStream ( data ) ) ; } Option < String > contextURL ; if ( isWriteOperation ( requestContext ) ) { contextURL = getContextUrlWriteOperation ( oDataUri ) ; } else { contextURL = getContextUrl ( oDataUri ) ; } checkContextURL ( requestContext , contextURL ) ; return contextURL . get ( ) ; }
Build the Context URL from a given OData request context .
38,894
protected void checkContextURL ( ODataRequestContext requestContext , Option < String > contextURL ) throws ODataRenderException { if ( ! contextURL . isDefined ( ) ) { throw new ODataRenderException ( String . format ( "Not possible to create context URL for request %s" , requestContext ) ) ; } }
Check whether the given Context URL is defined .
38,895
public ProcessorResult handleWrite ( Object action ) throws ODataException { Operation operation ; if ( action instanceof Operation ) { operation = ( Operation ) action ; Object data = operation . doOperation ( getODataRequestContext ( ) , getDataSourceFactory ( ) ) ; if ( data == null ) { return new ProcessorResult ( ODataResponse . Status . NO_CONTENT ) ; } else { return new ProcessorResult ( ODataResponse . Status . CREATED , QueryResult . from ( data ) ) ; } } else { throw new ODataBadRequestException ( "Incorrect operation instance" ) ; } }
Handles action call and returns result in case when action returns it .
38,896
public String getPropertyAsString ( Object data ) throws ODataException { LOG . trace ( "GetPropertyAsString invoked with {}" , data ) ; if ( data != null ) { return makePropertyString ( data ) ; } else { return generateNullPropertyString ( ) ; } }
This is main method to get property as string .
38,897
public String buildServiceDocument ( ) throws ODataRenderException { LOG . info ( "Building service(root) document" ) ; try ( ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( BUFFER_SIZE ) ) { XMLStreamWriter writer = startServiceDocument ( outputStream ) ; writeEntitySets ( writer ) ; writeSingleton ( writer ) ; endServiceDocument ( writer ) ; LOG . info ( "Successfully built service document" ) ; return outputStream . toString ( ) ; } catch ( XMLStreamException | IOException e ) { String msg = "Something went wrong when writing service document." ; LOG . error ( msg , e ) ; throw new ODataRenderException ( msg , e ) ; } }
This is main method which generates service document .
38,898
private void writeEntitySets ( XMLStreamWriter writer ) throws XMLStreamException , ODataRenderException { List < EntitySet > entitySets = getEntityContainer ( ) . getEntitySets ( ) ; LOG . debug ( "Number of entity sets to be written in service document are {}" , entitySets . size ( ) ) ; for ( EntitySet entitySet : entitySets ) { if ( entitySet . isIncludedInServiceDocument ( ) ) { writeElement ( writer , null , SERVICE_COLLECTION , null , entitySet . getName ( ) , entitySet . getName ( ) ) ; } } }
This writes all entity sets in entity data model as collection of elements .
38,899
private XMLStreamWriter startServiceDocument ( ByteArrayOutputStream outputStream ) throws XMLStreamException , ODataRenderException { XMLStreamWriter writer = XMLWriterUtil . startDocument ( outputStream , null , SERVICE , ODATA_SERVICE_NS ) ; writer . writeNamespace ( ATOM , ATOM_NS ) ; writer . writeNamespace ( METADATA , ODATA_METADATA_NS ) ; writer . writeNamespace ( SERVICE_BASE , oDataUri . serviceRoot ( ) ) ; writer . writeNamespace ( ODATA_CONTEXT , getContextURL ( oDataUri , entityDataModel ) ) ; writer . writeStartElement ( ODATA_SERVICE_NS , WORKSPACE ) ; writeTitle ( writer , getEntityContainer ( ) . getName ( ) ) ; return writer ; }
Starts service document with correct attributes and also writes workspace title elements .