idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
40,000
public com . google . api . ads . admanager . axis . v201805 . CustomFieldVisibility getVisibility ( ) { return visibility ; }
Gets the visibility value for this CustomField .
40,001
public void setProductTemplateMarketplaceInfo ( com . google . api . ads . admanager . axis . v201808 . ProductTemplateMarketplaceInfo productTemplateMarketplaceInfo ) { this . productTemplateMarketplaceInfo = productTemplateMarketplaceInfo ; }
Sets the productTemplateMarketplaceInfo value for this ProductTemplate .
40,002
@ SuppressWarnings ( "unchecked" ) public void setAuthorization ( Object soapClient , AdsSession adsSession ) throws AuthenticationException { final String authorizationHeader = authorizationHeaderProvider . getAuthorizationHeader ( adsSession , soapClientHandler . getEndpointAddress ( soapClient ) ) ; soapClientHandler . putAllHttpHeaders ( soapClient , new HashMap < String , String > ( ) { { put ( "Authorization" , authorizationHeader ) ; } } ) ; }
Sets the authorization header created from the session on the soap client .
40,003
public com . google . api . ads . adwords . axis . v201809 . cm . TrialAsyncError [ ] getEntries ( ) { return entries ; }
Gets the entries value for this TrialAsyncErrorPage .
40,004
public com . google . api . ads . adwords . axis . v201809 . cm . AppUrlOsType getOsType ( ) { return osType ; }
Gets the osType value for this AppUrl .
40,005
public com . google . api . ads . admanager . axis . v201808 . CreativeAsset getFallbackImageAsset ( ) { return fallbackImageAsset ; }
Gets the fallbackImageAsset value for this BaseFlashCreative .
40,006
public void setFallbackImageAsset ( com . google . api . ads . admanager . axis . v201808 . CreativeAsset fallbackImageAsset ) { this . fallbackImageAsset = fallbackImageAsset ; }
Sets the fallbackImageAsset value for this BaseFlashCreative .
40,007
public com . google . api . ads . adwords . axis . v201809 . cm . FeedStatus getFeedStatus ( ) { return feedStatus ; }
Gets the feedStatus value for this AdCustomizerFeed .
40,008
public com . google . api . ads . adwords . axis . v201809 . cm . AdCustomizerFeedAttribute [ ] getFeedAttributes ( ) { return feedAttributes ; }
Gets the feedAttributes value for this AdCustomizerFeed .
40,009
public com . google . api . ads . adwords . axis . v201809 . rm . RuleBasedUserListPrepopulationStatus getPrepopulationStatus ( ) { return prepopulationStatus ; }
Gets the prepopulationStatus value for this RuleBasedUserList .
40,010
public void buyNumber ( String country , String msisdn ) throws IOException , NexmoClientException { this . buyNumber . execute ( new BuyNumberRequest ( country , msisdn ) ) ; }
Start renting a Nexmo Virtual Number .
40,011
public void cancelNumber ( String country , String msisdn ) throws IOException , NexmoClientException { this . cancelNumber . execute ( new CancelNumberRequest ( country , msisdn ) ) ; }
Stop renting a Nexmo Virtual Number .
40,012
public void linkNumber ( String msisdn , String country , String appId ) throws IOException , NexmoClientException { UpdateNumberRequest request = new UpdateNumberRequest ( msisdn , country ) ; request . setVoiceCallbackType ( UpdateNumberRequest . CallbackType . APP ) ; request . setVoiceCallbackValue ( appId ) ; this . updateNumber ( request ) ; }
Link a given Nexmo Virtual Number to a Nexmo Application with the given ID .
40,013
public Document parseXml ( String xml ) throws NexmoResponseParseException { Document doc ; this . documentBuilderLock . lock ( ) ; try { if ( this . documentBuilder == null ) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; this . documentBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; } doc = XmlUtil . parseXmlString ( this . documentBuilder , xml ) ; } catch ( ParserConfigurationException e ) { throw new NexmoResponseParseException ( "Exception initialing XML parser" , e ) ; } finally { this . documentBuilderLock . unlock ( ) ; } return doc ; }
Parse a provided XML String and return the generated DOM Document .
40,014
public static AdvancedInsightRequest withNumberAndCountry ( String number , String country ) { return new Builder ( number ) . country ( country ) . build ( ) ; }
Construct a AdvancedInsightRequest with a number and country .
40,015
public DtmfResponse sendDtmf ( String uuid , String digits ) throws IOException , NexmoClientException { return dtmf . put ( uuid , digits ) ; }
Send DTMF codes to an ongoing call .
40,016
public ModifyCallResponse transferCall ( String uuid , String nccoUrl ) throws IOException , NexmoClientException { return this . modifyCall ( CallModifier . transferCall ( uuid , nccoUrl ) ) ; }
Transfer a call to a different NCCO endpoint .
40,017
public StreamResponse startStream ( String uuid , String streamUrl , int loop ) throws IOException , NexmoClientException { return streams . put ( new StreamRequest ( uuid , streamUrl , loop ) ) ; }
Stream audio to an ongoing call .
40,018
public static String calculateMd5 ( String input ) throws NoSuchAlgorithmException { try { return calculateMd5 ( input , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { return null ; } }
Calculates MD5 hash for string . assume string is UTF - 8 encoded
40,019
public static String calculateMd5 ( String input , String encoding ) throws NoSuchAlgorithmException , UnsupportedEncodingException { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( input . getBytes ( encoding ) ) ; byte digest [ ] = md . digest ( ) ; final StringBuilder hexString = new StringBuilder ( ) ; for ( byte element : digest ) { int z = 0xFF & element ; if ( z < 16 ) hexString . append ( "0" ) ; hexString . append ( Integer . toHexString ( z ) ) ; } return hexString . toString ( ) ; }
Calculates MD5 hash for string .
40,020
public void submitConversion ( ConversionRequest . Type type , String messageId , boolean delivered , Date timestamp ) throws IOException , NexmoClientException { this . conversionEndpoint . submitConversion ( new ConversionRequest ( type , messageId , delivered , timestamp ) ) ; }
Submit a request to the Conversion API indicating whether or not a message was delivered .
40,021
public SearchSmsResponse searchMessages ( String id , String ... ids ) throws IOException , NexmoClientException { List < String > idList = new ArrayList < > ( ids . length + 1 ) ; idList . add ( id ) ; idList . addAll ( Arrays . asList ( ids ) ) ; return this . searchMessages ( new SmsIdSearchRequest ( idList ) ) ; }
Search for completed SMS transactions by ID
40,022
public SearchSmsResponse searchMessages ( Date date , String to ) throws IOException , NexmoClientException { return this . searchMessages ( new SmsDateSearchRequest ( date , to ) ) ; }
Search for completed SMS transactions by date and recipient MSISDN .
40,023
public SearchRejectedMessagesResponse searchRejectedMessages ( Date date , String to ) throws IOException , NexmoClientException { return this . searchRejectedMessages ( new SearchRejectedMessagesRequest ( date , to ) ) ; }
Search for rejected SMS transactions by date and recipient MSISDN .
40,024
public PrefixPricingResponse getPrefixPrice ( ServiceType type , String prefix ) throws IOException , NexmoClientException { return getPrefixPrice ( new PrefixPricingRequest ( type , prefix ) ) ; }
Retrieve the pricing for a specified prefix .
40,025
public SecretResponse getSecret ( String apiKey , String secretId ) throws IOException , NexmoClientException { return getSecret ( new SecretRequest ( apiKey , secretId ) ) ; }
Get information for a specific secret id associated to a given API key .
40,026
public SecretResponse createSecret ( String apiKey , String secret ) throws IOException , NexmoClientException { return createSecret ( new CreateSecretRequest ( apiKey , secret ) ) ; }
Create a secret to be used with a specific API key .
40,027
public void revokeSecret ( String apiKey , String secretId ) throws IOException , NexmoClientException { revokeSecret ( new SecretRequest ( apiKey , secretId ) ) ; }
Revoke a secret associated with a specific API key .
40,028
public static StandardInsightRequest withNumberAndCountry ( String number , String country ) { return new Builder ( number ) . country ( country ) . build ( ) ; }
Construct a StandardInsightRequest with a number and country .
40,029
public String generateJwt ( ) throws NexmoUnacceptableAuthException { JWTAuthMethod authMethod = this . httpWrapper . getAuthCollection ( ) . getAuth ( JWTAuthMethod . class ) ; return authMethod . constructToken ( System . currentTimeMillis ( ) / 1000L , JWTAuthMethod . constructJTI ( ) ) ; }
Generate a JWT for the application the client has been configured with .
40,030
public static BasicInsightRequest withNumberAndCountry ( String number , String country ) { return new Builder ( number ) . country ( country ) . build ( ) ; }
Construct a BasicInsightRequest with a number and country .
40,031
public < T extends AuthMethod > T getAuth ( Class < T > type ) throws NexmoUnacceptableAuthException { for ( AuthMethod availableAuthMethod : this . authList ) { if ( type . isInstance ( availableAuthMethod ) ) { return ( T ) availableAuthMethod ; } } throw new NexmoUnacceptableAuthException ( this . authList , new HashSet < > ( Arrays . asList ( new Class [ ] { type } ) ) ) ; }
Obtain an AuthMethod of type T if one is contained in this collection .
40,032
public static String bytesToHex ( byte [ ] bytes , String separator ) { StringBuilder tmpBuffer = new StringBuilder ( ) ; if ( bytes != null ) { for ( byte c : bytes ) { int b = c ; if ( b < 0 ) b += 256 ; if ( separator != null ) tmpBuffer . append ( separator ) ; tmpBuffer . append ( HEX_CHARS [ ( b & 0xf0 ) / 0x10 ] ) ; tmpBuffer . append ( HEX_CHARS [ b & 0x0f ] ) ; } } return tmpBuffer . toString ( ) ; }
translate a byte array of raw data into a String with a hex representation of that data . Each octet will be separated with a specific separator .
40,033
public static byte [ ] hexToBytes ( String str ) { if ( str == null ) return null ; byte [ ] hexChars ; try { hexChars = str . toUpperCase ( ) . getBytes ( "ISO_8859-1" ) ; } catch ( UnsupportedEncodingException e ) { throw new NexmoUnexpectedException ( "ISO_8859_1 is an unsupported encoding in this JVM" ) ; } int size = hexChars . length ; byte [ ] bytes = new byte [ size / 2 ] ; int first ; int second ; int rIndex = 0 ; for ( int i = 0 ; i + 1 < size ; i = i + 2 ) { first = hexChars [ i ] ; if ( first < 58 ) first = ( ( first - 48 ) * 16 ) ; else first = ( ( first - 55 ) * 16 ) ; second = hexChars [ i + 1 ] ; if ( second < 58 ) second = second - 48 ; else second = second - 55 ; int total = ( first + second ) ; if ( total > 127 ) total = ( 256 + total ) ; bytes [ rIndex ] = ( byte ) total ; rIndex ++ ; } return bytes ; }
Converts a Hex encoded String into a byte vector .
40,034
public BasicInsightResponse getBasicNumberInsight ( String number ) throws IOException , NexmoClientException { return getBasicNumberInsight ( BasicInsightRequest . withNumber ( number ) ) ; }
Perform a Basic Insight Request with a number .
40,035
public BasicInsightResponse getBasicNumberInsight ( String number , String country ) throws IOException , NexmoClientException { return getBasicNumberInsight ( BasicInsightRequest . withNumberAndCountry ( number , country ) ) ; }
Perform a Basic Insight Request with a number and country .
40,036
public StandardInsightResponse getStandardNumberInsight ( String number ) throws IOException , NexmoClientException { return getStandardNumberInsight ( StandardInsightRequest . withNumber ( number ) ) ; }
Perform a Standard Insight Request with a number .
40,037
public StandardInsightResponse getStandardNumberInsight ( String number , String country ) throws IOException , NexmoClientException { return getStandardNumberInsight ( StandardInsightRequest . withNumberAndCountry ( number , country ) ) ; }
Perform a Standard Insight Request with a number and country .
40,038
public StandardInsightResponse getStandardNumberInsight ( String number , String country , boolean cnam ) throws IOException , NexmoClientException { return getStandardNumberInsight ( StandardInsightRequest . builder ( number ) . country ( country ) . cnam ( cnam ) . build ( ) ) ; }
Perform a Standard Insight Request with a number country and cnam .
40,039
public AdvancedInsightResponse getAdvancedNumberInsight ( String number ) throws IOException , NexmoClientException { return getAdvancedNumberInsight ( AdvancedInsightRequest . withNumber ( number ) ) ; }
Perform an Advanced Insight Request with a number .
40,040
public AdvancedInsightResponse getAdvancedNumberInsight ( String number , String country ) throws IOException , NexmoClientException { return getAdvancedNumberInsight ( AdvancedInsightRequest . withNumberAndCountry ( number , country ) ) ; }
Perform an Advanced Insight Request with a number and country .
40,041
public AdvancedInsightResponse getAdvancedNumberInsight ( String number , String country , String ipAddress ) throws IOException , NexmoClientException { return getAdvancedNumberInsight ( AdvancedInsightRequest . builder ( number ) . country ( country ) . ipAddress ( ipAddress ) . build ( ) ) ; }
Perform an Advanced Insight Request with a number country and ipAddress .
40,042
public ResultT execute ( RequestT request ) throws IOException , NexmoClientException { try { RequestBuilder requestBuilder = applyAuth ( makeRequest ( request ) ) ; HttpUriRequest httpRequest = requestBuilder . build ( ) ; if ( httpRequest instanceof HttpEntityEnclosingRequest ) { HttpEntityEnclosingRequest entityRequest = ( HttpEntityEnclosingRequest ) httpRequest ; HttpEntity entity = entityRequest . getEntity ( ) ; if ( entity instanceof UrlEncodedFormEntity ) { entityRequest . setEntity ( new UrlEncodedFormEntity ( requestBuilder . getParameters ( ) , Charset . forName ( "UTF-8" ) ) ) ; } else if ( entity instanceof StringEntity ) { entityRequest . setEntity ( new StringEntity ( EntityUtils . toString ( entity ) , Charset . forName ( "UTF-8" ) ) ) ; } } LOG . debug ( "Request: " + httpRequest ) ; if ( LOG . isDebugEnabled ( ) && httpRequest instanceof HttpEntityEnclosingRequestBase ) { HttpEntityEnclosingRequestBase enclosingRequest = ( HttpEntityEnclosingRequestBase ) httpRequest ; LOG . debug ( EntityUtils . toString ( enclosingRequest . getEntity ( ) ) ) ; } HttpResponse response = this . httpWrapper . getHttpClient ( ) . execute ( httpRequest ) ; return parseResponse ( response ) ; } catch ( UnsupportedEncodingException uee ) { throw new NexmoUnexpectedException ( "UTF-8 encoding is not supported by this JVM." , uee ) ; } }
Execute the REST call represented by this method object .
40,043
public VerifyResponse verify ( final String number , final String brand , final String from , final int length , final Locale locale ) throws IOException , NexmoClientException { return this . verify . verify ( number , brand , from , length , locale ) ; }
Send a verification request to a phone number .
40,044
public ControlResponse advanceVerification ( String requestId ) throws IOException , NexmoClientException { return this . control . execute ( new ControlRequest ( requestId , VerifyControlCommand . TRIGGER_NEXT_EVENT ) ) ; }
Advance a current verification request to the next stage in the process .
40,045
public ControlResponse cancelVerification ( String requestId ) throws IOException , NexmoClientException { return this . control . execute ( new ControlRequest ( requestId , VerifyControlCommand . CANCEL ) ) ; }
Cancel a current verification request .
40,046
public static void parseWikipediaDump ( URL dumpFile , PageCallbackHandler handler ) throws Exception { WikiXMLParser wxsp = WikiXMLParserFactory . getSAXParser ( dumpFile ) ; wxsp . setPageCallback ( handler ) ; wxsp . parse ( ) ; }
A convenience method for the Wikipedia SAX interface
40,047
private JMethod getMethodsMap ( MethodType type , JFieldVar field , ClassOutline co ) { String getterBody = "return " + field . name ( ) + ";" ; for ( JMethod method : co . implClass . methods ( ) ) { String name = method . name ( ) ; if ( method . type ( ) . isPrimitive ( ) ) { if ( MethodType . GETTER == type && ( name . startsWith ( "is" ) || name . startsWith ( "get" ) ) ) { JStatement o = ( JStatement ) method . body ( ) . getContents ( ) . get ( 0 ) ; String s = getterBody ( o ) ; if ( s . trim ( ) . equals ( getterBody ) ) { return method ; } } else if ( MethodType . SETTER == type && name . startsWith ( "set" ) ) { JStatement o = ( JStatement ) method . body ( ) . getContents ( ) . get ( 0 ) ; String s = setterBody ( o ) ; if ( s . startsWith ( "this." + field . name ( ) + " =" ) ) { return method ; } } } } throw new RuntimeException ( "Failed to find " + type + " for " + field . name ( ) + ", disable XReplacePrimitives and report a bug" ) ; }
I hate this shit
40,048
private ExecJavaCliParser createExecCommandParser ( String containerWorkDir ) { String execLine = this . filterAndExecuteLaunchScriptAndReturnExecLine ( containerWorkDir ) ; String [ ] values = execLine . split ( "\"" ) ; String javaCli = values [ 1 ] ; String [ ] javaCliValues = javaCli . split ( " " ) ; StringBuffer buffer = new StringBuffer ( ) ; for ( int i = 0 ; i < javaCliValues . length ; i ++ ) { if ( i > 0 ) { buffer . append ( javaCliValues [ i ] ) ; if ( javaCliValues . length - i > 1 ) { buffer . append ( " " ) ; } } } String extractedJavaCli = buffer . toString ( ) ; ExecJavaCliParser execJavaCliParser = new ExecJavaCliParser ( extractedJavaCli ) ; return execJavaCliParser ; }
Creates CLI parser which can be used to extract Container s class name and its launch arguments .
40,049
private String filterAndExecuteLaunchScriptAndReturnExecLine ( String containerWorkDir ) { BufferedReader reader = null ; BufferedWriter writer = null ; String execLine = null ; File inJvmlaunchScript = null ; try { File launchScript = new File ( containerWorkDir , "launch_container.sh" ) ; inJvmlaunchScript = new File ( containerWorkDir . toString ( ) , "injvm_launch_container.sh" ) ; inJvmlaunchScript . setExecutable ( true ) ; reader = new BufferedReader ( new FileReader ( launchScript ) ) ; writer = new BufferedWriter ( new FileWriter ( inJvmlaunchScript ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . startsWith ( "exec" ) ) { execLine = line ; } else if ( line . startsWith ( "cp \"launch_container.sh\"" ) ) { String [ ] lineParts = line . split ( " " ) ; writer . write ( lineParts [ 0 ] ) ; writer . write ( " \"" + containerWorkDir + "/launch_container.sh\" " ) ; writer . write ( lineParts [ 2 ] ) ; writer . write ( "\n" ) ; } else { writer . write ( line ) ; writer . write ( "\n" ) ; } } } catch ( Exception e ) { throw new IllegalStateException ( "Failed to override default launch script" , e ) ; } finally { try { reader . close ( ) ; } catch ( IOException e ) { } try { writer . close ( ) ; } catch ( IOException e ) { } } if ( inJvmlaunchScript != null ) { try { inJvmlaunchScript . setExecutable ( true ) ; Process process = Runtime . getRuntime ( ) . exec ( inJvmlaunchScript . getAbsolutePath ( ) ) ; int exitCode = process . waitFor ( ) ; if ( exitCode != 0 ) { throw new IllegalStateException ( "Failed to execute launch script. Exit code: " + exitCode ) ; } } catch ( Exception e ) { throw new IllegalStateException ( "Failed to execute " + inJvmlaunchScript . getAbsolutePath ( ) , e ) ; } } return execLine ; }
This method does three things 1 . It creates an updated version of the initial launch script where it simply copies its contents less the exec line 2 . It extract the exec line and returns it so the Container s class name and launch arguments could be retrieved . 3 . It executes the exec - less launch script to ensure that all symlinks and other prepwork expected by the underlying container is performed .
40,050
private void cleanUp ( ) { try { File file = new File ( System . getProperty ( "user.dir" ) ) ; String [ ] links = file . list ( ) ; for ( String name : links ) { File potentialSymLink = new File ( file , name ) ; if ( FileUtils . isSymlink ( potentialSymLink ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "DELETING: " + potentialSymLink ) ; } potentialSymLink . delete ( ) ; } } } catch ( Exception e ) { logger . warn ( "Failed to remove symlinks" , e ) ; } }
Will clean up symlinks that were created by a launch script
40,051
public Map < String , Integer > getGatewayPortMappings ( ) { final Map < String , Integer > result = new ConcurrentHashMap < String , Integer > ( ) ; final Map < String , String > properties = getValByRegex ( GATEWAY_PORT_MAPPING_REGEX ) ; for ( final Map . Entry < String , String > e : properties . entrySet ( ) ) { if ( ! e . getKey ( ) . equalsIgnoreCase ( GATEWAY_PORT_MAPPING_ENABLED ) ) { result . put ( StringUtils . substringAfter ( e . getKey ( ) , GATEWAY_PORT_MAPPING_PREFIX ) , Integer . parseInt ( e . getValue ( ) ) ) ; } } return Collections . unmodifiableMap ( result ) ; }
Map of Topology names and their ports .
40,052
public static void put ( String key , String value ) throws Exception { Map < String , String > environemnt = new HashMap < String , String > ( System . getenv ( ) ) ; environemnt . put ( key , value ) ; updateEnvironment ( environemnt ) ; }
Allows dynamic update to the environment variables .
40,053
public void createShareLib ( ) { if ( ! oozieShareLibCreate ) { LOG . info ( "OOZIE: Share Lib Create Disabled... skipping" ) ; } else { final String fullOozieTarFilePath = shareLibCacheDir + Path . SEPARATOR + getOozieTarFileName ( ) ; try { getOozieTarFileFromRepo ( ) ; String oozieExtractTempDir = extractOozieTarFileToTempDir ( new File ( fullOozieTarFilePath ) ) ; String fullOozieShareLibTarFilePath = oozieExtractTempDir + Path . SEPARATOR + "oozie-" + getOozieVersionFromOozieTarFileName ( ) + Path . SEPARATOR + "oozie-sharelib-" + getOozieVersionFromOozieTarFileName ( ) + ".tar.gz" ; String oozieShareLibExtractTempDir = extractOozieShareLibTarFileToTempDir ( new File ( fullOozieShareLibTarFilePath ) ) ; Path destPath = new Path ( oozieHdfsShareLibDir + Path . SEPARATOR + "oozie" + Path . SEPARATOR + SHARE_LIB_PREFIX + getTimestampDirectory ( ) ) ; LOG . info ( "OOZIE: Writing share lib contents to: {}" , destPath ) ; hdfsFileSystem . copyFromLocalFile ( false , new Path ( new File ( oozieShareLibExtractTempDir ) . toURI ( ) ) , destPath ) ; if ( purgeLocalShareLibCache ) { FileUtils . deleteDirectory ( new File ( shareLibCacheDir ) ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } }
Main driver that downloads extracts and deploys the oozie sharelib
40,054
public PageRevision getMostRecentRevision ( String ... titles ) throws Exception { URL url = new URL ( entryPoint + "/w/api.php?format=json&action=query&prop=revisions&rvprop=user|timestamp&titles=" + encode ( Joiner . on ( "|" ) . join ( titles ) , "UTF-8" ) ) ; String response = readURL ( url ) ; List < PageRevision > revisions = extractRevisions ( response ) ; Collections . sort ( revisions , new Comparator < PageRevision > ( ) { public int compare ( final PageRevision o1 , final PageRevision o2 ) { return o2 . date . compareTo ( o1 . date ) ; } } ) ; return revisions . get ( 0 ) ; }
Returns the latest revision of the page which was edited last
40,055
public StubWithCondition match ( String label , Condition ... conditions ) { StubWithCondition swc = new StubWithCondition ( stubServer , Condition . composite ( conditions ) ) ; swc . stub . withLabel ( label ) ; return swc ; }
Creates a stub with a label and adds a condition to it
40,056
public boolean isApplicable ( Call call ) { return when . getPredicate ( ) . test ( call ) && ( actionSequence . size ( ) == 0 || exceededAction != null || actionSequence . size ( ) > appliedTimes ) ; }
Checks whether the call satisfies condition of this stub
40,057
public Response apply ( Response response ) { if ( when instanceof ConditionWithApplicables ) { for ( Applicable applicable : ( ( ConditionWithApplicables ) when ) . getApplicables ( ) ) { response = applicable . apply ( response ) ; } } Applicable chosenAction ; if ( actionSequence . isEmpty ( ) ) { chosenAction = action ; } else if ( actionSequence . size ( ) > appliedTimes ) { chosenAction = composite ( action , actionSequence . get ( appliedTimes ) ) ; } else if ( exceededAction != null ) { chosenAction = exceededAction ; } else { chosenAction = action ; } response = chosenAction . apply ( response ) ; appliedTimes ++ ; return response ; }
Executes all actions against the response .
40,058
public StubWithAction then ( Applicable ... actions ) { Stub s = this . stub . withAction ( composite ( actions ) ) ; stubServer . addStub ( s ) ; return new StubWithAction ( s ) ; }
Attach actions to the stub
40,059
public static Action status ( final HttpStatus status ) { return new Action ( input -> { input . setStatus ( status ) ; return input ; } ) ; }
Sets HTTP status to response
40,060
public static Action bytesContent ( final byte [ ] content ) { return new Action ( response -> { response . setContentLength ( content . length ) ; try { response . getOutputStream ( ) . write ( content ) ; } catch ( IOException e ) { throw new RuntimeException ( "Can not write resource content for restito stubbing." ) ; } return response ; } ) ; }
Writes bytes content to response
40,061
public static Action header ( final String key , final String value ) { return new Action ( input -> { input . setHeader ( key , value ) ; return input ; } ) ; }
Sets key - value header on response
40,062
public static Action contentType ( final String contentType ) { return new Action ( r -> { r . setContentType ( contentType ) ; return r ; } ) ; }
Sets content type to the response
40,063
public static Action unauthorized ( final String realm ) { return new Action ( r -> { r . addHeader ( "WWW-Authenticate" , "Basic realm=\"" + realm + "\"" ) ; r . setStatus ( HttpStatus . UNAUTHORIZED_401 ) ; return r ; } ) ; }
Returns unauthorized response
40,064
public static Action delay ( final Integer delay ) { return new Action ( input -> { try { Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } return input ; } ) ; }
Sleeps so many milliseconds emulating slow requests .
40,065
public StubServer run ( ) { simpleServer . getServerConfiguration ( ) . addHttpHandler ( stubsToHandler ( ) , "/" ) ; try { if ( secured ) { for ( NetworkListener networkListener : simpleServer . getListeners ( ) ) { networkListener . setSecure ( true ) ; SSLEngineConfigurator sslEngineConfig = new SSLEngineConfigurator ( getSslConfig ( ) , false , false , false ) ; networkListener . setSSLEngineConfig ( sslEngineConfig ) ; } } simpleServer . start ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return this ; }
Starts the server
40,066
private String createCertificateStore ( String resourceName ) throws IOException { URL resource = StubServer . class . getResource ( "/" + resourceName ) ; File store = File . createTempFile ( resourceName , "store" ) ; try ( InputStream input = resource . openStream ( ) ) { Files . copy ( input , store . toPath ( ) , StandardCopyOption . REPLACE_EXISTING ) ; } finally { store . deleteOnExit ( ) ; } return store . getAbsolutePath ( ) ; }
Copy the Certificate store to the temporary directory as it needs to be in a real file not inside a jar for Grizzly to pick it up .
40,067
public static Condition method ( final Method m ) { return new Condition ( input -> m . equals ( input . getMethod ( ) ) ) ; }
Checks HTTP method
40,068
private static ConditionWithApplicables methodWithUriAndAutoDiscovery ( final Method m , String uri ) { try { final URL resource = new SmartDiscoverer ( "restito" ) . discoverResource ( m , uri ) ; return new ConditionWithApplicables ( composite ( method ( m ) , uri ( uri ) ) , resourceContent ( resource ) ) ; } catch ( IllegalArgumentException e ) { logger . debug ( "Can not auto-discover resource for URI [{}]" , uri ) ; } return new ConditionWithApplicables ( composite ( method ( m ) , uri ( uri ) ) , Action . noop ( ) ) ; }
Checks HTTP method URI and enables AutoDiscovery
40,069
public static Condition parameter ( final String key , final String ... parameterValues ) { return new Condition ( input -> Arrays . equals ( input . getParameters ( ) . get ( key ) , parameterValues ) ) ; }
Checks HTTP parameters . Also work with multi - valued parameters
40,070
public static Condition endsWithUri ( final String uri ) { return new Condition ( input -> input . getUri ( ) . endsWith ( uri ) ) ; }
URI ends with
40,071
public static Condition withPostBody ( ) { return new Condition ( input -> input . getPostBody ( ) != null && input . getPostBody ( ) . length ( ) > 0 ) ; }
Contains non - empty POST body
40,072
public static Condition basicAuth ( String username , String password ) { final String authString = username + ":" + password ; final String encodedAuthString = new String ( Base64 . encodeBase64 ( authString . getBytes ( ) ) ) ; return new Condition ( input -> ( "Basic " + encodedAuthString ) . equals ( input . getAuthorization ( ) ) ) ; }
If basic authentication is provided
40,073
public static Condition withPostBodyContaining ( final String str ) { return new Condition ( input -> input . getPostBody ( ) != null && input . getPostBody ( ) . contains ( str ) ) ; }
With POST body containing string
40,074
public static Condition withPostBodyContaining ( final Pattern pattern ) { return new Condition ( input -> input . getPostBody ( ) . matches ( pattern . pattern ( ) ) ) ; }
With post body matching pattern
40,075
public < Result > Result submitRequest ( TDApiRequest apiRequest , Optional < String > apiKeyCache , TDHttpRequestHandler < Result > handler ) throws TDClientException { RequestContext requestContext = new RequestContext ( config , apiRequest , apiKeyCache ) ; try { return submitRequest ( requestContext , handler ) ; } catch ( InterruptedException e ) { logger . warn ( "API request interrupted" , e ) ; throw new TDClientInterruptedException ( e ) ; } catch ( TDClientException e ) { throw e ; } catch ( Exception e ) { throw new TDClientException ( INVALID_JSON_RESPONSE , e ) ; } }
A low - level method to submit a TD API request .
40,076
public < Result > Result call ( TDApiRequest apiRequest , Optional < String > apiKeyCache , final Function < InputStream , Result > contentStreamHandler ) { return submitRequest ( apiRequest , apiKeyCache , newByteStreamHandler ( contentStreamHandler ) ) ; }
Submit an API request and returns the byte InputStream . This stream is valid until exiting this function .
40,077
public < Result > Result call ( TDApiRequest apiRequest , Optional < String > apiKeyCache , final Class < Result > resultType ) throws TDClientException { return call ( apiRequest , apiKeyCache , objectMapper . getTypeFactory ( ) . constructType ( resultType ) ) ; }
Submit an API request and bind the returned JSON data into an object of the given result type . For mapping it uses Jackson object mapper .
40,078
@ SuppressWarnings ( value = "unchecked cast" ) public < Result > Result call ( TDApiRequest apiRequest , Optional < String > apiKeyCache , final JavaType resultType ) throws TDClientException { try { byte [ ] content = submitRequest ( apiRequest , apiKeyCache , byteArrayContentHandler ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "response:\n{}" , new String ( content , StandardCharsets . UTF_8 ) ) ; } if ( resultType . getRawClass ( ) == String . class ) { return ( Result ) new String ( content , StandardCharsets . UTF_8 ) ; } else { return getJsonReader ( resultType ) . readValue ( content ) ; } } catch ( JsonMappingException e ) { logger . error ( "Jackson mapping error" , e ) ; throw new TDClientException ( INVALID_JSON_RESPONSE , e ) ; } catch ( IOException e ) { throw new TDClientException ( INVALID_JSON_RESPONSE , e ) ; } }
Submit an API request and bind the returned JSON data into an object of the given result jackson JavaType . For mapping it uses Jackson object mapper .
40,079
public Properties toProperties ( ) { Properties p = new Properties ( ) ; saveProperty ( p , Type . API_ENDPOINT , endpoint ) ; saveProperty ( p , Type . API_PORT , port ) ; saveProperty ( p , Type . USESSL , useSSL ) ; saveProperty ( p , Type . APIKEY , apiKey ) ; saveProperty ( p , Type . USER , user ) ; saveProperty ( p , Type . PASSOWRD , password ) ; if ( proxy . isPresent ( ) ) { ProxyConfig pc = proxy . get ( ) ; saveProperty ( p , Type . PROXY_HOST , pc . getHost ( ) ) ; saveProperty ( p , Type . PROXY_PORT , pc . getPort ( ) ) ; saveProperty ( p , Type . PROXY_USER , pc . getUser ( ) ) ; saveProperty ( p , Type . PROXY_PASSWORD , pc . getPassword ( ) ) ; saveProperty ( p , Type . PROXY_USESSL , pc . useSSL ( ) ) ; } saveProperty ( p , Type . RETRY_LIMIT , retryLimit ) ; saveProperty ( p , Type . RETRY_INITIAL_INTERVAL_MILLIS , retryInitialIntervalMillis ) ; saveProperty ( p , Type . RETRY_MAX_INTERVAL_MILLIS , retryMaxIntervalMillis ) ; saveProperty ( p , Type . RETRY_MULTIPLIER , retryMultiplier ) ; saveProperty ( p , Type . CONNECT_TIMEOUT_MILLIS , connectTimeoutMillis ) ; saveProperty ( p , Type . CONNECTION_POOL_SIZE , connectionPoolSize ) ; return p ; }
Output this configuration as a Properties object
40,080
public TDClient withApiKey ( String newApiKey ) { return new TDClient ( config , httpClient , Optional . of ( newApiKey ) ) ; }
Create a new TDClient that uses the given api key for the authentication . The new instance of TDClient shares the same HttpClient so closing this will invalidate the other copy of TDClient instances
40,081
private static TDClientHttpException clientError ( TDClientHttpException e , ResponseContext responseContext ) { boolean showWarning = true ; boolean showStackTrace = false ; int code = e . getStatusCode ( ) ; switch ( code ) { case HttpStatus . NOT_FOUND_404 : showWarning = false ; break ; case HttpStatus . CONFLICT_409 : showStackTrace = false ; break ; default : if ( ! ( HttpStatus . isClientError ( code ) || HttpStatus . isServerError ( code ) ) ) { showStackTrace = true ; } break ; } if ( showWarning ) { if ( showStackTrace ) { logger . warn ( e . getCause ( ) == null ? e . getMessage ( ) : e . getCause ( ) . getClass ( ) . toString ( ) , e ) ; } else { logger . warn ( e . getCause ( ) == null ? e . getMessage ( ) : e . getCause ( ) . getClass ( ) . toString ( ) ) ; } } return e ; }
Show or suppress warning messages for TDClientHttpException
40,082
public TDSaveQueryRequest merge ( TDSavedQuery base ) { return new TDSaveQueryRequest ( name . or ( base . getName ( ) ) , cron . or ( base . getCron ( ) ) , type . or ( base . getType ( ) ) , query . or ( base . getQuery ( ) ) , timezone . or ( base . getTimezone ( ) ) , delay . or ( base . getDelay ( ) ) , database . or ( base . getDatabase ( ) ) , priority . or ( base . getPriority ( ) ) , retryLimit . or ( base . getRetryLimit ( ) ) , result . or ( base . getResult ( ) ) , engineVersion . isPresent ( ) ? engineVersion . get ( ) : base . getEngineVersion ( ) ) ; }
Apply this update to the given TDSaveQuery objects and create a new TDSaveQueryRequest object .
40,083
public String getCmdOut ( ) { return debug . transform ( new Function < Debug , String > ( ) { public String apply ( Debug input ) { return input . getCmdout ( ) ; } } ) . or ( "" ) ; }
A short cut for reading cmdout message
40,084
public String getStdErr ( ) { return debug . transform ( new Function < Debug , String > ( ) { public String apply ( Debug input ) { return input . getStderr ( ) ; } } ) . or ( "" ) ; }
A short cut for reading stderr messsage
40,085
public TDClientConfig buildConfig ( ) { return new TDClientConfig ( endpoint , port , useSSL , apiKey , user , password , proxy , retryLimit , retryInitialIntervalMillis , retryMaxIntervalMillis , retryMultiplier , connectTimeoutMillis , readTimeoutMillis , connectionPoolSize , headers ) ; }
Build a config object .
40,086
public static String [ ] fastSplitKey ( String key ) { int i = key . indexOf ( ':' ) ; if ( - 1 == i ) { return new String [ ] { key } ; } else { int j = key . indexOf ( ':' , i + 1 ) ; if ( - 1 != j ) { return null ; } else { return new String [ ] { key . substring ( 0 , i ) , key . substring ( i + 1 ) } ; } } }
Java s string split is very expensive due to regexes . Implement our own simple version instead .
40,087
protected Kryo newKryoWithEx ( ) throws InstantiationException , IllegalAccessException { Kryo k = kryoClass . newInstance ( ) ; k . setInstantiatorStrategy ( instStratClass . newInstance ( ) ) ; k . setRegistrationRequired ( regRequired ) ; for ( IKryoRegistrar kr : registrations ) { kr . apply ( k ) ; } for ( IKryoRegistrar dkr : defaultRegistrations ) { dkr . apply ( k ) ; } return k ; }
This one adds expeption annotations that the interface does not have
40,088
public KryoInstantiator setClassLoader ( final ClassLoader cl ) { return new KryoInstantiator ( ) { public Kryo newKryo ( ) { Kryo k = KryoInstantiator . this . newKryo ( ) ; k . setClassLoader ( cl ) ; return k ; } } ; }
Use this to set a specific classloader
40,089
public KryoInstantiator setReferences ( final boolean ref ) { return new KryoInstantiator ( ) { public Kryo newKryo ( ) { Kryo k = KryoInstantiator . this . newKryo ( ) ; if ( k . getReferences ( ) != ref ) { k . setReferences ( ref ) ; } return k ; } } ; }
If true Kryo keeps a map of all the objects it has seen . this can use a ton of memory on hadoop but save serialization costs in some cases
40,090
public String get ( String key ) { Object value = conf . get ( key ) ; if ( null != value ) { return value . toString ( ) ; } else { return null ; } }
Return null if this key is undefined
40,091
public void writeOutputTo ( OutputStream os ) throws IOException { os . write ( output . getBuffer ( ) , 0 , output . position ( ) ) ; }
There for ByteArrayOutputStream cases this can be optimized
40,092
private static InputStream openResource ( final String file ) throws IOException { InputStream stream = HtmlConverterApplication . class . getResourceAsStream ( "/" + file ) ; if ( stream == null ) { throw new FileNotFoundException ( file ) ; } else { return stream ; } }
Opens a resource from classpath .
40,093
private static RuntimeDialect resolveDialect ( ) { if ( getJavaVersion ( ) >= MINIMUM_VERSION_MODERN_JAVA ) { return new ModernJavaRuntime ( ) ; } else if ( "Android Runtime" . equalsIgnoreCase ( System . getProperty ( "java.runtime.name" ) ) ) { return new AndroidRuntime ( ) ; } else { return new LegacyJavaRuntime ( ) ; } }
Resolves the runtime dialect for the current VM .
40,094
private static int getJavaVersion ( ) { String version = System . getProperty ( "java.version" ) ; if ( version == null ) { return - 1 ; } else { int index = version . indexOf ( '.' ) ; if ( index > 0 ) { version = version . substring ( 0 , index ) ; } try { return Integer . parseInt ( version ) ; } catch ( NumberFormatException ex ) { return - 1 ; } } }
Gets the major version number of Java .
40,095
private static String stripAnonymousPart ( final String className ) { for ( int index = className . indexOf ( "$" , 0 ) ; index != - 1 ; index = className . indexOf ( '$' , index + 2 ) ) { if ( index >= className . length ( ) - 1 ) { return className . substring ( 0 , index ) ; } char firstLetter = className . charAt ( index + 1 ) ; if ( firstLetter < 'A' || firstLetter > 'Z' ) { return className . substring ( 0 , index ) ; } } return className ; }
Strips the the anonymous part from a class name .
40,096
private static StackTraceElement normalizeClassName ( final StackTraceElement element ) { String className = element . getClassName ( ) ; int dollarIndex = className . indexOf ( "$" ) ; if ( dollarIndex == - 1 ) { return element ; } else { className = stripAnonymousPart ( className ) ; return new StackTraceElement ( className , element . getMethodName ( ) , element . getFileName ( ) , element . getLineNumber ( ) ) ; } }
Strips the the anonymous part from a class name of stack trace element .
40,097
protected String renderTag ( final LogEntry logEntry ) { StringBuilder builder = reuseOrCreate ( tagBuilder , TAG_MAX_LENGTH ) ; tagToken . render ( logEntry , builder ) ; if ( builder . length ( ) > TAG_MAX_LENGTH ) { return builder . substring ( 0 , TAG_MAX_LENGTH - ELLIPSIS . length ( ) ) + ELLIPSIS ; } else { return builder . toString ( ) ; } }
Renders the tag from a log entry .
40,098
protected String renderMessage ( final LogEntry logEntry ) { StringBuilder builder = reuseOrCreate ( messageBuilder , MESSAGE_BUILDER_CAPACITY ) ; messageToken . render ( logEntry , builder ) ; return builder . toString ( ) ; }
Renders the log message from a log entry .
40,099
private static boolean isCoveredByMinimumLevel ( final String tag , final Level level ) { return provider . getMinimumLevel ( tag ) . ordinal ( ) <= level . ordinal ( ) ; }
Checks if a given tag and severity level is covered by the logging provider s minimum level .