idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
35,900 | private String getMime ( String name , String delimiter ) { if ( StringUtils . hasText ( name ) ) { return name . substring ( name . lastIndexOf ( delimiter ) , name . length ( ) ) ; } return null ; } | Method get the mime value from the given file name |
35,901 | public void setCompressedData ( byte [ ] compressedData ) { if ( compressedData != null ) { this . compressedData = Arrays . copyOf ( compressedData , compressedData . length ) ; } } | Sets compressed data |
35,902 | public BankAccount create ( BankAccount bankAccount , String customerId ) throws BaseException { logger . debug ( "Enter BankAccountService::create" ) ; if ( StringUtils . isBlank ( customerId ) ) { logger . error ( "IllegalArgumentException {}" , customerId ) ; throw new IllegalArgumentException ( "customerId cannot be empty or null" ) ; } String apiUrl = requestContext . getBaseUrl ( ) . replaceAll ( "payments" , "customers" ) + "{id}/bank-accounts" . replaceAll ( "\\{format\\}" , "json" ) . replaceAll ( "\\{" + "id" + "\\}" , customerId . toString ( ) ) ; logger . info ( "apiUrl - " + apiUrl ) ; TypeReference < BankAccount > typeReference = new TypeReference < BankAccount > ( ) { } ; Request request = new Request . RequestBuilder ( MethodType . POST , apiUrl ) . requestObject ( bankAccount ) . typeReference ( typeReference ) . context ( requestContext ) . build ( ) ; Response response = sendRequest ( request ) ; BankAccount bankAccountResponse = ( BankAccount ) response . getResponseObject ( ) ; prepareResponse ( request , response , bankAccountResponse ) ; return bankAccountResponse ; } | Method to create BankAccount for a given customer |
35,903 | @ SuppressWarnings ( "unchecked" ) public QueryResponse getAllBankAccounts ( String customerId , int count ) throws BaseException { logger . debug ( "Enter BankAccountService::getAllBankAccounts" ) ; if ( StringUtils . isBlank ( customerId ) ) { logger . error ( "IllegalArgumentException {}" , customerId ) ; throw new IllegalArgumentException ( "customerId cannot be empty or null" ) ; } String apiUrl = requestContext . getBaseUrl ( ) . replaceAll ( "payments" , "customers" ) + "{id}/bank-accounts" . replaceAll ( "\\{format\\}" , "json" ) . replaceAll ( "\\{" + "id" + "\\}" , customerId . toString ( ) ) ; if ( count > 0 ) { apiUrl = apiUrl + "?count=" + count ; } logger . info ( "apiUrl - " + apiUrl ) ; TypeReference < List < BankAccount > > typeReference = new TypeReference < List < BankAccount > > ( ) { } ; Request request = new Request . RequestBuilder ( MethodType . GET , apiUrl ) . typeReference ( typeReference ) . context ( requestContext ) . build ( ) ; Response response = sendRequest ( request ) ; List < BankAccount > bankAccounts = ( List < BankAccount > ) response . getResponseObject ( ) ; QueryResponse queryResponse = new QueryResponse . Builder ( ) . bankAccounts ( bankAccounts ) . build ( ) ; prepareResponse ( request , response , queryResponse ) ; return queryResponse ; } | Method to Get All BankAccounts for a given customer specifying the count of records to be returned |
35,904 | private String extractEntity ( Object obj ) { String name = obj . getClass ( ) . getSimpleName ( ) ; String [ ] extracted = name . split ( "\\$\\$" ) ; if ( extracted . length == NUM_3 ) { return extracted [ 0 ] ; } return null ; } | Method to extract the entity |
35,905 | protected String extractPropertyName ( Method method ) { String name = method . getName ( ) ; name = name . startsWith ( "is" ) ? name . substring ( NUM_2 ) : name . substring ( NUM_3 ) ; return name ; } | extract the name of property from method called . |
35,906 | public Object getObject ( Type type ) throws FMSException { Object obj = null ; if ( type instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) type ; String typeString = pt . getActualTypeArguments ( ) [ 0 ] . toString ( ) . split ( " " ) [ 1 ] ; try { obj = Class . forName ( typeString ) . newInstance ( ) ; } catch ( Exception e ) { throw new FMSException ( e ) ; } } return obj ; } | Method to get the object for the given type |
35,907 | public List < EntitlementsResponse . Entitlement > getEntitlement ( ) { if ( entitlement == null ) { entitlement = new ArrayList < EntitlementsResponse . Entitlement > ( ) ; } return this . entitlement ; } | Gets the value of the entitlement property . |
35,908 | public void prepareResponse ( Request request , Response response , Entity entity ) { entity . setIntuit_tid ( response . getIntuit_tid ( ) ) ; entity . setRequestId ( request . getContext ( ) . getRequestId ( ) ) ; } | Sets additional attributes to the entity |
35,909 | public Expression < Boolean > eq ( Boolean value ) { String valueString = value . toString ( ) ; return new Expression < Boolean > ( this , Operation . eq , valueString ) ; } | Method to construct the equals expression for boolean |
35,910 | public Expression < Boolean > neq ( Boolean value ) { String valueString = value . toString ( ) ; return new Expression < Boolean > ( this , Operation . neq , valueString ) ; } | Method to construct the not equals expression for boolean |
35,911 | public Expression < Boolean > in ( Boolean [ ] value ) { String listBooleanString = "" ; Boolean firstNumber = true ; for ( Boolean v : value ) { if ( firstNumber ) { listBooleanString = listBooleanString . concat ( "(" ) . concat ( v . toString ( ) ) ; firstNumber = false ; } else { listBooleanString = listBooleanString . concat ( ", " ) . concat ( v . toString ( ) ) ; } } listBooleanString = listBooleanString . concat ( ")" ) ; return new Expression < Boolean > ( this , Operation . in , listBooleanString ) ; } | Method to construct the in expression for boolean |
35,912 | public List < JAXBElement < ? extends IntuitEntity > > getIntuitObject ( ) { if ( intuitObject == null ) { intuitObject = new ArrayList < JAXBElement < ? extends IntuitEntity > > ( ) ; } return this . intuitObject ; } | Any IntuitEntity derived object like Customer Invoice can be part of response Gets the value of the intuitObject property . |
35,913 | private static PropertyHelper init ( ) { propertHelper = new PropertyHelper ( ) ; try { ResourceBundle bundle = ResourceBundle . getBundle ( "ippdevkit" ) ; propertHelper . setVersion ( bundle . getString ( "version" ) ) ; propertHelper . setRequestSource ( bundle . getString ( "request.source" ) ) ; propertHelper . setRequestSourceHeader ( bundle . getString ( "request.source.header" ) ) ; } catch ( MissingResourceException e ) { LOG . debug ( "no value found for key" , e ) ; } return propertHelper ; } | Method to init the PropertyHelper by loading the ippdevkit . properties file |
35,914 | @ SuppressWarnings ( "unchecked" ) private < T extends IEntity > List < T > getEntities ( QueryResponse queryResponse ) { List < T > entityList = new ArrayList < T > ( ) ; List < JAXBElement < ? extends IntuitEntity > > intuitObjectsList = queryResponse . getIntuitObject ( ) ; if ( intuitObjectsList != null && ! intuitObjectsList . isEmpty ( ) ) { Iterator < JAXBElement < ? extends IntuitEntity > > itr = intuitObjectsList . iterator ( ) ; while ( itr . hasNext ( ) ) { JAXBElement < ? extends IntuitEntity > intuitObject = itr . next ( ) ; entityList . add ( ( T ) intuitObject . getValue ( ) ) ; } } return entityList ; } | Method to parse the QueryResponse and create the entity list |
35,915 | private boolean isDownload ( String action ) { if ( StringUtils . hasText ( action ) && action . equals ( OperationType . DOWNLOAD . toString ( ) ) ) { return true ; } return false ; } | Method to validate if the given action is download feature |
35,916 | private InputStream getDownloadedFile ( String response ) throws FMSException { if ( response != null ) { try { URL url = new URL ( response ) ; return url . openStream ( ) ; } catch ( Exception e ) { throw new FMSException ( "Exception while downloading the file from URL." , e ) ; } } return null ; } | Method to get the input stream from the download URL returned from service |
35,917 | private void executeRequestInterceptors ( final IntuitMessage intuitMessage ) throws FMSException { Iterator < Interceptor > itr = requestInterceptors . iterator ( ) ; while ( itr . hasNext ( ) ) { Interceptor interceptor = itr . next ( ) ; interceptor . execute ( intuitMessage ) ; } } | Method to execute only request interceptors which are added to requestInterceptors list |
35,918 | private void executeResponseInterceptors ( final IntuitMessage intuitMessage ) throws FMSException { Iterator < Interceptor > itr = responseInterceptors . iterator ( ) ; while ( itr . hasNext ( ) ) { Interceptor interceptor = itr . next ( ) ; interceptor . execute ( intuitMessage ) ; } } | Method to execute only response interceptors which are added to the responseInterceptors list |
35,919 | protected void invokeFeature ( String featureSwitch , Feature feature ) { if ( Config . getBooleanProperty ( featureSwitch , true ) ) { feature . execute ( ) ; } } | Executes feature if switch setting is on |
35,920 | protected void updateBigDecimalScale ( IntuitEntity intuitType ) { Feature feature = new Feature ( ) { private IntuitEntity obj ; public < T extends IntuitEntity > void set ( T object ) { obj = object ; } public void execute ( ) { ( new BigDecimalScaleUpdater ( ) ) . execute ( obj ) ; } } ; feature . set ( intuitType ) ; invokeFeature ( Config . BIGDECIMAL_SCALE_SHIFT , feature ) ; } | Updates instances of BigDecimal with new scale in intuitEntity |
35,921 | private void prepareDataServiceRequest ( IntuitMessage intuitMessage , RequestElements requestElements , Map < String , String > requestParameters , String action ) throws FMSException { requestParameters . put ( RequestElements . REQ_PARAM_RESOURCE_URL , getUri ( intuitMessage . isPlatformService ( ) , action , requestElements . getContext ( ) , requestParameters , intuitMessage . isEntitlementService ( ) ) ) ; Map < String , String > requestHeaders = requestElements . getRequestHeaders ( ) ; if ( isUpload ( action ) ) { prepareUploadParams ( requestElements ) ; } else if ( StringUtils . hasText ( requestElements . getPostString ( ) ) ) { requestHeaders . put ( RequestElements . HEADER_PARAM_CONTENT_TYPE , ContentTypes . TEXT . toString ( ) ) ; } else { String serializeFormat = getSerializationRequestFormat ( ) ; if ( StringUtils . hasText ( serializeFormat ) && ! isSendEmail ( requestParameters ) ) { requestHeaders . put ( RequestElements . HEADER_PARAM_CONTENT_TYPE , ContentTypes . getContentType ( serializeFormat ) ) ; } else if ( StringUtils . hasText ( serializeFormat ) && isSendEmail ( requestParameters ) ) { requestHeaders . put ( RequestElements . HEADER_PARAM_CONTENT_TYPE , ContentTypes . OCTECT_STREAM . toString ( ) ) ; } } String compressFormat = Config . getProperty ( Config . COMPRESSION_REQUEST_FORMAT ) ; if ( StringUtils . hasText ( compressFormat ) && CompressorFactory . isValidCompressFormat ( compressFormat ) ) { requestHeaders . put ( RequestElements . HEADER_PARAM_CONTENT_ENCODING , compressFormat ) ; } setupAcceptEncoding ( requestHeaders ) ; setupAcceptHeader ( action , requestHeaders , requestParameters ) ; UUID trackingID = requestElements . getContext ( ) . getTrackingID ( ) ; if ( ! ( trackingID == null ) ) { requestHeaders . put ( RequestElements . HEADER_INTUIT_TID , trackingID . toString ( ) ) ; } } | Method to prepare request parameters for data service |
35,922 | private void setupAcceptEncoding ( Map < String , String > requestHeaders ) { String acceptCompressionFormat = Config . getProperty ( Config . COMPRESSION_RESPONSE_FORMAT ) ; if ( StringUtils . hasText ( acceptCompressionFormat ) ) { requestHeaders . put ( RequestElements . HEADER_PARAM_ACCEPT_ENCODING , acceptCompressionFormat ) ; } } | Setup accept encoding header from configuration |
35,923 | private void setupAcceptHeader ( String action , Map < String , String > requestHeaders , Map < String , String > requestParameters ) { String serializeAcceptFormat = getSerializationResponseFormat ( ) ; if ( StringUtils . hasText ( serializeAcceptFormat ) && ! isDownload ( action ) && ! isDownloadPDF ( requestParameters ) ) { requestHeaders . put ( RequestElements . HEADER_PARAM_ACCEPT , ContentTypes . getContentType ( serializeAcceptFormat ) ) ; } if ( isDownloadPDF ( requestParameters ) ) { requestHeaders . put ( RequestElements . HEADER_PARAM_ACCEPT , ContentTypes . getContentType ( requestParameters . get ( RequestElements . REQ_PARAM_ENTITY_SELECTOR ) ) ) ; } } | Setup accept header depends from the semantic of the request |
35,924 | private < T extends IEntity > String getEntityName ( T entity ) { if ( entity != null ) { return entity . getClass ( ) . getSimpleName ( ) . toLowerCase ( ) ; } return null ; } | Method to get the entity name from the given entity object |
35,925 | private < T extends IEntity > String getUri ( Boolean platformService , String action , Context context , Map < String , String > requestParameters , Boolean entitlementService ) throws FMSException { String uri = null ; if ( ! platformService ) { ServiceType serviceType = context . getIntuitServiceType ( ) ; if ( entitlementService ) { uri = prepareEntitlementUri ( context ) ; } else if ( ServiceType . QBO == serviceType ) { uri = prepareQBOUri ( action , context , requestParameters ) ; } else if ( ServiceType . QBOPremier == serviceType ) { uri = prepareQBOPremierUri ( action , context , requestParameters ) ; } else { throw new FMSException ( "SDK doesn't support for the service type : " + serviceType ) ; } } else { uri = prepareIPSUri ( action , context ) ; } return uri ; } | Method to construct the URI |
35,926 | protected String getBaseUrl ( String url ) { if ( url . endsWith ( "/" ) ) { return url . substring ( 0 , url . length ( ) - 1 ) ; } else { return url ; } } | Return QBO base configuration from config file |
35,927 | private < T extends IEntity > String prepareQBOUri ( String entityName , Context context , Map < String , String > requestParameters ) throws FMSException { StringBuilder uri = new StringBuilder ( ) ; if ( entityName . equalsIgnoreCase ( "Taxservice" ) ) { entityName = entityName + "/" + "taxcode" ; } uri . append ( getBaseUrl ( Config . getProperty ( Config . BASE_URL_QBO ) ) ) . append ( "/" ) . append ( context . getRealmID ( ) ) . append ( "/" ) . append ( entityName ) ; addEntityID ( requestParameters , uri ) ; addEntitySelector ( requestParameters , uri ) ; addParentID ( requestParameters , uri ) ; uri . append ( "?" ) . append ( buildRequestParams ( requestParameters ) ) ; uri . append ( "requestid" ) . append ( "=" ) . append ( context . getRequestID ( ) ) . append ( "&" ) ; context . setRequestID ( null ) ; if ( context . getMinorVersion ( ) == null ) { context . setMinorVersion ( "37" ) ; } uri . append ( "minorversion" ) . append ( "=" ) . append ( context . getMinorVersion ( ) ) . append ( "&" ) ; if ( context . getIncludeParam ( ) != null ) { int includeval = context . getIncludeParam ( ) . size ( ) ; String includeParam = "" ; if ( includeval > 0 ) { for ( int i = 0 ; i < includeval ; i ++ ) { includeParam = includeParam + context . getIncludeParam ( ) . get ( i ) + "," ; } uri . append ( "include" ) . append ( "=" ) . append ( includeParam . substring ( 0 , includeParam . length ( ) - 1 ) ) . append ( "&" ) ; } } return uri . toString ( ) ; } | Method to construct the QBO URI |
35,928 | private void addEntityID ( Map < String , String > requestParameters , StringBuilder uri ) { if ( StringUtils . hasText ( requestParameters . get ( RequestElements . REQ_PARAM_ENTITY_ID ) ) ) { uri . append ( "/" ) . append ( requestParameters . get ( RequestElements . REQ_PARAM_ENTITY_ID ) ) ; } } | adding the entity id in the URI which is required for READ operation |
35,929 | private void addEntitySelector ( Map < String , String > requestParameters , StringBuilder uri ) { if ( StringUtils . hasText ( requestParameters . get ( RequestElements . REQ_PARAM_ENTITY_SELECTOR ) ) ) { uri . append ( "/" ) . append ( requestParameters . get ( RequestElements . REQ_PARAM_ENTITY_SELECTOR ) ) ; } } | adding additional selector in the URI which is required for READ operation Main purpose is to select or modify requested resource with well - defined keyword |
35,930 | private < T extends IEntity > String prepareQBOPremierUri ( String entityName , Context context , Map < String , String > requestParameters ) throws FMSException { StringBuilder uri = new StringBuilder ( ) ; uri . append ( Config . getProperty ( "BASE_URL_QBO_OLB" ) ) . append ( "/" ) . append ( context . getRealmID ( ) ) . append ( "/" ) . append ( entityName ) ; addEntityID ( requestParameters , uri ) ; addEntitySelector ( requestParameters , uri ) ; uri . append ( "?" ) . append ( buildRequestParams ( requestParameters ) ) ; uri . append ( "requestid" ) . append ( "=" ) . append ( context . getRequestID ( ) ) . append ( "&" ) ; context . setRequestID ( null ) ; if ( context . getMinorVersion ( ) != null ) { uri . append ( "minorversion" ) . append ( "=" ) . append ( context . getMinorVersion ( ) ) . append ( "&" ) ; } return uri . toString ( ) ; } | Method to construct the OLB QBO URI |
35,931 | private String prepareIPSUri ( String action , Context context ) throws FMSException { StringBuilder uri = new StringBuilder ( ) ; uri . append ( Config . getProperty ( Config . BASE_URL_PLATFORMSERVICE ) ) . append ( "/" ) . append ( context . getAppDBID ( ) ) . append ( "?act=" ) . append ( action ) . append ( "&token=" ) . append ( context . getAppToken ( ) ) ; return uri . toString ( ) ; } | Method to construct the IPS URI |
35,932 | private String buildRequestParams ( Map < String , String > requestParameters ) throws FMSException { StringBuilder reqParams = new StringBuilder ( ) ; Set < String > keySet = requestParameters . keySet ( ) ; Iterator < String > keySetIterator = keySet . iterator ( ) ; while ( keySetIterator . hasNext ( ) ) { String key = keySetIterator . next ( ) ; String value = requestParameters . get ( key ) ; if ( isKeyValueExpected ( key ) ) { if ( value == "updateAccountOnTxns" ) { reqParams . append ( "include" ) . append ( "=" ) . append ( "updateaccountontxns" ) . append ( "&" ) ; } else if ( value == "donotUpdateAccountOnTxns" ) { reqParams . append ( "include" ) . append ( "=" ) . append ( "donotupdateaccountontxns" ) . append ( "&" ) ; } else { reqParams . append ( key ) . append ( "=" ) . append ( value ) . append ( "&" ) ; } } else if ( key . equals ( RequestElements . REQ_PARAM_QUERY ) || key . equals ( RequestElements . REQ_PARAM_ENTITIES ) ) { try { String encodedQuery = URLEncoder . encode ( value , "UTF-8" ) ; reqParams . append ( key ) . append ( "=" ) . append ( encodedQuery ) . append ( "&" ) ; } catch ( UnsupportedEncodingException e ) { throw new FMSException ( "UnsupportedEncodingException" , e ) ; } } } return reqParams . toString ( ) ; } | Method to build the request params which are to be added in the URI |
35,933 | private void prepareUploadParams ( RequestElements requestElements ) { Map < String , String > requestHeaders = requestElements . getRequestHeaders ( ) ; UploadRequestElements uploadRequestElements = requestElements . getUploadRequestElements ( ) ; String boundaryId = uploadRequestElements . getBoundaryId ( ) ; String formMetadataName = "file_metadata_" + boundaryId . substring ( 0 , 5 ) + "_" + uploadRequestElements . getElementsId ( ) ; String formContentName = "file_content_" + boundaryId . substring ( 0 , 5 ) + "_" + uploadRequestElements . getElementsId ( ) ; String contentType = ContentTypes . getContentType ( getSerializationRequestFormat ( ) ) ; Attachable attachable = ( Attachable ) requestElements . getEntity ( ) ; String fileName = ( attachable . getFileName ( ) != null ) ? "; filename=\"" + attachable . getFileName ( ) + "\"" : "" ; String fileType = ( attachable . getContentType ( ) != null ) ? "Content-Type: " + attachable . getContentType ( ) + "\r\n" : "" ; String entityBoundary = String . format ( UploadRequestElements . TEMPLATE_ENTITY_BOUNDARY , boundaryId , formMetadataName , contentType ) ; String contentBoundary = String . format ( UploadRequestElements . TEMPLATE_CONTENT_BOUNDARY , boundaryId , formContentName , fileName , fileType ) ; requestHeaders . put ( RequestElements . HEADER_PARAM_CONTENT_TYPE , ContentTypes . MULTIPART_FORMDATA . toString ( ) + "; boundary=" + boundaryId ) ; uploadRequestElements . setBoundaryForEntity ( entityBoundary ) ; uploadRequestElements . setBoundaryForContent ( contentBoundary ) ; } | Method to prepare the request params for upload functionality |
35,934 | private boolean isDownloadPDF ( Map < String , String > map ) { return StringUtils . hasText ( map . get ( RequestElements . REQ_PARAM_ENTITY_SELECTOR ) ) && map . get ( RequestElements . REQ_PARAM_ENTITY_SELECTOR ) . equalsIgnoreCase ( ContentTypes . PDF . name ( ) ) ; } | Method returns true if this request expects PDF as response |
35,935 | private boolean isSendEmail ( Map < String , String > map ) { return StringUtils . hasText ( map . get ( RequestElements . REQ_PARAM_ENTITY_SELECTOR ) ) && map . get ( RequestElements . REQ_PARAM_ENTITY_SELECTOR ) . equalsIgnoreCase ( RequestElements . PARAM_SEND_SELECTOR ) ; } | Method returns true if this request should be send as email |
35,936 | private boolean isUpload ( String action ) { if ( StringUtils . hasText ( action ) && action . equals ( OperationType . UPLOAD . toString ( ) ) ) { return true ; } return false ; } | Method to validate if the given action is upload feature |
35,937 | private SyncError getSyncError ( JsonNode jsonNode ) throws IOException { ObjectMapper mapper = new ObjectMapper ( ) ; SimpleModule simpleModule = new SimpleModule ( "SyncErrorDeserializer" , new Version ( 1 , 0 , 0 , null ) ) ; simpleModule . addDeserializer ( SyncError . class , new SyncErrorDeserializer ( ) ) ; mapper . registerModule ( simpleModule ) ; return mapper . treeToValue ( jsonNode , SyncError . class ) ; } | Method to deserialize the SyncError object |
35,938 | public Expression < Enum < ? > > eq ( Enum < ? > value ) { String valueString = "'" + EnumPath . getValue ( value ) + "'" ; return new Expression < Enum < ? > > ( this , Operation . eq , valueString ) ; } | Method to construct the equals expression for enum |
35,939 | private static String getValue ( Enum < ? > value ) { try { Method m = value . getClass ( ) . getDeclaredMethod ( "value" ) ; return ( String ) m . invoke ( value ) ; } catch ( NoSuchMethodException ex ) { } catch ( IllegalAccessException ex ) { } catch ( InvocationTargetException ex ) { } return value . toString ( ) ; } | Intuit data enumerations have a value property which should be used in queries instead of enum names . |
35,940 | public Token createToken ( Token token ) throws BaseException { logger . debug ( "Enter TokenService::createToken" ) ; String apiUrl = requestContext . getBaseUrl ( ) + "tokens" ; logger . info ( "apiUrl - " + apiUrl ) ; TypeReference < Token > typeReference = new TypeReference < Token > ( ) { } ; Request request = new Request . RequestBuilder ( MethodType . POST , apiUrl ) . ignoreAuthHeader ( true ) . requestObject ( token ) . typeReference ( typeReference ) . context ( requestContext ) . build ( ) ; Response response = sendRequest ( request ) ; Token tokenResponse = ( Token ) response . getResponseObject ( ) ; prepareResponse ( request , response , tokenResponse ) ; return tokenResponse ; } | Method to create BankAccount |
35,941 | private String getCDCQueryJson ( CDCQuery cdcQuery ) throws SerializationException { ObjectMapper mapper = getObjectMapper ( ) ; String json = null ; try { json = mapper . writeValueAsString ( cdcQuery ) ; } catch ( Exception e ) { throw new SerializationException ( e ) ; } return json ; } | Method to get the Json string for CDCQuery object |
35,942 | private ObjectMapper getObjectMapper ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; AnnotationIntrospector primary = new JacksonAnnotationIntrospector ( ) ; AnnotationIntrospector secondary = new JaxbAnnotationIntrospector ( ) ; AnnotationIntrospector pair = new AnnotationIntrospectorPair ( primary , secondary ) ; mapper . setAnnotationIntrospector ( pair ) ; mapper . setSerializationInclusion ( Include . NON_NULL ) ; return mapper ; } | Method to get the Jackson object mapper |
35,943 | public OAuthMigrationResponse migrate ( ) throws ConnectionException { logger . debug ( "Enter OAuthMigrationClient::migrate" ) ; try { HttpRequestClient client = new HttpRequestClient ( oAuthMigrationRequest . getOauth2config ( ) . getProxyConfig ( ) ) ; String requestjson = new JSONObject ( ) . put ( "scope" , getScopeValue ( oAuthMigrationRequest . getScope ( ) ) ) . put ( "redirect_uri" , getRedirectUrl ( ) ) . put ( "client_id" , oAuthMigrationRequest . getOauth2config ( ) . getClientId ( ) ) . put ( "client_secret" , oAuthMigrationRequest . getOauth2config ( ) . getClientSecret ( ) ) . toString ( ) ; Request request = new Request . RequestBuilder ( MethodType . GET , getMigrationAPIUrl ( oAuthMigrationRequest . getEnvironment ( ) ) ) . requiresAuthentication ( true ) . postJson ( requestjson ) . build ( ) ; Response response = client . makeJsonRequest ( request , oAuthMigrationRequest ) ; logger . debug ( "Response Code : " + response . getStatusCode ( ) ) ; if ( response . getStatusCode ( ) == 200 ) { ObjectReader reader = mapper . readerFor ( OAuthMigrationResponse . class ) ; OAuthMigrationResponse oAuthMigrationResponse = reader . readValue ( response . getContent ( ) ) ; return oAuthMigrationResponse ; } else { logger . debug ( "failed calling migrate API" ) ; throw new ConnectionException ( "failed calling migrate API" , response . getStatusCode ( ) + "" ) ; } } catch ( Exception ex ) { logger . error ( "Exception while calling migrate" , ex ) ; throw new ConnectionException ( ex . getMessage ( ) , ex ) ; } } | Calls the migrate API based on the the request provided and returns an object with oauth2 tokens |
35,944 | public Date unmarshal ( String value ) { if ( value != null ) { if ( value . length ( ) >= lengthOfDateFmtYYYY_MM_DD ) { value = value . substring ( 0 , lengthOfDateFmtYYYY_MM_DD ) ; boolean isMatch = value . matches ( datePattern ) ; if ( isMatch ) { return DatatypeConverter . parseDate ( value ) . getTime ( ) ; } else { return DatatypeConverter . parseDate ( INVALIDDATE ) . getTime ( ) ; } } else { return DatatypeConverter . parseDate ( INVALIDDATE ) . getTime ( ) ; } } else { return null ; } } | Unmarshal a Date . |
35,945 | public < T extends IEntity > void addEntity ( T entity , OperationEnum operation , String bId ) { BatchItemRequest batchItemRequest = new BatchItemRequest ( ) ; batchItemRequest . setBId ( bId ) ; batchItemRequest . setOperation ( operation ) ; batchItemRequest . setIntuitObject ( getIntuitObject ( entity ) ) ; batchItemRequests . add ( batchItemRequest ) ; bIds . add ( bId ) ; } | Method to add the entity batch operations to the batchItemRequest |
35,946 | public void addQuery ( String query , String bId ) { BatchItemRequest batchItemRequest = new BatchItemRequest ( ) ; batchItemRequest . setBId ( bId ) ; batchItemRequest . setQuery ( query ) ; batchItemRequests . add ( batchItemRequest ) ; bIds . add ( bId ) ; } | Method to add the query batch operation to batchItemRequest |
35,947 | public void addCDCQuery ( List < ? extends IEntity > entities , String changedSince , String bId ) throws FMSException { if ( entities == null || entities . isEmpty ( ) ) { throw new FMSException ( "Entities is required." ) ; } if ( ! StringUtils . hasText ( changedSince ) ) { throw new FMSException ( "changedSince is required." ) ; } CDCQuery cdcQuery = new CDCQuery ( ) ; StringBuffer entityParam = new StringBuffer ( ) ; for ( IEntity entity : entities ) { entityParam . append ( entity . getClass ( ) . getSimpleName ( ) ) . append ( "," ) ; } entityParam . delete ( entityParam . length ( ) - 1 , entityParam . length ( ) ) ; cdcQuery . setEntities ( entityParam . toString ( ) ) ; try { cdcQuery . setChangedSince ( DateUtils . getDateFromString ( changedSince ) ) ; } catch ( ParseException e ) { LOG . error ( "ParseException while converting to Date." , e ) ; throw new FMSException ( "ParseException while converting to Date. Please provide valid DateTime (yyyy-MM-ddTHH:mm:ss.SSSZ)." , e ) ; } BatchItemRequest batchItemRequest = new BatchItemRequest ( ) ; batchItemRequest . setBId ( bId ) ; batchItemRequest . setCDCQuery ( cdcQuery ) ; batchItemRequests . add ( batchItemRequest ) ; bIds . add ( bId ) ; } | Method to add the cdc query batch operation to batchItemRequest |
35,948 | public void addReportQuery ( String reportQuery , String bId ) { BatchItemRequest batchItemRequest = new BatchItemRequest ( ) ; batchItemRequest . setBId ( bId ) ; batchItemRequest . setReportQuery ( reportQuery ) ; batchItemRequests . add ( batchItemRequest ) ; bIds . add ( bId ) ; } | Method to add the report query batch operation to batchItemRequest |
35,949 | @ SuppressWarnings ( "unchecked" ) protected < T > JAXBElement < ? extends IntuitEntity > getIntuitObject ( T entity ) { Class < ? > objectClass = entity . getClass ( ) ; String methodName = "create" . concat ( objectClass . getSimpleName ( ) ) ; ObjectFactory objectEntity = new ObjectFactory ( ) ; Class < ? > objectEntityClass = objectEntity . getClass ( ) ; Method method = null ; try { method = objectEntityClass . getMethod ( methodName , Class . forName ( objectClass . getName ( ) ) ) ; } catch ( Exception e ) { LOG . error ( "Exception while prepare the method signature using reflection to generate JAXBElement" , e ) ; } JAXBElement < ? extends IntuitEntity > jaxbElement = null ; try { jaxbElement = ( JAXBElement < ? extends IntuitEntity > ) method . invoke ( objectEntity , entity ) ; } catch ( Exception e ) { LOG . error ( "Exception while invoking the method using reflection to generate JAXBElement" , e ) ; } return jaxbElement ; } | Method to get the corresponding IEntity type for the given JAXBElement |
35,950 | public CredentialsProvider setProxyAuthentication ( ProxyConfig proxyConfig ) { if ( proxyConfig == null ) { return null ; } String username = proxyConfig . getUsername ( ) ; String password = proxyConfig . getPassword ( ) ; if ( ! username . isEmpty ( ) && ! password . isEmpty ( ) ) { String host = proxyConfig . getHost ( ) ; String port = proxyConfig . getPort ( ) ; if ( ! host . isEmpty ( ) && ! port . isEmpty ( ) ) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider ( ) ; String domain = proxyConfig . getDomain ( ) ; if ( ! domain . isEmpty ( ) ) { credentialsProvider . setCredentials ( new AuthScope ( host , Integer . parseInt ( port ) ) , new NTCredentials ( username , password , host , domain ) ) ; } else { credentialsProvider . setCredentials ( new AuthScope ( host , Integer . parseInt ( port ) ) , new UsernamePasswordCredentials ( username , password ) ) ; } return credentialsProvider ; } } return null ; } | Method to set proxy authentication |
35,951 | public Response makeJsonRequest ( Request request , OAuthMigrationRequest migrationRequest ) throws InvalidRequestException { logger . debug ( "Enter HttpRequestClient::makeJsonRequest" ) ; OAuthConsumer consumer = new CommonsHttpOAuthConsumer ( migrationRequest . getConsumerKey ( ) , migrationRequest . getConsumerSecret ( ) ) ; consumer . setTokenWithSecret ( migrationRequest . getAccessToken ( ) , migrationRequest . getAccessSecret ( ) ) ; HttpPost post = new HttpPost ( request . constructURL ( ) . toString ( ) ) ; try { consumer . sign ( post ) ; } catch ( OAuthMessageSignerException e ) { logger . error ( "Exception while making httpRequest" , e ) ; throw new InvalidRequestException ( e . getMessage ( ) ) ; } catch ( OAuthExpectationFailedException e ) { logger . error ( "Exception while making httpRequest" , e ) ; throw new InvalidRequestException ( e . getMessage ( ) ) ; } catch ( OAuthCommunicationException e ) { logger . error ( "Exception while making httpRequest" , e ) ; throw new InvalidRequestException ( e . getMessage ( ) ) ; } post . setHeader ( "Accept" , "application/json" ) ; post . setHeader ( "Content-Type" , "application/json" ) ; HttpEntity entity = new StringEntity ( request . getPostJson ( ) , "UTF-8" ) ; post . setEntity ( entity ) ; CloseableHttpResponse httpResponse = null ; try { httpResponse = client . execute ( post ) ; return new Response ( httpResponse . getEntity ( ) == null ? null : httpResponse . getEntity ( ) . getContent ( ) , httpResponse . getStatusLine ( ) . getStatusCode ( ) ) ; } catch ( ClientProtocolException e ) { logger . error ( "Exception while making httpRequest" , e ) ; throw new InvalidRequestException ( e . getMessage ( ) ) ; } catch ( IOException e ) { logger . error ( "Exception while making httpRequest" , e ) ; throw new InvalidRequestException ( e . getMessage ( ) ) ; } } | Method to make the HTTP POST request using the request attributes supplied |
35,952 | public static Marshaller createMarshaller ( ) throws JAXBException { Marshaller marshaller = MessageUtilsHelper . getContext ( ) . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , Boolean . TRUE ) ; return marshaller ; } | Create Marshaller from the JAXB context . |
35,953 | public URL constructURL ( ) throws InvalidRequestException { String stringUri = url ; try { URI uri = new URI ( stringUri ) ; return uri . toURL ( ) ; } catch ( final URISyntaxException e ) { throw new InvalidRequestException ( "Bad URI: " + stringUri , e ) ; } catch ( final MalformedURLException e ) { throw new InvalidRequestException ( "Bad URL: " + stringUri , e ) ; } } | Prepares request URL |
35,954 | public OptionalSyntax where ( Expression < ? > ... expression ) { for ( Expression < ? > exp : expression ) { getMessage ( ) . getOptional ( ) . add ( exp . toString ( ) ) ; LOG . debug ( "expression: " + exp ) ; } QueryMessage mess = getMessage ( ) ; return new OptionalSyntax ( mess ) ; } | Method to get the optional syntax for where operator |
35,955 | public OptionalSyntax orderBy ( Path < ? > ... path ) { String fieldList = "" ; boolean firstExpression = true ; for ( Path < ? > exp : path ) { if ( firstExpression ) { fieldList = fieldList . concat ( exp . toString ( ) ) ; firstExpression = false ; } else { fieldList = fieldList . concat ( ", " ) . concat ( exp . toString ( ) ) ; } LOG . debug ( "expression: " + exp ) ; } QueryMessage mess = getMessage ( ) ; mess . setOrderByClause ( fieldList ) ; return new OptionalSyntax ( mess ) ; } | Method to get the optional syntax for order by operator |
35,956 | public OptionalSyntax skip ( int num ) { getMessage ( ) . setStartposition ( num ) ; QueryMessage mess = getMessage ( ) ; return new OptionalSyntax ( mess ) ; } | Method to get the optional syntax for skip operator |
35,957 | public OptionalSyntax take ( int num ) { getMessage ( ) . setMaxresults ( num ) ; QueryMessage mess = getMessage ( ) ; return new OptionalSyntax ( mess ) ; } | Method to get the optional syntax for take operator |
35,958 | public static String getResult ( HttpResponse response ) throws IOException { StringBuffer result = new StringBuffer ( ) ; if ( response . getEntity ( ) != null && response . getEntity ( ) . getContent ( ) != null ) { BufferedReader rd = new BufferedReader ( new InputStreamReader ( response . getEntity ( ) . getContent ( ) ) ) ; String line = "" ; while ( ( line = rd . readLine ( ) ) != null ) { result . append ( line ) ; } } logger . info ( result . toString ( ) ) ; return result . toString ( ) ; } | Parse the response and return the string from httpresponse body |
35,959 | JavaXmlQuery compile ( XPath xpath ) { try { this . expression = xpath . compile ( getQuery ( ) ) ; } catch ( XPathExpressionException e ) { LOGGER . error ( "Cannot compile XPath query: " + getQuery ( ) , e ) ; } return this ; } | Adds a compiled expression to the query |
35,960 | private Object getObjectValue ( XmlNode node , String fieldName ) { if ( node != null ) { String name = node . getName ( ) ; switch ( node . getType ( ) ) { case XmlNode . ATTRIBUTE_NODE : return name . equalsIgnoreCase ( fieldName ) ? node : null ; case XmlNode . ELEMENT_NODE : { if ( name . equalsIgnoreCase ( fieldName ) ) { return new XmlNodeArray ( node . getChildren ( ) ) ; } else { Map < String , XmlNode > attributes = node . getAttributes ( ) ; for ( Map . Entry < String , XmlNode > entry : attributes . entrySet ( ) ) { String attributeName = entry . getKey ( ) ; if ( attributeName . equalsIgnoreCase ( fieldName ) ) { return entry . getValue ( ) ; } } return null ; } } default : return null ; } } return null ; } | Returns the object value for the given VTD XML node and field name |
35,961 | private String getStringValue ( XmlNodeArray nodes ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( "<string>" ) ; for ( XmlNode node : nodes ) { stringBuilder . append ( getStringValue ( node ) ) ; } stringBuilder . append ( "</string>" ) ; return stringBuilder . toString ( ) ; } | Returns the string value for the given node array |
35,962 | private Object getObjectValue ( Node node , String fieldName ) { if ( node != null ) { String name = node . getLocalName ( ) ; switch ( node . getNodeType ( ) ) { case Node . ATTRIBUTE_NODE : return name . equalsIgnoreCase ( fieldName ) ? node : null ; case Node . ELEMENT_NODE : { if ( name . equalsIgnoreCase ( fieldName ) ) { return new NodeArray ( node . getChildNodes ( ) ) ; } else { NamedNodeMap namedNodeMap = node . getAttributes ( ) ; for ( int attributeIndex = 0 ; attributeIndex < namedNodeMap . getLength ( ) ; ++ attributeIndex ) { Node attribute = namedNodeMap . item ( attributeIndex ) ; if ( attribute . getLocalName ( ) . equalsIgnoreCase ( fieldName ) ) { return attribute ; } } return null ; } } default : return null ; } } return null ; } | Returns the object value for the given field name and node |
35,963 | private String getStringValue ( Object o ) { if ( o instanceof String ) { return ( String ) o ; } else if ( o instanceof NodeArray ) { NodeArray array = ( NodeArray ) o ; switch ( array . size ( ) ) { case 0 : return null ; case 1 : { return getStringValue ( array . get ( 0 ) ) ; } default : return getStringValue ( array ) ; } } else if ( o instanceof Node ) { return getStringValue ( ( Node ) o ) ; } else if ( o != null ) { return o . toString ( ) ; } return null ; } | Returns the string value for the object |
35,964 | private String getStringValue ( Node node ) { switch ( node . getNodeType ( ) ) { case Node . ATTRIBUTE_NODE : case Node . TEXT_NODE : return node . getNodeValue ( ) ; default : { try { Transformer transformer = TRANSFORMER_FACTORY . newTransformer ( ) ; StringWriter buffer = new StringWriter ( ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; transformer . transform ( new DOMSource ( node ) , new StreamResult ( buffer ) ) ; return buffer . toString ( ) ; } catch ( Exception e ) { } return null ; } } } | Returns the string value for the node |
35,965 | private String getStringValue ( NodeArray nodes ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( "<string>" ) ; for ( Node node : nodes ) { stringBuilder . append ( getStringValue ( node ) ) ; } stringBuilder . append ( "</string>" ) ; return stringBuilder . toString ( ) ; } | Returns the string value for the node array |
35,966 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) private void populateMap ( Map map , Node node ) { Map . Entry entry = getMapEntry ( node ) ; if ( entry != null ) { map . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } | Given the node populates the map |
35,967 | public void addAttribute ( final String _name , final String _value ) { this . attributes . put ( _name , new XmlNode ( ) { { this . name = _name ; this . value = _value ; this . valid = true ; this . type = XmlNode . ATTRIBUTE_NODE ; } } ) ; } | Adds the attribute |
35,968 | public static Object getPrimitiveValue ( String value , PrimitiveCategory primitiveCategory ) { if ( value != null ) { try { switch ( primitiveCategory ) { case BOOLEAN : return Boolean . valueOf ( value ) ; case BYTE : return Byte . valueOf ( value ) ; case DOUBLE : return Double . valueOf ( value ) ; case FLOAT : return Float . valueOf ( value ) ; case INT : return Integer . valueOf ( value ) ; case LONG : return Long . valueOf ( value ) ; case SHORT : return Short . valueOf ( value ) ; case STRING : return value ; default : throw new IllegalStateException ( primitiveCategory . toString ( ) ) ; } } catch ( Exception ignored ) { } } return null ; } | Converts the string value to the java object for the given primitive category |
35,969 | public static ObjectInspector getStandardJavaObjectInspectorFromTypeInfo ( TypeInfo typeInfo , XmlProcessor xmlProcessor ) { switch ( typeInfo . getCategory ( ) ) { case PRIMITIVE : { return PrimitiveObjectInspectorFactory . getPrimitiveJavaObjectInspector ( ( ( PrimitiveTypeInfo ) typeInfo ) . getPrimitiveCategory ( ) ) ; } case LIST : { ObjectInspector listElementObjectInspector = getStandardJavaObjectInspectorFromTypeInfo ( ( ( ListTypeInfo ) typeInfo ) . getListElementTypeInfo ( ) , xmlProcessor ) ; return new XmlListObjectInspector ( listElementObjectInspector , xmlProcessor ) ; } case MAP : { MapTypeInfo mapTypeInfo = ( MapTypeInfo ) typeInfo ; ObjectInspector mapKeyObjectInspector = getStandardJavaObjectInspectorFromTypeInfo ( mapTypeInfo . getMapKeyTypeInfo ( ) , xmlProcessor ) ; ObjectInspector mapValueObjectInspector = getStandardJavaObjectInspectorFromTypeInfo ( mapTypeInfo . getMapValueTypeInfo ( ) , xmlProcessor ) ; return new XmlMapObjectInspector ( mapKeyObjectInspector , mapValueObjectInspector , xmlProcessor ) ; } case STRUCT : { StructTypeInfo structTypeInfo = ( StructTypeInfo ) typeInfo ; List < String > structFieldNames = structTypeInfo . getAllStructFieldNames ( ) ; List < TypeInfo > fieldTypeInfos = structTypeInfo . getAllStructFieldTypeInfos ( ) ; List < ObjectInspector > structFieldObjectInspectors = new ArrayList < ObjectInspector > ( fieldTypeInfos . size ( ) ) ; for ( int fieldIndex = 0 ; fieldIndex < fieldTypeInfos . size ( ) ; ++ fieldIndex ) { structFieldObjectInspectors . add ( getStandardJavaObjectInspectorFromTypeInfo ( fieldTypeInfos . get ( fieldIndex ) , xmlProcessor ) ) ; } return getStandardStructObjectInspector ( structFieldNames , structFieldObjectInspectors , xmlProcessor ) ; } default : { throw new IllegalStateException ( ) ; } } } | Returns the standard java object inspector |
35,970 | public static StructObjectInspector getStandardStructObjectInspector ( List < String > structFieldNames , List < ObjectInspector > structFieldObjectInspectors , XmlProcessor xmlProcessor ) { return new XmlStructObjectInspector ( structFieldNames , structFieldObjectInspectors , xmlProcessor ) ; } | Returns the struct object inspector |
35,971 | public void transform ( XmlNode node , StringBuilder builder ) { switch ( node . getType ( ) ) { case XmlNode . ELEMENT_NODE : { builder . append ( "<" ) ; builder . append ( node . getName ( ) ) ; for ( XmlNode attribute : node . getAttributes ( ) . values ( ) ) { transform ( attribute , builder ) ; } builder . append ( ">" ) ; for ( XmlNode child : node . getChildren ( ) ) { transform ( child , builder ) ; } builder . append ( "</" ) ; builder . append ( node . getName ( ) ) ; builder . append ( ">" ) ; } break ; case XmlNode . ATTRIBUTE_NODE : { builder . append ( " " ) ; builder . append ( node . getName ( ) ) ; builder . append ( "=\"" ) ; builder . append ( node . getValue ( ) ) ; builder . append ( "\"" ) ; } break ; case XmlNode . TEXT_NODE : { builder . append ( node . getValue ( ) ) ; } } } | Transforms the XML node into the string |
35,972 | public void setVideoURI ( Uri uri , Map < String , String > headers ) { mUri = uri ; mHeaders = headers ; mSeekWhenPrepared = 0 ; openVideo ( ) ; requestLayout ( ) ; invalidate ( ) ; } | Sets video URI using specific headers . |
35,973 | public static StartupSettings fromJSONFile ( File jsonFile ) throws JSONException , FileNotFoundException , IOException { StringBuffer buffer = new StringBuffer ( ) ; try ( BufferedReader br = new BufferedReader ( new FileReader ( jsonFile ) ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { buffer . append ( line . trim ( ) ) ; } } JSONObject jsonObject = new JSONArray ( buffer . toString ( ) ) . getJSONObject ( 0 ) ; int port = jsonObject . getInt ( "port" ) ; String id = jsonObject . getString ( "id" ) ; int gossipInterval = jsonObject . getInt ( "gossip_interval" ) ; int cleanupInterval = jsonObject . getInt ( "cleanup_interval" ) ; String cluster = jsonObject . getString ( "cluster" ) ; if ( cluster == null ) { throw new IllegalArgumentException ( "cluster was null. It is required" ) ; } StartupSettings settings = new StartupSettings ( id , port , new GossipSettings ( gossipInterval , cleanupInterval ) , cluster ) ; String configMembersDetails = "Config-members [" ; JSONArray membersJSON = jsonObject . getJSONArray ( "members" ) ; for ( int i = 0 ; i < membersJSON . length ( ) ; i ++ ) { JSONObject memberJSON = membersJSON . getJSONObject ( i ) ; RemoteGossipMember member = new RemoteGossipMember ( memberJSON . getString ( "cluster" ) , memberJSON . getString ( "host" ) , memberJSON . getInt ( "port" ) , "" ) ; settings . addGossipMember ( member ) ; configMembersDetails += member . getAddress ( ) ; if ( i < ( membersJSON . length ( ) - 1 ) ) configMembersDetails += ", " ; } log . info ( configMembersDetails + "]" ) ; return settings ; } | Parse the settings for the gossip service from a JSON file . |
35,974 | protected void sendMembershipList ( LocalGossipMember me , List < LocalGossipMember > memberList ) { GossipService . LOGGER . debug ( "Send sendMembershipList() is called." ) ; me . setHeartbeat ( System . currentTimeMillis ( ) ) ; LocalGossipMember member = selectPartner ( memberList ) ; if ( member == null ) { return ; } try ( DatagramSocket socket = new DatagramSocket ( ) ) { socket . setSoTimeout ( gossipManager . getSettings ( ) . getGossipInterval ( ) ) ; InetAddress dest = InetAddress . getByName ( member . getHost ( ) ) ; ActiveGossipMessage message = new ActiveGossipMessage ( ) ; message . getMembers ( ) . add ( convert ( me ) ) ; for ( LocalGossipMember other : memberList ) { message . getMembers ( ) . add ( convert ( other ) ) ; } byte [ ] json_bytes = om . writeValueAsString ( message ) . getBytes ( ) ; int packet_length = json_bytes . length ; if ( packet_length < GossipManager . MAX_PACKET_SIZE ) { byte [ ] buf = createBuffer ( packet_length , json_bytes ) ; DatagramPacket datagramPacket = new DatagramPacket ( buf , buf . length , dest , member . getPort ( ) ) ; socket . send ( datagramPacket ) ; } else { GossipService . LOGGER . error ( "The length of the to be send message is too large (" + packet_length + " > " + GossipManager . MAX_PACKET_SIZE + ")." ) ; } } catch ( IOException e1 ) { GossipService . LOGGER . warn ( e1 ) ; } } | Performs the sending of the membership list after we have incremented our own heartbeat . |
35,975 | public void run ( ) { for ( LocalGossipMember member : members . keySet ( ) ) { if ( member != me ) { member . startTimeoutTimer ( ) ; } } try { passiveGossipThread = passiveGossipThreadClass . getConstructor ( GossipManager . class ) . newInstance ( this ) ; gossipThreadExecutor . execute ( passiveGossipThread ) ; activeGossipThread = activeGossipThreadClass . getConstructor ( GossipManager . class ) . newInstance ( this ) ; gossipThreadExecutor . execute ( activeGossipThread ) ; } catch ( InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1 ) { throw new RuntimeException ( e1 ) ; } GossipService . LOGGER . debug ( "The GossipService is started." ) ; while ( gossipServiceRunning . get ( ) ) { try { TimeUnit . MILLISECONDS . sleep ( 1 ) ; } catch ( InterruptedException e ) { GossipService . LOGGER . warn ( "The GossipClient was interrupted." ) ; } } } | Starts the client . Specifically start the various cycles for this protocol . Start the gossip thread and start the receiver thread . |
35,976 | public void shutdown ( ) { gossipServiceRunning . set ( false ) ; gossipThreadExecutor . shutdown ( ) ; if ( passiveGossipThread != null ) { passiveGossipThread . shutdown ( ) ; } if ( activeGossipThread != null ) { activeGossipThread . shutdown ( ) ; } try { boolean result = gossipThreadExecutor . awaitTermination ( 1000 , TimeUnit . MILLISECONDS ) ; if ( ! result ) { LOGGER . error ( "executor shutdown timed out" ) ; } } catch ( InterruptedException e ) { LOGGER . error ( e ) ; } } | Shutdown the gossip service . |
35,977 | private boolean isObjectHasValue ( Object targetObj ) { for ( Map . Entry < String , String > entry : cellMapping . entrySet ( ) ) { if ( ! StringUtils . equalsIgnoreCase ( HEADER_KEY , entry . getKey ( ) ) ) { if ( StringUtils . isNotBlank ( getPropertyValue ( targetObj , entry . getValue ( ) ) ) ) { return true ; } } } return false ; } | To check generic object of T has a minimum one value assigned or not |
35,978 | private void readSheet ( StylesTable styles , ReadOnlySharedStringsTable sharedStringsTable , InputStream sheetInputStream ) throws IOException , ParserConfigurationException , SAXException { SAXParserFactory saxFactory = SAXParserFactory . newInstance ( ) ; XMLReader sheetParser = saxFactory . newSAXParser ( ) . getXMLReader ( ) ; ContentHandler handler = new XSSFSheetXMLHandler ( styles , sharedStringsTable , sheetContentsHandler , true ) ; sheetParser . setContentHandler ( handler ) ; sheetParser . parse ( new InputSource ( sheetInputStream ) ) ; } | Parses the content of one sheet using the specified styles and shared - strings tables . |
35,979 | private static String getProgramProperty ( String property ) { if ( System . getProperty ( property ) != null ) { return System . getProperty ( property ) . trim ( ) ; } Properties prop = new Properties ( ) ; try ( InputStream input = new FileInputStream ( SELENIFIED ) ) { prop . load ( input ) ; } catch ( IOException e ) { log . info ( e ) ; } String fullProperty = prop . getProperty ( property ) ; if ( fullProperty != null ) { fullProperty = fullProperty . trim ( ) ; } return fullProperty ; } | Retrieves the specified program property . if it exists from the system properties that is returned overridding all other values . Otherwise if it exists from the properties file that is returned otherwise null is returned |
35,980 | public static boolean generatePDF ( ) { String generatePDF = getProgramProperty ( GENERATE_PDF ) ; if ( generatePDF == null ) { return false ; } if ( "" . equals ( generatePDF ) ) { return true ; } return "true" . equalsIgnoreCase ( generatePDF ) ; } | Determines if we are supposed to generate a pdf of the results or not |
35,981 | public static boolean packageResults ( ) { String packageResults = getProgramProperty ( PACKAGE_RESULTS ) ; if ( packageResults == null ) { return false ; } if ( "" . equals ( packageResults ) ) { return true ; } return "true" . equalsIgnoreCase ( packageResults ) ; } | Determines if we are supposed to zip up the results or not |
35,982 | public static String getProxy ( ) throws InvalidProxyException { String proxy = getProgramProperty ( PROXY ) ; if ( proxy == null ) { throw new InvalidProxyException ( PROXY_ISNT_SET ) ; } String [ ] proxyParts = proxy . split ( ":" ) ; if ( proxyParts . length != 2 ) { throw new InvalidProxyException ( "Proxy '" + proxy + "' isn't valid. Must contain address and port, without protocol" ) ; } try { Integer . parseInt ( proxyParts [ 1 ] ) ; } catch ( NumberFormatException e ) { throw new InvalidProxyException ( "Proxy '" + proxy + "' isn't valid. Must contain address and port, without protocol. Invalid port provided. " + e ) ; } return proxy ; } | Retrieves the proxy property if it is set . This could be to something local or in the cloud . Provide the protocol address and port |
35,983 | public static String getAppURL ( String clazz , ITestContext context ) throws InvalidHTTPException { String appURL = checkAppURL ( null , ( String ) context . getAttribute ( clazz + APP_URL ) , "The provided app via test case setup '" ) ; Properties prop = new Properties ( ) ; try ( InputStream input = new FileInputStream ( SELENIFIED ) ) { prop . load ( input ) ; } catch ( IOException e ) { log . info ( e ) ; } appURL = checkAppURL ( appURL , prop . getProperty ( APP_URL ) , "The provided app via Properties file '" ) ; appURL = checkAppURL ( appURL , System . getProperty ( APP_URL ) , "The provided app via System Properties '" ) ; if ( appURL != null ) { return appURL ; } throw new InvalidHTTPException ( "There was not a valid app provided to test. Please properly set the 'appURL'" ) ; } | Obtains the application under test as a URL . If the site was provided as a system property that value will override whatever was set in the particular test suite . If no site was set null will be returned which will causes the tests to error out |
35,984 | private static String checkAppURL ( String originalAppURL , String newAppURL , String s ) { if ( newAppURL != null && ! "" . equals ( newAppURL ) ) { if ( ! newAppURL . toLowerCase ( ) . startsWith ( "http" ) && ! newAppURL . toLowerCase ( ) . startsWith ( "file" ) ) { newAppURL = "http://" + newAppURL ; } try { new URL ( newAppURL ) ; return newAppURL ; } catch ( MalformedURLException e ) { log . error ( s + newAppURL + "' is not a valud URL." ) ; } } return originalAppURL ; } | A helper method to getAppURL which checks the provided URL and if it is valid overrides the initially provided one . |
35,985 | public static String getBrowser ( ) { String browser = getProgramProperty ( BROWSER ) ; if ( browser == null || "" . equals ( browser ) ) { browser = Browser . BrowserName . HTMLUNIT . toString ( ) ; } return browser ; } | Retrieves the browser property if it is set . This can be a single browser name or browser details . If it is not set HTMLUnit will be returned as the default browser to use |
35,986 | public static boolean runHeadless ( ) { String headless = getProgramProperty ( HEADLESS ) ; if ( headless == null ) { return false ; } if ( "" . equals ( headless ) ) { return true ; } return "true" . equalsIgnoreCase ( headless ) ; } | Determines if the headless parameter was set to have the browser run in headless mode . This only can be used for Chrome and Firefox . |
35,987 | public static String getOptions ( ) throws InvalidBrowserOptionsException { String options = getProgramProperty ( OPTIONS ) ; if ( options == null || "" . equals ( options ) ) { throw new InvalidBrowserOptionsException ( "Browser options aren't set" ) ; } return options ; } | Retrieves the set options |
35,988 | public void present ( double seconds ) { try { double timeTook = elementPresent ( seconds ) ; checkPresent ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkPresent ( seconds , seconds ) ; } } | Waits for the element to be present . The provided wait time will be used and if the element isn t present after that time it will fail and log the issue with a screenshot for traceability and added debugging support . |
35,989 | public void notPresent ( double seconds ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; try { WebDriverWait wait = new WebDriverWait ( element . getDriver ( ) , ( long ) seconds , DEFAULT_POLLING_INTERVAL ) ; wait . until ( ExpectedConditions . not ( ExpectedConditions . presenceOfAllElementsLocatedBy ( element . defineByElement ( ) ) ) ) ; double timeTook = Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; checkNotPresent ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkNotPresent ( seconds , seconds ) ; } } | Waits for the element to not be present . The provided wait time will be used and if the element isn t present after that time it will fail and log the issue with a screenshot for traceability and added debugging support . |
35,990 | public void displayed ( double seconds ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; try { double timeTook = elementPresent ( seconds ) ; WebDriverWait wait = new WebDriverWait ( element . getDriver ( ) , ( long ) ( seconds - timeTook ) , DEFAULT_POLLING_INTERVAL ) ; wait . until ( ExpectedConditions . visibilityOfElementLocated ( element . defineByElement ( ) ) ) ; timeTook = Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; checkDisplayed ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkDisplayed ( seconds , seconds ) ; } } | Waits for the element to be displayed . The provided wait time will be used and if the element isn t present after that time it will fail and log the issue with a screenshot for traceability and added debugging support . |
35,991 | public void notDisplayed ( double seconds ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; try { double timeTook = elementPresent ( seconds ) ; WebDriverWait wait = new WebDriverWait ( element . getDriver ( ) , ( long ) ( seconds - timeTook ) , DEFAULT_POLLING_INTERVAL ) ; wait . until ( ExpectedConditions . invisibilityOfElementLocated ( element . defineByElement ( ) ) ) ; timeTook = Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; checkNotDisplayed ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkNotDisplayed ( seconds , seconds ) ; } } | Waits for the element to not be displayed . The provided wait time will be used and if the element isn t present after that time it will fail and log the issue with a screenshot for traceability and added debugging support . |
35,992 | public void checked ( double seconds ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; try { elementPresent ( seconds ) ; while ( ! element . is ( ) . checked ( ) && System . currentTimeMillis ( ) < end ) ; double timeTook = Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; checkChecked ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkNotDisplayed ( seconds , seconds ) ; } } | Waits for the element to be checked . The provided wait time will be used and if the element isn t present after that time it will fail and log the issue with a screenshot for traceability and added debugging support . |
35,993 | public void editable ( double seconds ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; try { elementPresent ( seconds ) ; while ( ! element . is ( ) . editable ( ) && System . currentTimeMillis ( ) < end ) ; double timeTook = Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; checkEditable ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkEnabled ( seconds , seconds ) ; } } | Waits for the element to be editable . The provided wait time will be used and if the element isn t present after that time it will fail and log the issue with a screenshot for traceability and added debugging support . If the element isn t an input this will constitute a failure same as it not being editable . |
35,994 | public void enabled ( double seconds ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; try { double timeTook = elementPresent ( seconds ) ; WebDriverWait wait = new WebDriverWait ( element . getDriver ( ) , ( long ) ( seconds - timeTook ) , DEFAULT_POLLING_INTERVAL ) ; wait . until ( ExpectedConditions . elementToBeClickable ( element . defineByElement ( ) ) ) ; timeTook = Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; checkEnabled ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkEnabled ( seconds , seconds ) ; } } | Waits for the element to be enabled . The provided wait time will be used and if the element isn t present after that time it will fail and log the issue with a screenshot for traceability and added debugging support . |
35,995 | public void notEnabled ( double seconds ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; try { double timeTook = elementPresent ( seconds ) ; WebDriverWait wait = new WebDriverWait ( element . getDriver ( ) , ( long ) ( seconds - timeTook ) , DEFAULT_POLLING_INTERVAL ) ; wait . until ( ExpectedConditions . not ( ExpectedConditions . elementToBeClickable ( element . defineByElement ( ) ) ) ) ; timeTook = Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; checkNotEnabled ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkNotEnabled ( seconds , seconds ) ; } } | Waits for the element to not be enabled . The provided wait time will be used and if the element isn t present after that time it will fail and log the issue with a screenshot for traceability and added debugging support . |
35,996 | private Response call ( Method method , String endpoint , Request params , File inputFile ) { StringBuilder action = new StringBuilder ( ) ; action . append ( "Making <i>" ) ; action . append ( method . toString ( ) ) ; action . append ( "</i> call to <i>" ) ; action . append ( http . getServiceBaseUrl ( ) ) . append ( endpoint ) . append ( http . getRequestParams ( params ) ) ; action . append ( "</i>" ) ; action . append ( "<div class='indent'>" ) ; action . append ( Reporter . getCredentialStringOutput ( http ) ) ; action . append ( Reporter . getRequestHeadersOutput ( http ) ) ; action . append ( Reporter . getRequestPayloadOutput ( params , inputFile ) ) ; action . append ( "</div>" ) ; String expected = "<i>" + method + "</i> call was performed" ; Response response = null ; try { switch ( method ) { case GET : response = http . get ( endpoint , params ) ; break ; case POST : response = http . post ( endpoint , params , inputFile ) ; break ; case PUT : response = http . put ( endpoint , params , inputFile ) ; break ; case DELETE : response = http . delete ( endpoint , params , inputFile ) ; break ; } String actual = expected ; actual += "<div class='indent'>" ; actual += Reporter . getResponseHeadersOutput ( response ) ; actual += Reporter . getResponseCodeOutput ( response ) ; actual += Reporter . getResponseOutput ( response ) ; actual += "</div>" ; reporter . pass ( action . toString ( ) , expected , actual ) ; } catch ( Exception e ) { reporter . fail ( action . toString ( ) , expected , "<i>" + method + "</i> call failed. " + e . getMessage ( ) ) ; } return response ; } | Performs an http call and writes the call and response information to the output file |
35,997 | public void setupProxy ( ) throws InvalidProxyException { if ( Property . isProxySet ( ) ) { Proxy proxy = new Proxy ( ) ; proxy . setHttpProxy ( Property . getProxy ( ) ) ; desiredCapabilities . setCapability ( CapabilityType . PROXY , proxy ) ; } } | Obtains the set system values for the proxy and adds them to the desired desiredCapabilities |
35,998 | public WebDriver setupDriver ( ) throws InvalidBrowserException { WebDriver driver ; switch ( browser . getName ( ) ) { case HTMLUNIT : System . getProperties ( ) . put ( "org.apache.commons.logging.simplelog.defaultlog" , "fatal" ) ; java . util . logging . Logger . getLogger ( "com.gargoylesoftware.htmlunit" ) . setLevel ( Level . OFF ) ; java . util . logging . Logger . getLogger ( "org.apache.http" ) . setLevel ( Level . OFF ) ; driver = new HtmlUnitDriver ( desiredCapabilities ) ; break ; case FIREFOX : WebDriverManager . firefoxdriver ( ) . forceCache ( ) . setup ( ) ; FirefoxOptions firefoxOptions = new FirefoxOptions ( desiredCapabilities ) ; firefoxOptions . addArguments ( getBrowserOptions ( ) ) ; if ( Property . runHeadless ( ) ) { firefoxOptions . setHeadless ( true ) ; } driver = new FirefoxDriver ( firefoxOptions ) ; break ; case CHROME : WebDriverManager . chromedriver ( ) . forceCache ( ) . setup ( ) ; ChromeOptions chromeOptions = new ChromeOptions ( ) ; chromeOptions = chromeOptions . merge ( desiredCapabilities ) ; chromeOptions . addArguments ( getBrowserOptions ( ) ) ; if ( Property . runHeadless ( ) ) { chromeOptions . setHeadless ( true ) ; } driver = new ChromeDriver ( chromeOptions ) ; break ; case INTERNETEXPLORER : WebDriverManager . iedriver ( ) . forceCache ( ) . setup ( ) ; InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions ( desiredCapabilities ) ; driver = new InternetExplorerDriver ( internetExplorerOptions ) ; break ; case EDGE : WebDriverManager . edgedriver ( ) . forceCache ( ) . setup ( ) ; EdgeOptions edgeOptions = new EdgeOptions ( ) ; edgeOptions = edgeOptions . merge ( desiredCapabilities ) ; driver = new EdgeDriver ( edgeOptions ) ; break ; case SAFARI : SafariOptions safariOptions = new SafariOptions ( desiredCapabilities ) ; driver = new SafariDriver ( safariOptions ) ; break ; case OPERA : WebDriverManager . operadriver ( ) . forceCache ( ) . setup ( ) ; OperaOptions operaOptions = new OperaOptions ( ) ; operaOptions = operaOptions . merge ( desiredCapabilities ) ; driver = new OperaDriver ( operaOptions ) ; break ; case PHANTOMJS : WebDriverManager . phantomjs ( ) . forceCache ( ) . setup ( ) ; driver = new PhantomJSDriver ( desiredCapabilities ) ; break ; default : throw new InvalidBrowserException ( "The selected browser " + browser . getName ( ) + " is not an applicable choice" ) ; } return driver ; } | this creates the webdriver object which will be used to interact with for all browser web tests |
35,999 | public void addExtraCapabilities ( DesiredCapabilities extraCapabilities ) { if ( extraCapabilities != null && browser . getName ( ) != BrowserName . NONE ) { desiredCapabilities = desiredCapabilities . merge ( extraCapabilities ) ; } } | If additional capabilities are provided in the test case add them in |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.