idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
25,900 | private List < Policy > aggregateContractPolicies ( ContractBean contractBean , EntityInfo clientInfo ) throws StorageException { List < Policy > policies = new ArrayList <> ( ) ; PolicyType [ ] types = new PolicyType [ ] { PolicyType . Client , PolicyType . Plan , PolicyType . Api } ; for ( PolicyType policyType : types ) { String org , id , ver ; switch ( policyType ) { case Client : { org = clientInfo . organizationId ; id = clientInfo . id ; ver = clientInfo . version ; break ; } case Plan : { org = contractBean . getApi ( ) . getApi ( ) . getOrganization ( ) . getId ( ) ; id = contractBean . getPlan ( ) . getPlan ( ) . getId ( ) ; ver = contractBean . getPlan ( ) . getVersion ( ) ; break ; } case Api : { org = contractBean . getApi ( ) . getApi ( ) . getOrganization ( ) . getId ( ) ; id = contractBean . getApi ( ) . getApi ( ) . getId ( ) ; ver = contractBean . getApi ( ) . getVersion ( ) ; break ; } default : { throw new RuntimeException ( "Missing case for switch!" ) ; //$NON-NLS-1$ } } Iterator < PolicyBean > clientPolicies = storage . getAllPolicies ( org , id , ver , policyType ) ; while ( clientPolicies . hasNext ( ) ) { PolicyBean policyBean = clientPolicies . next ( ) ; Policy policy = new Policy ( ) ; policy . setPolicyJsonConfig ( policyBean . getConfiguration ( ) ) ; policy . setPolicyImpl ( policyBean . getDefinition ( ) . getPolicyImpl ( ) ) ; policies . add ( policy ) ; } } return policies ; } | Aggregates the api client and plan policies into a single ordered list . | 420 | 15 |
25,901 | protected void doLoadFromClasspath ( String policyImpl , IAsyncResultHandler < IPolicy > handler ) { IPolicy rval ; String classname = policyImpl . substring ( 6 ) ; Class < ? > c = null ; // First try a simple Class.forName() try { c = Class . forName ( classname ) ; } catch ( ClassNotFoundException e ) { } // Didn't work? Try using this class's classloader. if ( c == null ) { try { c = getClass ( ) . getClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } // Still didn't work? Try the thread's context classloader. if ( c == null ) { try { c = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } if ( c == null ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( classname ) ) ) ; return ; } try { rval = ( IPolicy ) c . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl , e ) ) ) ; return ; } policyCache . put ( policyImpl , rval ) ; handler . handle ( AsyncResultImpl . create ( rval ) ) ; return ; } | Loads a policy from a class on the classpath . | 324 | 12 |
25,902 | private void doLoadFromPlugin ( final String policyImpl , final IAsyncResultHandler < IPolicy > handler ) { PluginCoordinates coordinates = PluginCoordinates . fromPolicySpec ( policyImpl ) ; if ( coordinates == null ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl ) ) ) ; return ; } int ssidx = policyImpl . indexOf ( ' ' ) ; if ( ssidx == - 1 ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl ) ) ) ; return ; } final String classname = policyImpl . substring ( ssidx + 1 ) ; this . pluginRegistry . loadPlugin ( coordinates , new IAsyncResultHandler < Plugin > ( ) { @ Override public void handle ( IAsyncResult < Plugin > result ) { if ( result . isSuccess ( ) ) { IPolicy rval ; Plugin plugin = result . getResult ( ) ; PluginClassLoader pluginClassLoader = plugin . getLoader ( ) ; ClassLoader oldCtxLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( pluginClassLoader ) ; Class < ? > c = pluginClassLoader . loadClass ( classname ) ; rval = ( IPolicy ) c . newInstance ( ) ; } catch ( Exception e ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl , e ) ) ) ; return ; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldCtxLoader ) ; } policyCache . put ( policyImpl , rval ) ; handler . handle ( AsyncResultImpl . create ( rval ) ) ; } else { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl , result . getError ( ) ) ) ) ; } } } ) ; } | Loads a policy from a plugin . | 432 | 8 |
25,903 | private < T > T unmarshalAs ( String valueAsString , Class < T > asClass ) throws IOException { return mapper . reader ( asClass ) . readValue ( valueAsString ) ; } | Unmarshall the given type of object . | 45 | 10 |
25,904 | protected void doApply ( ApiResponse response , IPolicyContext context , C config , IPolicyChain < ApiResponse > chain ) { chain . doApply ( response ) ; } | Apply the policy to the response . | 38 | 7 |
25,905 | protected void doProcessFailure ( PolicyFailure failure , IPolicyContext context , C config , IPolicyFailureChain chain ) { chain . doFailure ( failure ) ; } | Override if you wish to modify a failure . | 34 | 9 |
25,906 | protected SecurityHandler createSecurityHandler ( ) throws Exception { HashLoginService l = new HashLoginService ( ) ; // UserStore is now separate store entity and must be added to HashLoginService UserStore userStore = new UserStore ( ) ; l . setUserStore ( userStore ) ; for ( User user : Users . getUsers ( ) ) { userStore . addUser ( user . getId ( ) , Credential . getCredential ( user . getPassword ( ) ) , user . getRolesAsArray ( ) ) ; } l . setName ( "apimanrealm" ) ; ConstraintSecurityHandler csh = new ConstraintSecurityHandler ( ) ; csh . setAuthenticator ( new BasicAuthenticator ( ) ) ; csh . setRealmName ( "apimanrealm" ) ; csh . setLoginService ( l ) ; return csh ; } | Creates a basic auth security handler . | 191 | 8 |
25,907 | private static BucketSizeType bucketSizeFromInterval ( HistogramIntervalType interval ) { BucketSizeType bucketSize ; switch ( interval ) { case minute : bucketSize = BucketSizeType . Minute ; break ; case hour : bucketSize = BucketSizeType . Hour ; break ; case day : bucketSize = BucketSizeType . Day ; break ; case week : bucketSize = BucketSizeType . Week ; break ; case month : bucketSize = BucketSizeType . Month ; break ; default : bucketSize = BucketSizeType . Day ; break ; } return bucketSize ; } | Converts an interval into a bucket size . | 119 | 9 |
25,908 | @ SuppressWarnings ( "nls" ) private void doInit ( ) { QueryRunner run = new QueryRunner ( ds ) ; Boolean isInitialized ; try { isInitialized = run . query ( "SELECT * FROM gw_apis" , new ResultSetHandler < Boolean > ( ) { @ Override public Boolean handle ( ResultSet rs ) throws SQLException { return true ; } } ) ; } catch ( SQLException e ) { isInitialized = false ; } if ( isInitialized ) { System . out . println ( "============================================" ) ; System . out . println ( "Apiman Gateway database already initialized." ) ; System . out . println ( "============================================" ) ; return ; } ClassLoader cl = JdbcInitializer . class . getClassLoader ( ) ; URL resource = cl . getResource ( "ddls/apiman-gateway_" + dbType + ".ddl" ) ; try ( InputStream is = resource . openStream ( ) ) { System . out . println ( "=======================================" ) ; System . out . println ( "Initializing apiman Gateway database." ) ; DdlParser ddlParser = new DdlParser ( ) ; List < String > statements = ddlParser . parse ( is ) ; for ( String sql : statements ) { System . out . println ( sql ) ; run . update ( sql ) ; } System . out . println ( "=======================================" ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Do the initialization work . | 326 | 5 |
25,909 | private boolean satisfiesAnyPath ( IgnoredResourcesConfig config , String destination , String verb ) { if ( destination == null || destination . trim ( ) . length ( ) == 0 ) { destination = "/" ; //$NON-NLS-1$ } for ( IgnoredResource resource : config . getRules ( ) ) { String resourceVerb = resource . getVerb ( ) ; boolean verbMatches = verb == null || IgnoredResource . VERB_MATCH_ALL . equals ( resourceVerb ) || verb . equalsIgnoreCase ( resourceVerb ) ; // $NON-NLS-1$ boolean destinationMatches = destination . matches ( resource . getPathPattern ( ) ) ; if ( verbMatches && destinationMatches ) { return true ; } } return false ; } | Evaluates whether the destination provided matches any of the configured rules | 170 | 13 |
25,910 | private PublishingException readPublishingException ( HttpResponse response ) { InputStream is = null ; PublishingException exception ; try { is = response . getEntity ( ) . getContent ( ) ; GatewayApiErrorBean error = mapper . reader ( GatewayApiErrorBean . class ) . readValue ( is ) ; exception = new PublishingException ( error . getMessage ( ) ) ; StackTraceElement [ ] stack = parseStackTrace ( error . getStacktrace ( ) ) ; if ( stack != null ) { exception . setStackTrace ( stack ) ; } } catch ( Exception e ) { exception = new PublishingException ( e . getMessage ( ) , e ) ; } finally { IOUtils . closeQuietly ( is ) ; } return exception ; } | Reads a publishing exception from the response . | 167 | 9 |
25,911 | protected static StackTraceElement [ ] parseStackTrace ( String stacktrace ) { try ( BufferedReader reader = new BufferedReader ( new StringReader ( stacktrace ) ) ) { List < StackTraceElement > elements = new ArrayList <> ( ) ; String line ; // Example lines: // \tat io.apiman.gateway.engine.es.ESRegistry$1.completed(ESRegistry.java:79) // \tat org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81)\r\n while ( ( line = reader . readLine ( ) ) != null ) { if ( line . startsWith ( "\tat " ) ) { //$NON-NLS-1$ int openParenIdx = line . indexOf ( ' ' ) ; int closeParenIdx = line . indexOf ( ' ' ) ; String classAndMethod = line . substring ( 4 , openParenIdx ) ; String fileAndLineNum = line . substring ( openParenIdx + 1 , closeParenIdx ) ; String className = classAndMethod . substring ( 0 , classAndMethod . lastIndexOf ( ' ' ) ) ; String methodName = classAndMethod . substring ( classAndMethod . lastIndexOf ( ' ' ) + 1 ) ; String [ ] split = fileAndLineNum . split ( ":" ) ; //$NON-NLS-1$ if ( split . length == 1 ) { elements . add ( new StackTraceElement ( className , methodName , fileAndLineNum , - 1 ) ) ; } else { String fileName = split [ 0 ] ; String lineNum = split [ 1 ] ; elements . add ( new StackTraceElement ( className , methodName , fileName , new Integer ( lineNum ) ) ) ; } } } return elements . toArray ( new StackTraceElement [ elements . size ( ) ] ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } } | Parses a stack trace from the given string . | 460 | 11 |
25,912 | protected < T extends IComponent > void addComponent ( Class < T > componentType , T component ) { components . put ( componentType , component ) ; } | Adds a component to the registry . | 33 | 7 |
25,913 | public static final void main ( String [ ] args ) throws Exception { GatewayMicroService microService = new GatewayMicroService ( ) ; microService . start ( ) ; microService . join ( ) ; } | Main entry point for the API Gateway micro service . | 42 | 10 |
25,914 | @ Override public IApiConnector createConnector ( ApiRequest req , Api api , RequiredAuthType authType , boolean hasDataPolicy , IConnectorConfig connectorConfig ) { return ( request , resultHandler ) -> { // Apply options from config as our base case ApimanHttpConnectorOptions httpOptions = new ApimanHttpConnectorOptions ( config ) . setHasDataPolicy ( hasDataPolicy ) . setRequiredAuthType ( authType ) . setTlsOptions ( tlsOptions ) . setUri ( parseApiEndpoint ( api ) ) . setSsl ( api . getEndpoint ( ) . toLowerCase ( ) . startsWith ( "https" ) ) ; //$NON-NLS-1$ // If API has endpoint properties indicating timeouts, then override config. setAttributesFromApiEndpointProperties ( api , httpOptions ) ; // Get from cache HttpClient client = clientFromCache ( httpOptions ) ; return new HttpConnector ( vertx , client , request , api , httpOptions , connectorConfig , resultHandler ) . connect ( ) ; } ; } | In the future we can switch to different back - end implementations here! | 232 | 14 |
25,915 | private void setAttributesFromApiEndpointProperties ( Api api , ApimanHttpConnectorOptions options ) { try { Map < String , String > endpointProperties = api . getEndpointProperties ( ) ; if ( endpointProperties . containsKey ( "timeouts.read" ) ) { //$NON-NLS-1$ int connectTimeoutMs = Integer . parseInt ( endpointProperties . get ( "timeouts.read" ) ) ; //$NON-NLS-1$ options . setRequestTimeout ( connectTimeoutMs ) ; } if ( endpointProperties . containsKey ( "timeouts.connect" ) ) { //$NON-NLS-1$ int connectTimeoutMs = Integer . parseInt ( endpointProperties . get ( "timeouts.connect" ) ) ; //$NON-NLS-1$ options . setConnectionTimeout ( connectTimeoutMs ) ; } } catch ( NumberFormatException e ) { throw new RuntimeException ( e ) ; } } | If the endpoint properties includes a read timeout override then set it here . | 215 | 14 |
25,916 | public < T extends IComponent > T createAndRegisterComponent ( Class < T > componentType ) throws ComponentNotFoundException { try { synchronized ( components ) { Class < ? extends T > componentClass = engineConfig . getComponentClass ( componentType , pluginRegistry ) ; Map < String , String > componentConfig = engineConfig . getComponentConfig ( componentType ) ; T component = create ( componentClass , componentConfig ) ; components . put ( componentType , component ) ; // Because components are lazily created, we need to initialize them here // if necessary. DependsOnComponents annotation = componentClass . getAnnotation ( DependsOnComponents . class ) ; if ( annotation != null ) { Class < ? extends IComponent > [ ] value = annotation . value ( ) ; for ( Class < ? extends IComponent > theC : value ) { Method setter = ReflectionUtils . findSetter ( componentClass , theC ) ; if ( setter != null ) { IComponent injectedComponent = getComponent ( theC ) ; try { setter . invoke ( component , new Object [ ] { injectedComponent } ) ; } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; } } } } if ( component instanceof IRequiresInitialization ) { ( ( IRequiresInitialization ) component ) . initialize ( ) ; } return component ; } } catch ( Exception e ) { throw new ComponentNotFoundException ( componentType . getName ( ) ) ; } } | Creates the component and registers it in the registry . | 324 | 11 |
25,917 | protected void addComponentMapping ( Class < ? extends IComponent > klazz , IComponent component ) { components . put ( klazz , component ) ; } | Add a component that may have been instantiated elsewhere . | 35 | 11 |
25,918 | protected void registerRateLimiterComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + IRateLimiterComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , ESRateLimiterComponent . class . getName ( ) ) ; setConfigProperty ( componentPropName + ".client.type" , "jest" ) ; setConfigProperty ( componentPropName + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( componentPropName + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( componentPropName + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( componentPropName + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( componentPropName + ".client.password" , "${apiman.es.password}" ) ; } | The rate limiter component . | 213 | 6 |
25,919 | protected void registerSharedStateComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + ISharedStateComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , ESSharedStateComponent . class . getName ( ) ) ; setConfigProperty ( componentPropName + ".client.type" , "jest" ) ; setConfigProperty ( componentPropName + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( componentPropName + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( componentPropName + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( componentPropName + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( componentPropName + ".client.password" , "${apiman.es.password}" ) ; } | The shared state component . | 212 | 5 |
25,920 | protected void registerCacheStoreComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + ICacheStoreComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , ESCacheStoreComponent . class . getName ( ) ) ; setConfigProperty ( componentPropName + ".client.type" , "jest" ) ; setConfigProperty ( componentPropName + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( componentPropName + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( componentPropName + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( componentPropName + ".client.index" , "apiman_cache" ) ; setConfigProperty ( componentPropName + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( componentPropName + ".client.password" , "${apiman.es.password}" ) ; } | The cache store component . | 231 | 5 |
25,921 | protected void registerJdbcComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + IJdbcComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , DefaultJdbcComponent . class . getName ( ) ) ; } | The jdbc component . | 65 | 6 |
25,922 | protected void registerLdapComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + ILdapComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , DefaultLdapComponent . class . getName ( ) ) ; } | The ldap component . | 64 | 6 |
25,923 | protected void configureConnectorFactory ( ) { setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS , HttpConnectorFactory . class . getName ( ) ) ; setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS + ".http.timeouts.read" , "25" ) ; setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS + ".http.timeouts.write" , "25" ) ; setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS + ".http.timeouts.connect" , "10" ) ; setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS + ".http.followRedirects" , "true" ) ; } | The connector factory . | 173 | 4 |
25,924 | protected void configureRegistry ( ) { setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS , PollCachingESRegistry . class . getName ( ) ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.type" , "jest" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.password" , "${apiman.es.password}" ) ; } | The registry . | 228 | 3 |
25,925 | protected void configureMetrics ( ) { setConfigProperty ( GatewayConfigProperties . METRICS_CLASS , ESMetrics . class . getName ( ) ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.type" , "jest" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.password" , "${apiman.es.password}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.index" , "apiman_metrics" ) ; } | Configure the metrics system . | 255 | 6 |
25,926 | protected void setConfigProperty ( String propName , String propValue ) { if ( System . getProperty ( propName ) == null ) { System . setProperty ( propName , propValue ) ; } } | Sets a system property if it s not already set . | 43 | 12 |
25,927 | public boolean resetIfNecessary ( RateBucketPeriod period ) { long periodBoundary = getLastPeriodBoundary ( period ) ; if ( System . currentTimeMillis ( ) >= periodBoundary ) { setCount ( 0 ) ; return true ; } return false ; } | Resets the count if the period boundary has been crossed . Returns true if the count was reset to 0 or false otherwise . | 62 | 25 |
25,928 | public long getResetMillis ( RateBucketPeriod period ) { long now = System . currentTimeMillis ( ) ; long periodBoundary = getPeriodBoundary ( now , period ) ; return periodBoundary - now ; } | Returns the number of millis until the period resets . | 52 | 12 |
25,929 | private static long getPeriodBoundary ( long timestamp , RateBucketPeriod period ) { Calendar lastCal = Calendar . getInstance ( ) ; lastCal . setTimeInMillis ( timestamp ) ; switch ( period ) { case Second : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . add ( Calendar . SECOND , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Minute : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . add ( Calendar . MINUTE , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Hour : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . set ( Calendar . MINUTE , 0 ) ; lastCal . add ( Calendar . HOUR_OF_DAY , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Day : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . set ( Calendar . MINUTE , 0 ) ; lastCal . set ( Calendar . HOUR_OF_DAY , 0 ) ; lastCal . add ( Calendar . DAY_OF_YEAR , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Month : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . set ( Calendar . MINUTE , 0 ) ; lastCal . set ( Calendar . HOUR_OF_DAY , 0 ) ; lastCal . set ( Calendar . DAY_OF_MONTH , 1 ) ; lastCal . add ( Calendar . MONTH , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Year : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . set ( Calendar . MINUTE , 0 ) ; lastCal . set ( Calendar . HOUR_OF_DAY , 0 ) ; lastCal . set ( Calendar . DAY_OF_YEAR , 1 ) ; lastCal . add ( Calendar . YEAR , 1 ) ; return lastCal . getTimeInMillis ( ) ; } return Long . MAX_VALUE ; } | Gets the boundary timestamp for the given rate bucket period . In other words returns the timestamp associated with when the rate period will reset . | 524 | 27 |
25,930 | private PluginRegistryBean loadRegistry ( URI registryUrl ) { PluginRegistryBean fromCache = registryCache . get ( registryUrl ) ; if ( fromCache != null ) { return fromCache ; } try { PluginRegistryBean registry = mapper . reader ( PluginRegistryBean . class ) . readValue ( registryUrl . toURL ( ) ) ; registryCache . put ( registryUrl , registry ) ; return registry ; } catch ( IOException e ) { return null ; } } | Loads a plugin registry from its URL . Will use the value in the cache if it exists . If not it will connect to the remote URL and grab the registry JSON file . | 107 | 36 |
25,931 | public static final PoliciesBean from ( PolicyBean policy ) { PoliciesBean rval = new PoliciesBean ( ) ; rval . setType ( policy . getType ( ) ) ; rval . setOrganizationId ( policy . getOrganizationId ( ) ) ; rval . setEntityId ( policy . getEntityId ( ) ) ; rval . setEntityVersion ( policy . getEntityVersion ( ) ) ; rval . getPolicies ( ) . add ( policy ) ; return rval ; } | Create a new Policies object from the given policy bean instance . | 111 | 12 |
25,932 | public static VersionMigratorChain chain ( String fromVersion , String toVersion ) { List < IVersionMigrator > matchedMigrators = new ArrayList <> ( ) ; for ( Entry entry : migrators ) { if ( entry . isBetween ( fromVersion , toVersion ) ) { matchedMigrators . add ( entry . migrator ) ; } } return new VersionMigratorChain ( matchedMigrators ) ; } | Gets the chain of migrators to use when migrating from version X to version Y . | 93 | 18 |
25,933 | public void createTenant ( String tenantId ) { TenantBean tenant = new TenantBean ( tenantId ) ; try { URL endpoint = serverUrl . toURI ( ) . resolve ( "tenants" ) . toURL ( ) ; //$NON-NLS-1$ Request request = new Request . Builder ( ) . url ( endpoint ) . post ( toBody ( tenant ) ) . header ( "Hawkular-Tenant" , tenantId ) //$NON-NLS-1$ . build ( ) ; Response response = httpClient . newCall ( request ) . execute ( ) ; if ( response . code ( ) >= 400 ) { throw hawkularMetricsError ( response ) ; } } catch ( URISyntaxException | IOException e ) { throw new RuntimeException ( e ) ; } } | Creates a new tenant . | 178 | 6 |
25,934 | public List < MetricBean > listCounterMetrics ( String tenantId ) { try { URL endpoint = serverUrl . toURI ( ) . resolve ( "counters" ) . toURL ( ) ; //$NON-NLS-1$ Request request = new Request . Builder ( ) . url ( endpoint ) . header ( "Accept" , "application/json" ) //$NON-NLS-1$ //$NON-NLS-2$ . header ( "Hawkular-Tenant" , tenantId ) //$NON-NLS-1$ . build ( ) ; Response response = httpClient . newCall ( request ) . execute ( ) ; if ( response . code ( ) >= 400 ) { throw hawkularMetricsError ( response ) ; } if ( response . code ( ) == 204 ) { return Collections . EMPTY_LIST ; } String responseBody = response . body ( ) . string ( ) ; return readMapper . reader ( new TypeReference < List < MetricBean > > ( ) { } ) . readValue ( responseBody ) ; } catch ( URISyntaxException | IOException e ) { throw new RuntimeException ( e ) ; } } | Get a list of all counter metrics for a given tenant . | 259 | 12 |
25,935 | public DataPointLongBean addCounterDataPoint ( String tenantId , String counterId , Date timestamp , long value ) { List < DataPointLongBean > dataPoints = new ArrayList <> ( ) ; DataPointLongBean dataPoint = new DataPointLongBean ( timestamp , value ) ; dataPoints . add ( dataPoint ) ; addCounterDataPoints ( tenantId , counterId , dataPoints ) ; return dataPoint ; } | Adds a single data point to the given counter . | 94 | 10 |
25,936 | public void addMultipleCounterDataPoints ( String tenantId , List < MetricLongBean > data ) { try { URL endpoint = serverUrl . toURI ( ) . resolve ( "counters/raw" ) . toURL ( ) ; //$NON-NLS-1$ Request request = new Request . Builder ( ) . url ( endpoint ) . post ( toBody ( data ) ) . header ( "Hawkular-Tenant" , tenantId ) //$NON-NLS-1$ . build ( ) ; Response response = httpClient . newCall ( request ) . execute ( ) ; if ( response . code ( ) >= 400 ) { throw hawkularMetricsError ( response ) ; } } catch ( URISyntaxException | IOException e ) { throw new RuntimeException ( e ) ; } } | Adds one or more data points for multiple counters all at once! | 176 | 13 |
25,937 | public static Map < String , String > tags ( String ... strings ) { Map < String , String > tags = new HashMap <> ( ) ; for ( int i = 0 ; i < strings . length - 1 ; i += 2 ) { String key = strings [ i ] ; String value = strings [ i + 1 ] ; if ( key != null && value != null ) { tags . put ( key , value ) ; } } return tags ; } | Simple method to create some tags . | 95 | 7 |
25,938 | protected static String encodeTags ( Map < String , String > tags ) { if ( tags == null ) { return null ; } try { StringBuilder builder = new StringBuilder ( ) ; boolean first = true ; for ( Entry < String , String > entry : tags . entrySet ( ) ) { if ( ! first ) { builder . append ( ' ' ) ; } builder . append ( URLEncoder . encode ( entry . getKey ( ) , "UTF-8" ) ) ; //$NON-NLS-1$ builder . append ( ' ' ) ; builder . append ( URLEncoder . encode ( entry . getValue ( ) , "UTF-8" ) ) ; //$NON-NLS-1$ first = false ; } return builder . toString ( ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; return "" ; //$NON-NLS-1$ } } | Encodes the tags into the format expected by HM . | 204 | 11 |
25,939 | protected void startCacheInvalidator ( ) { polling = true ; Thread thread = new Thread ( new Runnable ( ) { @ Override public void run ( ) { // Wait for 30s on startup before starting to poll. try { Thread . sleep ( startupDelayMillis ) ; } catch ( InterruptedException e1 ) { e1 . printStackTrace ( ) ; } while ( polling ) { try { Thread . sleep ( pollIntervalMillis ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } checkCacheVersion ( ) ; } } } , "ESRegistryCacheInvalidator" ) ; //$NON-NLS-1$ thread . setDaemon ( true ) ; thread . start ( ) ; } | Starts up a thread that polls the ES store for updates . | 162 | 13 |
25,940 | public void chainPolicyHandlers ( ) { IReadWriteStream < H > previousHandler = null ; Iterator < PolicyWithConfiguration > iterator = iterator ( ) ; while ( iterator . hasNext ( ) ) { final PolicyWithConfiguration pwc = iterator . next ( ) ; final IPolicy policy = pwc . getPolicy ( ) ; final IReadWriteStream < H > handler = getApiHandler ( policy , pwc . getConfiguration ( ) ) ; if ( handler == null ) { continue ; } if ( headPolicyHandler == null ) { headPolicyHandler = handler ; } if ( previousHandler != null ) { previousHandler . bodyHandler ( new IAsyncHandler < IApimanBuffer > ( ) { @ Override public void handle ( IApimanBuffer result ) { handler . write ( result ) ; } } ) ; previousHandler . endHandler ( new IAsyncHandler < Void > ( ) { @ Override public void handle ( Void result ) { handler . end ( ) ; } } ) ; } previousHandler = handler ; } IReadWriteStream < H > tailPolicyHandler = previousHandler ; // If no policy handlers were found, then just make ourselves the head, // otherwise connect the last policy handler in the chain to ourselves // Leave the head and tail policy handlers null - the write() and end() methods // will deal with that case. if ( headPolicyHandler != null && tailPolicyHandler != null ) { tailPolicyHandler . bodyHandler ( new IAsyncHandler < IApimanBuffer > ( ) { @ Override public void handle ( IApimanBuffer chunk ) { handleBody ( chunk ) ; } } ) ; tailPolicyHandler . endHandler ( new IAsyncHandler < Void > ( ) { @ Override public void handle ( Void result ) { handleEnd ( ) ; } } ) ; } } | Chain together the body handlers . | 384 | 6 |
25,941 | public static KeyManager [ ] getKeyManagers ( Info pathInfo ) throws Exception { if ( pathInfo . store == null ) { return null ; } File clientKeyStoreFile = new File ( pathInfo . store ) ; if ( ! clientKeyStoreFile . isFile ( ) ) { throw new Exception ( "No KeyManager: " + pathInfo . store + " does not exist or is not a file." ) ; } String clientKeyStorePassword = pathInfo . password ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; KeyStore keyStore = KeyStore . getInstance ( "JKS" ) ; FileInputStream clientFis = new FileInputStream ( pathInfo . store ) ; keyStore . load ( clientFis , clientKeyStorePassword . toCharArray ( ) ) ; clientFis . close ( ) ; kmf . init ( keyStore , clientKeyStorePassword . toCharArray ( ) ) ; return kmf . getKeyManagers ( ) ; } | Gets the array of key managers for a given info store + info . | 222 | 15 |
25,942 | public static TrustManager [ ] getTrustManagers ( Info pathInfo ) throws Exception { File trustStoreFile = new File ( pathInfo . store ) ; if ( ! trustStoreFile . isFile ( ) ) { throw new Exception ( "No TrustManager: " + pathInfo . store + " does not exist." ) ; } String trustStorePassword = pathInfo . password ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; KeyStore truststore = KeyStore . getInstance ( "JKS" ) ; FileInputStream fis = new FileInputStream ( pathInfo . store ) ; truststore . load ( fis , trustStorePassword . toCharArray ( ) ) ; fis . close ( ) ; tmf . init ( truststore ) ; return tmf . getTrustManagers ( ) ; } | Gets an array of trust managers for a given store + password . | 188 | 14 |
25,943 | private void popLastItem ( ) { KeyValue < K , V > lastKV = items . last ( ) ; items . remove ( lastKV ) ; index . remove ( lastKV . key ) ; } | Removes the last item in the list . | 46 | 9 |
25,944 | private void validateCredentials ( String username , String password , ApiRequest request , IPolicyContext context , BasicAuthenticationConfig config , IAsyncResultHandler < Boolean > handler ) { if ( config . getStaticIdentity ( ) != null ) { staticIdentityValidator . validate ( username , password , request , context , config . getStaticIdentity ( ) , handler ) ; } else if ( config . getLdapIdentity ( ) != null ) { ldapIdentityValidator . validate ( username , password , request , context , config . getLdapIdentity ( ) , handler ) ; } else if ( config . getJdbcIdentity ( ) != null ) { jdbcIdentityValidator . validate ( username , password , request , context , config . getJdbcIdentity ( ) , handler ) ; } else { handler . handle ( AsyncResultImpl . create ( Boolean . FALSE ) ) ; } } | Validate the inbound authentication credentials . | 203 | 8 |
25,945 | protected void sendAuthFailure ( IPolicyContext context , IPolicyChain < ? > chain , BasicAuthenticationConfig config , int reason ) { IPolicyFailureFactoryComponent pff = context . getComponent ( IPolicyFailureFactoryComponent . class ) ; PolicyFailure failure = pff . createFailure ( PolicyFailureType . Authentication , reason , Messages . i18n . format ( "BasicAuthenticationPolicy.AuthenticationFailed" ) ) ; //$NON-NLS-1$ String realm = config . getRealm ( ) ; if ( realm == null || realm . trim ( ) . isEmpty ( ) ) { realm = "Apiman" ; //$NON-NLS-1$ } failure . getHeaders ( ) . put ( "WWW-Authenticate" , String . format ( "Basic realm=\"%1$s\"" , realm ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ chain . doFailure ( failure ) ; } | Sends the unauthenticated response as a policy failure . | 214 | 12 |
25,946 | private String getApiIdx ( String orgId , String apiId , String version ) { return "API::" + orgId + "|" + apiId + "|" + version ; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } | Generates an in - memory key for an API used to index the app for later quick retrieval . | 73 | 20 |
25,947 | protected void unregisterApiContracts ( Client client , Connection connection ) throws SQLException { QueryRunner run = new QueryRunner ( ) ; run . update ( connection , "DELETE FROM contracts WHERE client_org_id = ? AND client_id = ? AND client_version = ?" , //$NON-NLS-1$ client . getOrganizationId ( ) , client . getClientId ( ) , client . getVersion ( ) ) ; } | Removes all of the api contracts from the database . | 101 | 11 |
25,948 | protected Api getApiInternal ( String organizationId , String apiId , String apiVersion ) throws SQLException { QueryRunner run = new QueryRunner ( ds ) ; return run . query ( "SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?" , //$NON-NLS-1$ Handlers . API_HANDLER , organizationId , apiId , apiVersion ) ; } | Gets an api from the DB . | 98 | 8 |
25,949 | protected Client getClientInternal ( String apiKey ) throws SQLException { QueryRunner run = new QueryRunner ( ds ) ; return run . query ( "SELECT bean FROM gw_clients WHERE api_key = ?" , //$NON-NLS-1$ Handlers . CLIENT_HANDLER , apiKey ) ; } | Simply pull the client from storage . | 74 | 7 |
25,950 | protected void doBasicAuth ( Creds credentials , HttpServletRequest request , HttpServletResponse response , FilterChain chain ) throws IOException , ServletException { try { if ( credentials . username . equals ( request . getRemoteUser ( ) ) ) { // Already logged in as this user - do nothing. This can happen // in some app servers if the app server processes the BASIC auth // credentials before this filter gets a crack at them. WildFly 8 // works this way, for example (despite the web.xml not specifying // any login config!). } else if ( request . getRemoteUser ( ) != null ) { // switch user request . logout ( ) ; request . login ( credentials . username , credentials . password ) ; } else { request . login ( credentials . username , credentials . password ) ; } } catch ( Exception e ) { // TODO log this error? e . printStackTrace ( ) ; sendAuthResponse ( response ) ; return ; } doFilterChain ( request , response , chain , null ) ; } | Handle BASIC authentication . Delegates this to the container by invoking login on the inbound http servlet request object . | 221 | 24 |
25,951 | protected void doFilterChain ( ServletRequest request , ServletResponse response , FilterChain chain , AuthPrincipal principal ) throws IOException , ServletException { if ( principal == null ) { chain . doFilter ( request , response ) ; } else { HttpServletRequest hsr ; hsr = wrapTheRequest ( request , principal ) ; chain . doFilter ( hsr , response ) ; } } | Further process the filter chain . | 86 | 6 |
25,952 | private HttpServletRequest wrapTheRequest ( final ServletRequest request , final AuthPrincipal principal ) { HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper ( ( HttpServletRequest ) request ) { @ Override public Principal getUserPrincipal ( ) { return principal ; } @ Override public boolean isUserInRole ( String role ) { return principal . getRoles ( ) . contains ( role ) ; } @ Override public String getRemoteUser ( ) { return principal . getName ( ) ; } } ; return wrapper ; } | Wrap the request to provide the principal . | 122 | 9 |
25,953 | private Creds parseAuthorizationBasic ( String authHeader ) { String userpassEncoded = authHeader . substring ( 6 ) ; String data = StringUtils . newStringUtf8 ( Base64 . decodeBase64 ( userpassEncoded ) ) ; int sepIdx = data . indexOf ( ' ' ) ; if ( sepIdx > 0 ) { String username = data . substring ( 0 , sepIdx ) ; String password = data . substring ( sepIdx + 1 ) ; return new Creds ( username , password ) ; } else { return new Creds ( data , null ) ; } } | Parses the Authorization request header into a username and password . | 136 | 13 |
25,954 | private AuthToken parseAuthorizationToken ( String authHeader ) { try { String tokenEncoded = authHeader . substring ( 11 ) ; return AuthTokenUtil . consumeToken ( tokenEncoded ) ; } catch ( IllegalArgumentException e ) { // TODO log this error return null ; } } | Parses the Authorization request to retrieve the Base64 encoded auth token . | 64 | 15 |
25,955 | private void sendAuthResponse ( HttpServletResponse response ) throws IOException { response . setHeader ( "WWW-Authenticate" , String . format ( "Basic realm=\"%1$s\"" , realm ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ response . sendError ( HttpServletResponse . SC_UNAUTHORIZED ) ; } | Sends a response that tells the client that authentication is required . | 91 | 13 |
25,956 | private void replaceHeaders ( URLRewritingConfig config , HeaderMap headers ) { for ( Entry < String , String > entry : headers ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; value = doHeaderReplaceAll ( value , config . getFromRegex ( ) , config . getToReplacement ( ) ) ; if ( value != null ) { headers . put ( key , value ) ; } } } | Perform replacement . | 99 | 4 |
25,957 | private String doHeaderReplaceAll ( String headerValue , String fromRegex , String toReplacement ) { return headerValue . replaceAll ( fromRegex , toReplacement ) ; } | Finds all matching instances of the regular expression and replaces them with the replacement value . | 40 | 17 |
25,958 | protected JestClient createJestClient ( Map < String , String > config , String indexName , String defaultIndexName ) { String host = config . get ( "client.host" ) ; //$NON-NLS-1$ String port = config . get ( "client.port" ) ; //$NON-NLS-1$ String protocol = config . get ( "client.protocol" ) ; //$NON-NLS-1$ String initialize = config . get ( "client.initialize" ) ; //$NON-NLS-1$ if ( initialize == null ) { initialize = "true" ; //$NON-NLS-1$ } if ( StringUtils . isBlank ( host ) ) { throw new RuntimeException ( "Missing client.host configuration for ESRegistry." ) ; //$NON-NLS-1$ } if ( StringUtils . isBlank ( port ) ) { throw new RuntimeException ( "Missing client.port configuration for ESRegistry." ) ; //$NON-NLS-1$ } if ( StringUtils . isBlank ( protocol ) ) { protocol = "http" ; //$NON-NLS-1$ } String clientKey = "jest:" + host + ' ' + port + ' ' + indexName ; //$NON-NLS-1$ synchronized ( clients ) { if ( clients . containsKey ( clientKey ) ) { return clients . get ( clientKey ) ; } else { StringBuilder builder = new StringBuilder ( ) ; builder . append ( protocol ) ; builder . append ( "://" ) ; //$NON-NLS-1$ builder . append ( host ) ; builder . append ( ":" ) ; //$NON-NLS-1$ builder . append ( String . valueOf ( port ) ) ; String connectionUrl = builder . toString ( ) ; JestClientFactory factory = new JestClientFactory ( ) ; Builder httpClientConfig = new HttpClientConfig . Builder ( connectionUrl ) ; updateHttpConfig ( httpClientConfig , config ) ; factory . setHttpClientConfig ( httpClientConfig . build ( ) ) ; updateJestClientFactory ( factory , config ) ; JestClient client = factory . getObject ( ) ; clients . put ( clientKey , client ) ; if ( "true" . equals ( initialize ) ) { //$NON-NLS-1$ initializeClient ( client , indexName , defaultIndexName ) ; } return client ; } } } | Creates a transport client from a configuration map . | 545 | 10 |
25,959 | protected void updateHttpConfig ( Builder httpClientConfig , Map < String , String > config ) { String username = config . get ( "client.username" ) ; //$NON-NLS-1$ String password = config . get ( "client.password" ) ; //$NON-NLS-1$ String timeout = config . get ( "client.timeout" ) ; //$NON-NLS-1$ if ( StringUtils . isBlank ( timeout ) ) { timeout = "10000" ; //$NON-NLS-1$ } httpClientConfig . connTimeout ( new Integer ( timeout ) ) . readTimeout ( new Integer ( timeout ) ) . maxTotalConnection ( 75 ) . defaultMaxTotalConnectionPerRoute ( 75 ) . multiThreaded ( true ) ; if ( ! StringUtils . isBlank ( username ) ) { httpClientConfig . defaultCredentials ( username , password ) ; } if ( "https" . equals ( config . get ( "protocol" ) ) ) { //$NON-NLS-1$ //$NON-NLS-2$ updateSslConfig ( httpClientConfig , config ) ; } } | Update the http client config . | 255 | 6 |
25,960 | private void orderPolicies ( PoliciesBean policies ) { int idx = 1 ; for ( PolicyBean policy : policies . getPolicies ( ) ) { policy . setOrderIndex ( idx ++ ) ; } } | Set the order index of all policies . | 49 | 8 |
25,961 | private Map < String , Object > getEntity ( String type , String id ) throws StorageException { try { JestResult response = esClient . execute ( new Get . Builder ( getIndexName ( ) , id ) . type ( type ) . build ( ) ) ; if ( ! response . isSucceeded ( ) ) { return null ; } return response . getSourceAsObject ( Map . class ) ; } catch ( Exception e ) { throw new StorageException ( e ) ; } } | Gets an entity . Callers must unmarshal the resulting map . | 104 | 15 |
25,962 | private List < Hit < Map < String , Object > , Void > > listEntities ( String type , SearchSourceBuilder searchSourceBuilder ) throws StorageException { try { String query = searchSourceBuilder . string ( ) ; Search search = new Search . Builder ( query ) . addIndex ( getIndexName ( ) ) . addType ( type ) . build ( ) ; SearchResult response = esClient . execute ( search ) ; @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) List < Hit < Map < String , Object > , Void > > thehits = ( List ) response . getHits ( Map . class ) ; return thehits ; } catch ( Exception e ) { throw new StorageException ( e ) ; } } | Returns a list of entities . | 162 | 6 |
25,963 | private void deleteEntity ( String type , String id ) throws StorageException { try { JestResult response = esClient . execute ( new Delete . Builder ( id ) . index ( getIndexName ( ) ) . type ( type ) . build ( ) ) ; if ( ! response . isSucceeded ( ) ) { throw new StorageException ( "Document could not be deleted because it did not exist:" + response . getErrorMessage ( ) ) ; //$NON-NLS-1$ } } catch ( StorageException e ) { throw e ; } catch ( Exception e ) { throw new StorageException ( e ) ; } } | Deletes an entity . | 134 | 5 |
25,964 | private void updateEntity ( String type , String id , XContentBuilder source ) throws StorageException { try { String doc = source . string ( ) ; /* JestResult response = */ esClient . execute ( new Index . Builder ( doc ) . setParameter ( Parameters . OP_TYPE , "index" ) . index ( getIndexName ( ) ) . type ( type ) . id ( id ) . build ( ) ) ; //$NON-NLS-1$ } catch ( Exception e ) { throw new StorageException ( e ) ; } } | Updates a single entity . | 116 | 6 |
25,965 | private static String getPoliciesDocType ( PolicyType type ) { String docType = "planPolicies" ; //$NON-NLS-1$ if ( type == PolicyType . Api ) { docType = "apiPolicies" ; //$NON-NLS-1$ } else if ( type == PolicyType . Client ) { docType = "clientPolicies" ; //$NON-NLS-1$ } return docType ; } | Returns the policies document type to use given the policy type . | 105 | 12 |
25,966 | private static String id ( String organizationId , String entityId , String version ) { return organizationId + ' ' + entityId + ' ' + version ; } | A composite ID created from an organization ID entity ID and version . | 33 | 13 |
25,967 | private < T > Iterator < T > getAll ( String entityType , IUnmarshaller < T > unmarshaller ) throws StorageException { String query = matchAllQuery ( ) ; return getAll ( entityType , unmarshaller , query ) ; } | Returns an iterator over all instances of the given entity type . | 59 | 12 |
25,968 | private boolean hasOriginHeader ( HttpServletRequest httpReq ) { String origin = httpReq . getHeader ( "Origin" ) ; //$NON-NLS-1$ return origin != null && origin . trim ( ) . length ( ) > 0 ; } | Returns true if the Origin request header is present . | 59 | 10 |
25,969 | public static AuthHandler getAuth ( Vertx vertx , Router router , VertxEngineConfig apimanConfig ) { String type = apimanConfig . getAuth ( ) . getString ( "type" , "NONE" ) ; JsonObject authConfig = apimanConfig . getAuth ( ) . getJsonObject ( "config" , new JsonObject ( ) ) ; switch ( AuthType . getType ( type ) ) { case BASIC : return BasicAuth . create ( authConfig ) ; case NONE : return NoneAuth . create ( ) ; case KEYCLOAK : return KeycloakOAuthFactory . create ( vertx , router , apimanConfig , authConfig ) ; default : return NoneAuth . create ( ) ; } } | Creates an auth handler of the type indicated in the auth section of config . | 160 | 16 |
25,970 | public Session createSession ( ) throws OpenViduJavaClientException , OpenViduHttpException { Session s = new Session ( ) ; OpenVidu . activeSessions . put ( s . getSessionId ( ) , s ) ; return s ; } | Creates an OpenVidu session with the default settings | 56 | 12 |
25,971 | public Recording getRecording ( String recordingId ) throws OpenViduJavaClientException , OpenViduHttpException { HttpGet request = new HttpGet ( OpenVidu . urlOpenViduServer + API_RECORDINGS + "/" + recordingId ) ; HttpResponse response ; try { response = OpenVidu . httpClient . execute ( request ) ; } catch ( IOException e ) { throw new OpenViduJavaClientException ( e . getMessage ( ) , e . getCause ( ) ) ; } try { int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( ( statusCode == org . apache . http . HttpStatus . SC_OK ) ) { return new Recording ( httpResponseToJson ( response ) ) ; } else { throw new OpenViduHttpException ( statusCode ) ; } } finally { EntityUtils . consumeQuietly ( response . getEntity ( ) ) ; } } | Gets an existing recording | 213 | 5 |
25,972 | @ SuppressWarnings ( "unchecked" ) public List < Recording > listRecordings ( ) throws OpenViduJavaClientException , OpenViduHttpException { HttpGet request = new HttpGet ( OpenVidu . urlOpenViduServer + API_RECORDINGS ) ; HttpResponse response ; try { response = OpenVidu . httpClient . execute ( request ) ; } catch ( IOException e ) { throw new OpenViduJavaClientException ( e . getMessage ( ) , e . getCause ( ) ) ; } try { int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( ( statusCode == org . apache . http . HttpStatus . SC_OK ) ) { List < Recording > recordings = new ArrayList <> ( ) ; JSONObject json = httpResponseToJson ( response ) ; JSONArray array = ( JSONArray ) json . get ( "items" ) ; array . forEach ( item -> { recordings . add ( new Recording ( ( JSONObject ) item ) ) ; } ) ; return recordings ; } else { throw new OpenViduHttpException ( statusCode ) ; } } finally { EntityUtils . consumeQuietly ( response . getEntity ( ) ) ; } } | Lists all existing recordings | 278 | 5 |
25,973 | public void createSession ( Session sessionNotActive , KurentoClientSessionInfo kcSessionInfo ) throws OpenViduException { String sessionId = kcSessionInfo . getRoomName ( ) ; KurentoSession session = ( KurentoSession ) sessions . get ( sessionId ) ; if ( session != null ) { throw new OpenViduException ( Code . ROOM_CANNOT_BE_CREATED_ERROR_CODE , "Session '" + sessionId + "' already exists" ) ; } this . kurentoClient = kcProvider . getKurentoClient ( kcSessionInfo ) ; session = new KurentoSession ( sessionNotActive , kurentoClient , kurentoSessionEventsHandler , kurentoEndpointConfig , kcProvider . destroyWhenUnused ( ) ) ; KurentoSession oldSession = ( KurentoSession ) sessions . putIfAbsent ( sessionId , session ) ; if ( oldSession != null ) { log . warn ( "Session '{}' has just been created by another thread" , sessionId ) ; return ; } String kcName = "[NAME NOT AVAILABLE]" ; if ( kurentoClient . getServerManager ( ) != null ) { kcName = kurentoClient . getServerManager ( ) . getName ( ) ; } log . warn ( "No session '{}' exists yet. Created one using KurentoClient '{}'." , sessionId , kcName ) ; sessionEventsHandler . onSessionCreated ( session ) ; } | Creates a session if it doesn t already exist . The session s id will be indicated by the session info bean . | 348 | 24 |
25,974 | protected void unregisterElementErrListener ( MediaElement element , final ListenerSubscription subscription ) { if ( element == null || subscription == null ) { return ; } element . removeErrorListener ( subscription ) ; } | Unregisters the error listener from the media element using the provided subscription . | 45 | 15 |
25,975 | public Set < Participant > getParticipants ( String sessionId ) throws OpenViduException { Session session = sessions . get ( sessionId ) ; if ( session == null ) { throw new OpenViduException ( Code . ROOM_NOT_FOUND_ERROR_CODE , "Session '" + sessionId + "' not found" ) ; } Set < Participant > participants = session . getParticipants ( ) ; participants . removeIf ( p -> p . isClosed ( ) ) ; return participants ; } | Returns all the participants inside a session . | 110 | 8 |
25,976 | public Participant getParticipant ( String sessionId , String participantPrivateId ) throws OpenViduException { Session session = sessions . get ( sessionId ) ; if ( session == null ) { throw new OpenViduException ( Code . ROOM_NOT_FOUND_ERROR_CODE , "Session '" + sessionId + "' not found" ) ; } Participant participant = session . getParticipantByPrivateId ( participantPrivateId ) ; if ( participant == null ) { throw new OpenViduException ( Code . USER_NOT_FOUND_ERROR_CODE , "Participant '" + participantPrivateId + "' not found in session '" + sessionId + "'" ) ; } return participant ; } | Returns a participant in a session | 155 | 6 |
25,977 | public Participant getParticipant ( String participantPrivateId ) throws OpenViduException { for ( Session session : sessions . values ( ) ) { if ( ! session . isClosed ( ) ) { if ( session . getParticipantByPrivateId ( participantPrivateId ) != null ) { return session . getParticipantByPrivateId ( participantPrivateId ) ; } } } throw new OpenViduException ( Code . USER_NOT_FOUND_ERROR_CODE , "No participant with private id '" + participantPrivateId + "' was found" ) ; } | Returns a participant | 122 | 3 |
25,978 | protected void updateRecordingManagerCollections ( Session session , Recording recording ) { this . recordingManager . sessionHandler . setRecordingStarted ( session . getSessionId ( ) , recording ) ; this . recordingManager . sessionsRecordings . put ( session . getSessionId ( ) , recording ) ; this . recordingManager . startingRecordings . remove ( recording . getId ( ) ) ; this . recordingManager . startedRecordings . put ( recording . getId ( ) , recording ) ; } | Changes recording from starting to started updates global recording collections and sends RPC response to clients | 104 | 16 |
25,979 | protected void sendRecordingStartedNotification ( Session session , Recording recording ) { this . recordingManager . getSessionEventsHandler ( ) . sendRecordingStartedNotification ( session , recording ) ; } | Sends RPC response for recording started event | 43 | 8 |
25,980 | public Notification getNotification ( ) { try { Notification notif = notifications . take ( ) ; log . debug ( "Dequeued notification {}" , notif ) ; return notif ; } catch ( InterruptedException e ) { log . info ( "Interrupted while polling notifications' queue" ) ; return null ; } } | Blocks until an element is available and then returns it by removing it from the queue . | 69 | 17 |
25,981 | public ServiceCall < SessionResponse > createSession ( CreateSessionOptions createSessionOptions ) { Validator . notNull ( createSessionOptions , "createSessionOptions cannot be null" ) ; String [ ] pathSegments = { "v2/assistants" , "sessions" } ; String [ ] pathParameters = { createSessionOptions . assistantId ( ) } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "conversation" , "v2" , "createSession" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( SessionResponse . class ) ) ; } | Create a session . | 244 | 4 |
25,982 | public ServiceCall < Void > deleteSession ( DeleteSessionOptions deleteSessionOptions ) { Validator . notNull ( deleteSessionOptions , "deleteSessionOptions cannot be null" ) ; String [ ] pathSegments = { "v2/assistants" , "sessions" } ; String [ ] pathParameters = { deleteSessionOptions . assistantId ( ) , deleteSessionOptions . sessionId ( ) } ; RequestBuilder builder = RequestBuilder . delete ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "conversation" , "v2" , "deleteSession" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getVoid ( ) ) ; } | Delete session . | 249 | 3 |
25,983 | public ServiceCall < MessageResponse > message ( MessageOptions messageOptions ) { Validator . notNull ( messageOptions , "messageOptions cannot be null" ) ; String [ ] pathSegments = { "v2/assistants" , "sessions" , "message" } ; String [ ] pathParameters = { messageOptions . assistantId ( ) , messageOptions . sessionId ( ) } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "conversation" , "v2" , "message" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; final JsonObject contentJson = new JsonObject ( ) ; if ( messageOptions . input ( ) != null ) { contentJson . add ( "input" , GsonSingleton . getGson ( ) . toJsonTree ( messageOptions . input ( ) ) ) ; } if ( messageOptions . context ( ) != null ) { contentJson . add ( "context" , GsonSingleton . getGson ( ) . toJsonTree ( messageOptions . context ( ) ) ) ; } builder . bodyJson ( contentJson ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( MessageResponse . class ) ) ; } | Send user input to assistant . | 371 | 6 |
25,984 | public ServiceCall < IdentifiedLanguages > identify ( IdentifyOptions identifyOptions ) { Validator . notNull ( identifyOptions , "identifyOptions cannot be null" ) ; String [ ] pathSegments = { "v3/identify" } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "language_translator" , "v3" , "identify" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; builder . bodyContent ( identifyOptions . text ( ) , "text/plain" ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( IdentifiedLanguages . class ) ) ; } | Identify language . | 237 | 4 |
25,985 | public ServiceCall < IdentifiableLanguages > listIdentifiableLanguages ( ListIdentifiableLanguagesOptions listIdentifiableLanguagesOptions ) { String [ ] pathSegments = { "v3/identifiable_languages" } ; RequestBuilder builder = RequestBuilder . get ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "language_translator" , "v3" , "listIdentifiableLanguages" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( listIdentifiableLanguagesOptions != null ) { } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( IdentifiableLanguages . class ) ) ; } | List identifiable languages . | 231 | 4 |
25,986 | public ServiceCall < TranslationModel > createModel ( CreateModelOptions createModelOptions ) { Validator . notNull ( createModelOptions , "createModelOptions cannot be null" ) ; Validator . isTrue ( ( createModelOptions . forcedGlossary ( ) != null ) || ( createModelOptions . parallelCorpus ( ) != null ) , "At least one of forcedGlossary or parallelCorpus must be supplied." ) ; String [ ] pathSegments = { "v3/models" } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "language_translator" , "v3" , "createModel" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; builder . query ( "base_model_id" , createModelOptions . baseModelId ( ) ) ; if ( createModelOptions . name ( ) != null ) { builder . query ( "name" , createModelOptions . name ( ) ) ; } MultipartBody . Builder multipartBuilder = new MultipartBody . Builder ( ) ; multipartBuilder . setType ( MultipartBody . FORM ) ; if ( createModelOptions . forcedGlossary ( ) != null ) { RequestBody forcedGlossaryBody = RequestUtils . inputStreamBody ( createModelOptions . forcedGlossary ( ) , "application/octet-stream" ) ; multipartBuilder . addFormDataPart ( "forced_glossary" , "filename" , forcedGlossaryBody ) ; } if ( createModelOptions . parallelCorpus ( ) != null ) { RequestBody parallelCorpusBody = RequestUtils . inputStreamBody ( createModelOptions . parallelCorpus ( ) , "application/octet-stream" ) ; multipartBuilder . addFormDataPart ( "parallel_corpus" , "filename" , parallelCorpusBody ) ; } builder . body ( multipartBuilder . build ( ) ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( TranslationModel . class ) ) ; } | Create model . | 535 | 3 |
25,987 | public ServiceCall < HTMLReturn > convertToHtml ( ConvertToHtmlOptions convertToHtmlOptions ) { Validator . notNull ( convertToHtmlOptions , "convertToHtmlOptions cannot be null" ) ; String [ ] pathSegments = { "v1/html_conversion" } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "convertToHtml" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( convertToHtmlOptions . model ( ) != null ) { builder . query ( "model" , convertToHtmlOptions . model ( ) ) ; } MultipartBody . Builder multipartBuilder = new MultipartBody . Builder ( ) ; multipartBuilder . setType ( MultipartBody . FORM ) ; RequestBody fileBody = RequestUtils . inputStreamBody ( convertToHtmlOptions . file ( ) , convertToHtmlOptions . fileContentType ( ) ) ; multipartBuilder . addFormDataPart ( "file" , convertToHtmlOptions . filename ( ) , fileBody ) ; builder . body ( multipartBuilder . build ( ) ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( HTMLReturn . class ) ) ; } | Convert document to HTML . | 382 | 6 |
25,988 | public ServiceCall < CompareReturn > compareDocuments ( CompareDocumentsOptions compareDocumentsOptions ) { Validator . notNull ( compareDocumentsOptions , "compareDocumentsOptions cannot be null" ) ; String [ ] pathSegments = { "v1/comparison" } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "compareDocuments" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( compareDocumentsOptions . file1Label ( ) != null ) { builder . query ( "file_1_label" , compareDocumentsOptions . file1Label ( ) ) ; } if ( compareDocumentsOptions . file2Label ( ) != null ) { builder . query ( "file_2_label" , compareDocumentsOptions . file2Label ( ) ) ; } if ( compareDocumentsOptions . model ( ) != null ) { builder . query ( "model" , compareDocumentsOptions . model ( ) ) ; } MultipartBody . Builder multipartBuilder = new MultipartBody . Builder ( ) ; multipartBuilder . setType ( MultipartBody . FORM ) ; RequestBody file1Body = RequestUtils . inputStreamBody ( compareDocumentsOptions . file1 ( ) , compareDocumentsOptions . file1ContentType ( ) ) ; multipartBuilder . addFormDataPart ( "file_1" , "filename" , file1Body ) ; RequestBody file2Body = RequestUtils . inputStreamBody ( compareDocumentsOptions . file2 ( ) , compareDocumentsOptions . file2ContentType ( ) ) ; multipartBuilder . addFormDataPart ( "file_2" , "filename" , file2Body ) ; builder . body ( multipartBuilder . build ( ) ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( CompareReturn . class ) ) ; } | Compare two documents . | 498 | 4 |
25,989 | public ServiceCall < FeedbackReturn > addFeedback ( AddFeedbackOptions addFeedbackOptions ) { Validator . notNull ( addFeedbackOptions , "addFeedbackOptions cannot be null" ) ; String [ ] pathSegments = { "v1/feedback" } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "addFeedback" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; final JsonObject contentJson = new JsonObject ( ) ; contentJson . add ( "feedback_data" , GsonSingleton . getGson ( ) . toJsonTree ( addFeedbackOptions . feedbackData ( ) ) ) ; if ( addFeedbackOptions . userId ( ) != null ) { contentJson . addProperty ( "user_id" , addFeedbackOptions . userId ( ) ) ; } if ( addFeedbackOptions . comment ( ) != null ) { contentJson . addProperty ( "comment" , addFeedbackOptions . comment ( ) ) ; } builder . bodyJson ( contentJson ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( FeedbackReturn . class ) ) ; } | Add feedback . | 369 | 3 |
25,990 | public ServiceCall < Void > deleteFeedback ( DeleteFeedbackOptions deleteFeedbackOptions ) { Validator . notNull ( deleteFeedbackOptions , "deleteFeedbackOptions cannot be null" ) ; String [ ] pathSegments = { "v1/feedback" } ; String [ ] pathParameters = { deleteFeedbackOptions . feedbackId ( ) } ; RequestBuilder builder = RequestBuilder . delete ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "deleteFeedback" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( deleteFeedbackOptions . model ( ) != null ) { builder . query ( "model" , deleteFeedbackOptions . model ( ) ) ; } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getVoid ( ) ) ; } | Delete a specified feedback entry . | 276 | 6 |
25,991 | public ServiceCall < GetFeedback > getFeedback ( GetFeedbackOptions getFeedbackOptions ) { Validator . notNull ( getFeedbackOptions , "getFeedbackOptions cannot be null" ) ; String [ ] pathSegments = { "v1/feedback" } ; String [ ] pathParameters = { getFeedbackOptions . feedbackId ( ) } ; RequestBuilder builder = RequestBuilder . get ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "getFeedback" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( getFeedbackOptions . model ( ) != null ) { builder . query ( "model" , getFeedbackOptions . model ( ) ) ; } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( GetFeedback . class ) ) ; } | List a specified feedback entry . | 282 | 6 |
25,992 | public ServiceCall < BatchStatus > createBatch ( CreateBatchOptions createBatchOptions ) { Validator . notNull ( createBatchOptions , "createBatchOptions cannot be null" ) ; String [ ] pathSegments = { "v1/batches" } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "createBatch" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; builder . query ( "function" , createBatchOptions . function ( ) ) ; if ( createBatchOptions . model ( ) != null ) { builder . query ( "model" , createBatchOptions . model ( ) ) ; } MultipartBody . Builder multipartBuilder = new MultipartBody . Builder ( ) ; multipartBuilder . setType ( MultipartBody . FORM ) ; RequestBody inputCredentialsFileBody = RequestUtils . inputStreamBody ( createBatchOptions . inputCredentialsFile ( ) , "application/json" ) ; multipartBuilder . addFormDataPart ( "input_credentials_file" , "filename" , inputCredentialsFileBody ) ; multipartBuilder . addFormDataPart ( "input_bucket_location" , createBatchOptions . inputBucketLocation ( ) ) ; multipartBuilder . addFormDataPart ( "input_bucket_name" , createBatchOptions . inputBucketName ( ) ) ; RequestBody outputCredentialsFileBody = RequestUtils . inputStreamBody ( createBatchOptions . outputCredentialsFile ( ) , "application/json" ) ; multipartBuilder . addFormDataPart ( "output_credentials_file" , "filename" , outputCredentialsFileBody ) ; multipartBuilder . addFormDataPart ( "output_bucket_location" , createBatchOptions . outputBucketLocation ( ) ) ; multipartBuilder . addFormDataPart ( "output_bucket_name" , createBatchOptions . outputBucketName ( ) ) ; builder . body ( multipartBuilder . build ( ) ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( BatchStatus . class ) ) ; } | Submit a batch - processing request . | 587 | 7 |
25,993 | public ServiceCall < BatchStatus > getBatch ( GetBatchOptions getBatchOptions ) { Validator . notNull ( getBatchOptions , "getBatchOptions cannot be null" ) ; String [ ] pathSegments = { "v1/batches" } ; String [ ] pathParameters = { getBatchOptions . batchId ( ) } ; RequestBuilder builder = RequestBuilder . get ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "getBatch" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( BatchStatus . class ) ) ; } | Get information about a specific batch - processing job . | 249 | 10 |
25,994 | public ServiceCall < Batches > listBatches ( ListBatchesOptions listBatchesOptions ) { String [ ] pathSegments = { "v1/batches" } ; RequestBuilder builder = RequestBuilder . get ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "listBatches" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( listBatchesOptions != null ) { } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( Batches . class ) ) ; } | List submitted batch - processing jobs . | 215 | 7 |
25,995 | public ServiceCall < BatchStatus > updateBatch ( UpdateBatchOptions updateBatchOptions ) { Validator . notNull ( updateBatchOptions , "updateBatchOptions cannot be null" ) ; String [ ] pathSegments = { "v1/batches" } ; String [ ] pathParameters = { updateBatchOptions . batchId ( ) } ; RequestBuilder builder = RequestBuilder . put ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; builder . query ( "version" , versionDate ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "compare-comply" , "v1" , "updateBatch" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; builder . query ( "action" , updateBatchOptions . action ( ) ) ; if ( updateBatchOptions . model ( ) != null ) { builder . query ( "model" , updateBatchOptions . model ( ) ) ; } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( BatchStatus . class ) ) ; } | Update a pending or active batch - processing job . | 300 | 10 |
25,996 | public ServiceCall < Voice > getVoice ( GetVoiceOptions getVoiceOptions ) { Validator . notNull ( getVoiceOptions , "getVoiceOptions cannot be null" ) ; String [ ] pathSegments = { "v1/voices" } ; String [ ] pathParameters = { getVoiceOptions . voice ( ) } ; RequestBuilder builder = RequestBuilder . get ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "text_to_speech" , "v1" , "getVoice" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( getVoiceOptions . customizationId ( ) != null ) { builder . query ( "customization_id" , getVoiceOptions . customizationId ( ) ) ; } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( Voice . class ) ) ; } | Get a voice . | 261 | 4 |
25,997 | public ServiceCall < Voices > listVoices ( ListVoicesOptions listVoicesOptions ) { String [ ] pathSegments = { "v1/voices" } ; RequestBuilder builder = RequestBuilder . get ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "text_to_speech" , "v1" , "listVoices" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( listVoicesOptions != null ) { } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( Voices . class ) ) ; } | List voices . | 201 | 3 |
25,998 | public ServiceCall < InputStream > synthesize ( SynthesizeOptions synthesizeOptions ) { Validator . notNull ( synthesizeOptions , "synthesizeOptions cannot be null" ) ; String [ ] pathSegments = { "v1/synthesize" } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "text_to_speech" , "v1" , "synthesize" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } if ( synthesizeOptions . accept ( ) != null ) { builder . header ( "Accept" , synthesizeOptions . accept ( ) ) ; } if ( synthesizeOptions . voice ( ) != null ) { builder . query ( "voice" , synthesizeOptions . voice ( ) ) ; } if ( synthesizeOptions . customizationId ( ) != null ) { builder . query ( "customization_id" , synthesizeOptions . customizationId ( ) ) ; } final JsonObject contentJson = new JsonObject ( ) ; contentJson . addProperty ( "text" , synthesizeOptions . text ( ) ) ; builder . bodyJson ( contentJson ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getInputStream ( ) ) ; } | Synthesize audio . | 341 | 6 |
25,999 | public ServiceCall < Pronunciation > getPronunciation ( GetPronunciationOptions getPronunciationOptions ) { Validator . notNull ( getPronunciationOptions , "getPronunciationOptions cannot be null" ) ; String [ ] pathSegments = { "v1/pronunciation" } ; RequestBuilder builder = RequestBuilder . get ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "text_to_speech" , "v1" , "getPronunciation" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; builder . query ( "text" , getPronunciationOptions . text ( ) ) ; if ( getPronunciationOptions . voice ( ) != null ) { builder . query ( "voice" , getPronunciationOptions . voice ( ) ) ; } if ( getPronunciationOptions . format ( ) != null ) { builder . query ( "format" , getPronunciationOptions . format ( ) ) ; } if ( getPronunciationOptions . customizationId ( ) != null ) { builder . query ( "customization_id" , getPronunciationOptions . customizationId ( ) ) ; } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( Pronunciation . class ) ) ; } | Get pronunciation . | 351 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.