idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
40,800
public < T extends Type & Element > void register ( String fullyQualifiedName , T type ) { if ( resolve ( fullyQualifiedName ) != null ) { throw new ParserException ( type , "Cannot register duplicate type: %s" , fullyQualifiedName ) ; } symbolTable . put ( fullyQualifiedName , type ) ; }
Register user type in symbol table . Full name should start with . .
40,801
public < T extends Type > T resolve ( String typeName , Class < T > clazz ) { Type instance = resolve ( typeName ) ; if ( instance == null ) { return null ; } if ( clazz . isAssignableFrom ( instance . getClass ( ) ) ) { return clazz . cast ( instance ) ; } else { throw new ParserException ( "Type error: %s of type %s ...
Resolve a type declaration by it s name using this proto context .
40,802
protected void channelRead0 ( final ChannelHandlerContext ctx , final HttpObject msg ) throws Exception { if ( msg instanceof HttpContent ) { HttpContent content = ( HttpContent ) msg ; decodeChunk ( ( InetSocketAddress ) ctx . channel ( ) . remoteAddress ( ) , content . content ( ) ) ; } }
If we get a new content chunk send it towards decoding .
40,803
private void decodeChunk ( InetSocketAddress address , final ByteBuf chunk ) { responseContent . writeBytes ( chunk ) ; String currentChunk = responseContent . toString ( CharsetUtil . UTF_8 ) ; int separatorIndex = currentChunk . indexOf ( "\n\n\n\n" ) ; if ( separatorIndex > 0 ) { String rawConfig = currentChunk . su...
Helper method to decode and analyze the chunk .
40,804
public void handlerRemoved ( final ChannelHandlerContext ctx ) throws Exception { if ( responseContent != null && responseContent . refCnt ( ) > 0 ) { responseContent . release ( ) ; responseContent = null ; } }
Once the handler is removed make sure the response content is released and freed .
40,805
public static String getClassName ( UserType userType ) { String name = userType . getName ( ) ; return Formatter . toPascalCase ( name ) ; }
Returns a java class name for a user type .
40,806
public static String getCanonicalName ( UserType userType ) { String name = getClassName ( userType ) ; String canonicalName ; if ( userType . isNested ( ) ) { Message parent = ( Message ) userType . getParent ( ) ; canonicalName = getCanonicalName ( parent ) + '.' + name ; } else { Proto proto = userType . getProto ( ...
Returns java canonical class name for a user type .
40,807
public static Version getServerVersion ( Channel channel ) { Version version = channel . attr ( SERVER_VERSION ) . get ( ) ; if ( version == null ) { throw new IllegalStateException ( "Server version attribute not yet set by " + DcpConnectHandler . class . getSimpleName ( ) ) ; } return version ; }
Returns the Couchbase Server version associated with the given channel .
40,808
public void channelActive ( final ChannelHandlerContext ctx ) throws Exception { ByteBuf request = ctx . alloc ( ) . buffer ( ) ; VersionRequest . init ( request ) ; ctx . writeAndFlush ( request ) ; }
Once the channel becomes active sends the initial open connection request .
40,809
public Oneof getOneof ( String name ) { for ( Oneof oneof : getOneofs ( ) ) { if ( name . equals ( oneof . getName ( ) ) ) { return oneof ; } } return null ; }
Get oneof node by it s name .
40,810
private void negotiate ( final ChannelHandlerContext ctx ) { if ( controlSettings . hasNext ( ) ) { Map . Entry < String , String > setting = controlSettings . next ( ) ; LOGGER . debug ( "Negotiating DCP Control {}: {}" , setting . getKey ( ) , setting . getValue ( ) ) ; ByteBuf request = ctx . alloc ( ) . buffer ( ) ...
Helper method to walk the iterator and create a new request that defines which control param should be negotiated right now .
40,811
public void channelActive ( final ChannelHandlerContext ctx ) throws Exception { controlSettings = dcpControl . getControls ( getServerVersion ( ctx . channel ( ) ) ) . entrySet ( ) . iterator ( ) ; negotiate ( ctx ) ; }
Once the channel becomes active start negotiating the dcp control params .
40,812
public void setFromJson ( final byte [ ] persisted ) { try { SessionState decoded = JACKSON . readValue ( persisted , SessionState . class ) ; decoded . foreachPartition ( new Action1 < PartitionState > ( ) { int i = 0 ; public void call ( PartitionState dps ) { partitionStates . set ( i ++ , dps ) ; } } ) ; } catch ( ...
Recovers the session state from persisted JSON .
40,813
public boolean isAtEnd ( ) { final AtomicBoolean atEnd = new AtomicBoolean ( true ) ; foreachPartition ( ps -> { if ( ! ps . isAtEnd ( ) ) { atEnd . set ( false ) ; } } ) ; return atEnd . get ( ) ; }
Check if the current sequence numbers for all partitions are > = the ones set as end .
40,814
public void foreachPartition ( final Action1 < PartitionState > action ) { int len = partitionStates . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { PartitionState ps = partitionStates . get ( i ) ; if ( ps == null ) { continue ; } action . call ( ps ) ; } }
Provides an iterator over all partitions calling the callback for each one .
40,815
public static String removeFirstAndLastChar ( String text ) { Preconditions . checkNotNull ( text , "text can not be null" ) ; int n = text . length ( ) ; return text . substring ( 1 , n - 1 ) ; }
Remove first and last character from given string and return result .
40,816
public Set < String > getConstantNames ( ) { return constants . stream ( ) . map ( EnumConstant :: getName ) . collect ( Collectors . toSet ( ) ) ; }
Returns a list of all enum constant names .
40,817
public EnumConstant getConstant ( String name ) { for ( EnumConstant enumConstant : getConstants ( ) ) { if ( enumConstant . getName ( ) . equals ( name ) ) { return enumConstant ; } } return null ; }
Get enum constant by it s name .
40,818
public void clear ( final short vbucket ) { final Queue < BufferedEvent > queue = partitionQueues . get ( vbucket ) ; synchronized ( queue ) { LOGGER . debug ( "Clearing stream event buffer for partition {}" , vbucket ) ; for ( BufferedEvent bufferedEvent : queue ) { bufferedEvent . discard ( ) ; } queue . clear ( ) ; ...
Discard all buffered events in the given vbucket .
40,819
private void rollback ( final short vbucket , final long toSeqno ) { final Queue < BufferedEvent > queue = partitionQueues . get ( vbucket ) ; synchronized ( queue ) { for ( Iterator < BufferedEvent > i = queue . iterator ( ) ; i . hasNext ( ) ; ) { final BufferedEvent event = i . next ( ) ; final boolean eventSeqnoIsG...
Discard any buffered events in the given vBucket with sequence numbers higher than the given sequence number .
40,820
void onSeqnoPersisted ( final short vbucket , final long seqno ) { final Queue < BufferedEvent > queue = partitionQueues . get ( vbucket ) ; synchronized ( queue ) { while ( ! queue . isEmpty ( ) && Long . compareUnsigned ( queue . peek ( ) . seqno , seqno ) < 1 ) { final BufferedEvent event = queue . poll ( ) ; try { ...
Send to the wrapped handler all events with sequence numbers < = the given sequence number .
40,821
public static String getMethodName ( ServiceMethod serviceMethod ) { String name = serviceMethod . getName ( ) ; String formattedName = Formatter . toCamelCase ( name ) ; if ( isReservedKeyword ( formattedName ) ) { return formattedName + '_' ; } return formattedName ; }
Returns java method name for corresponding rpc method .
40,822
public static List < String > bitFieldNames ( Message message ) { int fieldCount = message . getFieldCount ( ) ; if ( fieldCount == 0 ) { return Collections . emptyList ( ) ; } List < String > result = new ArrayList < > ( ) ; int n = ( fieldCount - 1 ) / 32 + 1 ; for ( int i = 0 ; i < n ; i ++ ) { result . add ( "__bit...
Returns a list of bit fields used for field presence checks .
40,823
public static String getOneofNotSetConstantName ( Oneof oneof ) { String name = oneof . getName ( ) ; String underscored = Formatter . toUnderscoreCase ( name ) ; return Formatter . toUpperCase ( underscored ) + "_NOT_SET" ; }
Returns a not set name for one - of enum constant .
40,824
public void compile ( ModuleConfiguration configuration ) { LOGGER . debug ( "Compiling module {}" , configuration ) ; FileReaderFactory fileReaderFactory = injector . getInstance ( FileReaderFactory . class ) ; Importer importer = injector . getInstance ( Importer . class ) ; CompilerRegistry registry = injector . get...
Compile module - parse source files and generate code using specified outputs .
40,825
public ServiceMethod getMethod ( String name ) { for ( ServiceMethod serviceMethod : getMethods ( ) ) { if ( serviceMethod . getName ( ) . equals ( name ) ) { return serviceMethod ; } } return null ; }
Get a service method by it s name .
40,826
public void walk ( ) { for ( Processor < Proto > protoProcessor : protoProcessors ) { protoProcessor . run ( context , proto ) ; } walk ( proto ) ; }
Start walking .
40,827
public void channelActive ( final ChannelHandlerContext ctx ) throws Exception { String terseUri = "/pools/default/bs/" + bucket ; FullHttpRequest request = new DefaultFullHttpRequest ( HttpVersion . HTTP_1_1 , HttpMethod . GET , terseUri ) ; request . headers ( ) . add ( HttpHeaders . Names . ACCEPT , "application/jso...
Once the channel is active start to send the HTTP request to begin chunking .
40,828
private void addHttpBasicAuth ( final ChannelHandlerContext ctx , final HttpRequest request ) { ByteBuf raw = ctx . alloc ( ) . buffer ( username . length ( ) + password . length ( ) + 1 ) ; raw . writeBytes ( ( username + ":" + password ) . getBytes ( CharsetUtil . UTF_8 ) ) ; ByteBuf encoded = Base64 . encode ( raw ,...
Helper method to add authentication credentials to the config stream request .
40,829
public void userEventTriggered ( ChannelHandlerContext ctx , Object evt ) throws Exception { if ( evt instanceof IdleStateEvent ) { IdleStateEvent e = ( IdleStateEvent ) evt ; if ( e . state ( ) == IdleState . READER_IDLE ) { LOGGER . warn ( "Closing dead connection." ) ; ctx . close ( ) ; return ; } } super . userEven...
Close dead connection in response to idle event from IdleStateHandler .
40,830
private void handleRequest ( final ChannelHandlerContext ctx , final ByteBuf message ) { if ( isDataMessage ( message ) ) { dataEventHandler . onEvent ( flowController , message ) ; } else if ( isControlMessage ( message ) ) { controlHandler . onEvent ( flowController , message ) ; } else if ( DcpNoopRequest . is ( mes...
Dispatch incoming message to either the data or the control feeds .
40,831
private static boolean isDataMessage ( final ByteBuf msg ) { return DcpMutationMessage . is ( msg ) || DcpDeletionMessage . is ( msg ) || DcpExpirationMessage . is ( msg ) ; }
Helper method to check if the given byte buffer is a data message .
40,832
protected final Application ensureApplicationReference ( ) { if ( this . application == null ) { assertState ( ) ; Application tmpApp = applicationResolver . getApplication ( client , applicationRestUrl ) ; if ( tmpApp == null ) { throw new IllegalStateException ( "ApplicationResolver returned 'null' Application, this ...
acquisition so it is negligible if this executes a few times instead of just once .
40,833
public RestTemplate restTemplate ( ) { RestTemplate restTemplate = new RestTemplate ( ) ; List < HttpMessageConverter < ? > > mc = restTemplate . getMessageConverters ( ) ; MappingJackson2HttpMessageConverter json = new MappingJackson2HttpMessageConverter ( ) ; List < MediaType > supportedMediaTypes = new ArrayList < M...
This bean adds in unsupported return types . Necessary because even though rest proxy accepts all types there are still a few that are unsupported
40,834
public static Collection < SimplePrincipalProvider > getSimplePrincipals ( Collection < PrincipalProvider < ? > > principalProviders ) { Collection < SimplePrincipalProvider > principals = new ArrayList < > ( ) ; for ( PrincipalProvider < ? > principal : principalProviders ) { if ( principal instanceof SimplePrincipalP...
Extracts the simple principals of the collection of principals
40,835
public static SimplePrincipalProvider getSimplePrincipalByName ( Collection < PrincipalProvider < ? > > principalProviders , String principalName ) { for ( SimplePrincipalProvider principal : getSimplePrincipals ( principalProviders ) ) { if ( principal . getName ( ) . equals ( principalName ) ) { return principal ; } ...
Gives the simple principal with the given name from the given collection of principals
40,836
public static Class < ? > cleanProxy ( Class < ? > toClean ) { if ( ProxyUtils . isProxy ( toClean ) ) { return toClean . getSuperclass ( ) ; } return toClean ; }
Return the non proxy class if needed .
40,837
private static < T > ServiceBindingBuilder < T > newFactoryBinder ( final Factory < T > factory ) { return BindingBuilderFactory . newFactoryBinder ( factory ) ; }
Get a new factory instance - based service binding builder .
40,838
public boolean includes ( Scope scope ) { if ( scope == null ) { return true ; } if ( scope instanceof SimpleScope ) { SimpleScope simpleScope = ( SimpleScope ) scope ; return this . value . equals ( simpleScope . value ) ; } return false ; }
Checks if the current simple scope equals the verified simple scope .
40,839
public static void load ( String confingFilename ) { try { if ( config == null ) { config = new AXUConfig ( ) ; logger . debug ( "create new AXUConfig instance" ) ; } long nowTime = ( new Date ( ) ) . getTime ( ) ; if ( nowTime - lastLoadTime < 3000 ) { return ; } else { lastLoadTime = nowTime ; } Serializer serializer...
read config from confingPath
40,840
SSLContext getSSLContext ( String protocol , KeyManager [ ] keyManagers , TrustManager [ ] trustManagers ) { try { SSLContext sslContext = SSLContext . getInstance ( protocol ) ; sslContext . init ( keyManagers , trustManagers , null ) ; return sslContext ; } catch ( NoSuchAlgorithmException e ) { throw SeedException ....
Gets an SSLContext configured and initialized .
40,841
public HalRepresentation link ( String rel , String href ) { addLink ( rel , new Link ( href ) ) ; return this ; }
Adds a link with the specified rel and href .
40,842
public HalRepresentation embedded ( String rel , Object embedded ) { this . embedded . put ( rel , embedded ) ; return this ; }
Adds an embedded resource or array of resources .
40,843
ResourceScanner scan ( final Collection < Class < ? > > classes ) { for ( Class < ? > aClass : classes ) { collectHttpMethodsWithRel ( aClass ) ; } buildJsonHomeResources ( ) ; buildHalLink ( ) ; return this ; }
Scans a collection of resources .
40,844
Map < Key < EncryptionService > , EncryptionService > createBindings ( CryptoConfig cryptoConfig , List < KeyPairConfig > keyPairConfigurations , Map < String , KeyStore > keyStores ) { Map < Key < EncryptionService > , EncryptionService > encryptionServices = new HashMap < > ( ) ; Map < String , EncryptionServiceFacto...
Creates the encryption service bindings .
40,845
@ SuppressWarnings ( "unchecked" ) public < S extends Scope > Set < S > getScopesByType ( Class < S > scopeType ) { Set < S > typedScopes = new HashSet < > ( ) ; for ( Scope scope : getScopes ( ) ) { if ( scopeType . isInstance ( scope ) ) { typedScopes . add ( ( S ) scope ) ; } } return typedScopes ; }
Filters the scopes corresponding to a type
40,846
public static < T > ClassConfiguration < T > empty ( Class < T > targetClass ) { return new ClassConfiguration < T > ( targetClass , new HashMap < > ( ) ) { } ; }
Create an empty class configuration for the specified class .
40,847
public ClassConfiguration < T > merge ( ClassConfiguration < T > other ) { if ( ! targetClass . isAssignableFrom ( other . targetClass ) ) { throw new IllegalArgumentException ( "Cannot merge class configurations: " + targetClass . getName ( ) + " is not assignable to " + other . targetClass . getName ( ) ) ; } map . p...
Merge the class configuration with another one overriding the existing values having an identical key . If a key with a null value is merged the key is completely removed from the resulting configuration .
40,848
static Rel findRel ( Method method ) { Rel rootRel = method . getDeclaringClass ( ) . getAnnotation ( Rel . class ) ; Rel rel = method . getAnnotation ( Rel . class ) ; if ( rel != null ) { return rel ; } else if ( rootRel != null ) { return rootRel ; } return null ; }
Finds a the rel of a method . The rel can be found on the declaring class but the rel on the method will have the precedence .
40,849
public void merge ( Hints hints ) { this . allow . addAll ( hints . getAllow ( ) ) ; this . formats . putAll ( hints . getFormats ( ) ) ; this . acceptPath . addAll ( hints . getAcceptPath ( ) ) ; this . acceptPost . addAll ( hints . getAcceptPost ( ) ) ; this . acceptRanges . addAll ( hints . getAcceptRanges ( ) ) ; t...
Merges the current hints with hints comming from another method of the resource .
40,850
private static String bytesToHex ( byte [ ] bytes ) { char [ ] hexChars = new char [ bytes . length * 2 ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { int v = bytes [ i ] & 0xFF ; hexChars [ i * 2 ] = hexArray [ v >>> 4 ] ; hexChars [ i * 2 + 1 ] = hexArray [ v & 0x0F ] ; } return new String ( hexChars ) ; }
We don t have Guava here
40,851
private String [ ] toNameConfigPair ( String token ) throws ConfigurationException { String [ ] pair = token . split ( "\\[" , 2 ) ; String name = StringUtils . clean ( pair [ 0 ] ) ; if ( name == null ) { throw new IllegalArgumentException ( "Filter name not found for filter chain definition token: " + token ) ; } Str...
This method is copied from the same method in Shiro in class DefaultFilterChainManager .
40,852
public static boolean hasRoleOn ( String role , String simpleScope ) { return securitySupport . hasRole ( role , new SimpleScope ( simpleScope ) ) ; }
Checks the current user role in the given scopes .
40,853
public static boolean hasPermissionOn ( String permission , String simpleScope ) { return securitySupport . isPermitted ( permission , new SimpleScope ( simpleScope ) ) ; }
Checks the current user permission .
40,854
private Optional < String [ ] > parseCredentials ( String url ) { if ( ! Strings . isNullOrEmpty ( url ) ) { int p ; if ( ( p = url . indexOf ( "://" ) ) != - 1 ) { url = url . substring ( p + 3 ) ; } if ( ( p = url . indexOf ( '@' ) ) != - 1 ) { String [ ] result = new String [ 2 ] ; String credentials = url . substri...
Given a proxy URL returns a two element arrays containing the user name and the password . The second component of the array is null if no password is specified .
40,855
private Optional < String [ ] > parseProxy ( String url , String defPort ) { if ( ! Strings . isNullOrEmpty ( url ) ) { String [ ] result = new String [ 2 ] ; int p = url . indexOf ( "://" ) ; if ( p != - 1 ) url = url . substring ( p + 3 ) ; if ( ( p = url . indexOf ( '@' ) ) != - 1 ) url = url . substring ( p + 1 ) ;...
Given a proxy URL returns a two element arrays containing the host name and the port
40,856
private Pattern makePattern ( String noProxy ) { String regex = noProxy . replaceAll ( "\\." , "\\\\." ) . replaceAll ( "\\*" , ".*" ) ; if ( ! regex . startsWith ( ".*" ) ) { regex = ".*" + regex ; } regex = "^" + regex + "$" ; return Pattern . compile ( regex ) ; }
Creates a regexp pattern equivalent to the classic noProxy wildcard expression .
40,857
protected Object doInvocation ( TransactionLogger transactionLogger , MethodInvocation invocation , TransactionMetadata transactionMetadata , Object currentTransaction ) throws Throwable { Object result = null ; try { transactionLogger . log ( "invocation started" , transactionLogger ) ; result = invocation . proceed (...
This method call the wrapped transactional method .
40,858
public static boolean isBindable ( Class < ? > subClass ) { return ! subClass . isInterface ( ) && ! Modifier . isAbstract ( subClass . getModifiers ( ) ) && subClass . getTypeParameters ( ) . length == 0 ; }
Checks if the class is not an interface an abstract class or a class with unresolved generics .
40,859
public String hrefTemplate ( ) { UriTemplateBuilder uriTemplateBuilder = UriTemplate . buildFromTemplate ( hrefTemplate ) ; if ( ! queryParams . isEmpty ( ) ) { uriTemplateBuilder = uriTemplateBuilder . query ( queryParams . keySet ( ) . toArray ( new String [ queryParams . keySet ( ) . size ( ) ] ) ) ; } return uriTem...
Return the href template . It s empty unless the path is templated .
40,860
public Map < String , String > hrefVars ( ) { Map < String , String > map = new HashMap < > ( pathParams ) ; map . putAll ( queryParams ) ; return map ; }
Return the hrefVars . It s empty unless the path is templated .
40,861
public void merge ( Resource resource ) { if ( resource == null ) { return ; } checkRel ( resource ) ; checkHrefs ( resource ) ; if ( resource . templated ( ) ) { this . pathParams . putAll ( resource . pathParams ) ; this . queryParams . putAll ( resource . queryParams ) ; } if ( resource . hints ( ) != null ) { this ...
Merges the current resource with another resource instance . The merge objects must represent the same resource but can come from multiple methods .
40,862
public Map < String , Object > toRepresentation ( ) { Map < String , Object > representation = new HashMap < > ( ) ; if ( templated ( ) ) { representation . put ( "href-template" , hrefTemplate ) ; representation . put ( "href-vars" , hrefVars ( ) ) ; } else { representation . put ( "href" , href ) ; } if ( hints != nu...
Serializes the resource into a map .
40,863
public void addRole ( Role role ) { apiRoles . add ( role ) ; roles . add ( role . getName ( ) ) ; for ( org . seedstack . seed . security . Permission permission : role . getPermissions ( ) ) { if ( ! role . getScopes ( ) . isEmpty ( ) ) { for ( Scope scope : role . getScopes ( ) ) { ScopePermission sp = new ScopePerm...
Adds a role and its permissions to the authorization info .
40,864
static String stripLeadingSlash ( String path ) { if ( path . endsWith ( "/" ) ) { return path . substring ( 0 , path . length ( ) - 1 ) ; } else { return path ; } }
Removes the leading slash in the given path .
40,865
static boolean jaxTemplate ( String href ) { Matcher m = JAX_RS_TEMPLATE . matcher ( href ) ; return m . matches ( ) ; }
Returns whether the href is a JAX - RS template .
40,866
public static BaseException translateException ( Exception exception ) { if ( exception instanceof BaseException ) { return ( BaseException ) exception ; } else { for ( SeedExceptionTranslator exceptionTranslator : exceptionTranslators ) { if ( exceptionTranslator . canTranslate ( exception ) ) { return exceptionTransl...
Translates any exception that occurred in the application using an extensible exception mechanism .
40,867
public Map < String , Context > getJndiContexts ( ) { Map < String , Context > jndiContexts = new HashMap < > ( ) ; jndiContexts . putAll ( additionalJndiContexts ) ; jndiContexts . put ( "default" , defaultJndiContext ) ; return jndiContexts ; }
Retrieve all configured JNDI contexts .
40,868
public Hints findHint ( Method method ) { Hints hints = new Hints ( ) ; for ( Annotation annotation : method . getDeclaredAnnotations ( ) ) { findAllow ( hints , annotation ) ; findFormats ( hints , annotation ) ; } return hints ; }
Finds the JSON - HOME hints on the given method .
40,869
private void setVelocity ( int firstVisibleItem , int totalItemCount ) { if ( mMaxVelocity > MAX_VELOCITY_OFF && mPreviousFirstVisibleItem != firstVisibleItem ) { long currTime = System . currentTimeMillis ( ) ; long timeToScrollOneItem = currTime - mPreviousEventTime ; if ( timeToScrollOneItem < 1 ) { double newSpeed ...
Should be called in onScroll to keep take of current Velocity .
40,870
private void doJazziness ( View item , int position , int scrollDirection ) { if ( mIsScrolling ) { if ( mOnlyAnimateNewItems && mAlreadyAnimatedItems . contains ( position ) ) return ; if ( mOnlyAnimateOnFling && ! mIsFlingEvent ) return ; if ( mMaxVelocity > MAX_VELOCITY_OFF && mMaxVelocity < mSpeed ) return ; if ( m...
Initializes the item view and triggers the animation .
40,871
public QueryResult getResultFor ( String subAnalysisLabel ) { if ( ! this . analysesResults . containsKey ( subAnalysisLabel ) ) { throw new IllegalArgumentException ( "No results for a sub-analysis with that label." ) ; } return this . analysesResults . get ( subAnalysisLabel ) ; }
Provides the result for a sub - analysis .
40,872
public static void initialize ( KeenClient client ) { if ( client == null ) { throw new IllegalArgumentException ( "Client must not be null" ) ; } if ( ClientSingleton . INSTANCE . client != null ) { return ; } ClientSingleton . INSTANCE . client = client ; }
Initializes the static Keen client . Only the first call to this method has any effect . All subsequent calls are ignored .
40,873
public void addEvent ( KeenProject project , String eventCollection , Map < String , Object > event , Map < String , Object > keenProperties , KeenCallback callback ) { if ( ! isActive ) { handleLibraryInactive ( callback ) ; return ; } if ( project == null && defaultProject == null ) { handleFailure ( null , project ,...
Synchronously adds an event to the specified collection . This method will immediately publish the event to the Keen server in the current thread .
40,874
public void queueEvent ( String eventCollection , Map < String , Object > event ) { queueEvent ( eventCollection , event , null ) ; }
Queues an event in the default project with default Keen properties and no callbacks .
40,875
public void queueEvent ( String eventCollection , Map < String , Object > event , Map < String , Object > keenProperties ) { queueEvent ( null , eventCollection , event , keenProperties , null ) ; }
Queues an event in the default project with no callbacks .
40,876
public synchronized void sendQueuedEvents ( KeenProject project , KeenCallback callback ) { if ( ! isActive ) { handleLibraryInactive ( callback ) ; return ; } if ( project == null && defaultProject == null ) { handleFailure ( null , new IllegalStateException ( "No project specified, but no default project found" ) ) ;...
Synchronously sends all queued events for the given project . This method will immediately publish the events to the Keen server in the current thread .
40,877
public void setProxy ( String proxyHost , int proxyPort ) { this . proxy = new Proxy ( Proxy . Type . HTTP , new InetSocketAddress ( proxyHost , proxyPort ) ) ; }
Sets an HTTP proxy server configuration for this client .
40,878
protected Map < String , Object > validateAndBuildEvent ( KeenProject project , String eventCollection , Map < String , Object > event , Map < String , Object > keenProperties ) { if ( project . getWriteKey ( ) == null ) { throw new NoWriteKeyException ( "You can't send events to Keen if you haven't set a write key." )...
Validates an event and inserts global properties producing a new event object which is ready to be published to the Keen service .
40,879
private void mergeGlobalProperties ( Map < String , Object > globalProperties , Map < String , Object > keenProperties , Map < String , Object > newEvent ) { if ( globalProperties != null ) { globalProperties = new HashMap < String , Object > ( globalProperties ) ; Object keen = globalProperties . remove ( "keen" ) ; i...
Removes the keen key from the globalProperties map and if a map was removed then all of its pairs are added to the keenProperties map . Anything left in the globalProperties map is then added to the newEvent map .
40,880
private void validateEventCollection ( String eventCollection ) { if ( eventCollection == null || eventCollection . length ( ) == 0 ) { throw new InvalidEventCollectionException ( "You must specify a non-null, " + "non-empty event collection: " + eventCollection ) ; } if ( eventCollection . length ( ) > 256 ) { throw n...
Validates the name of an event collection .
40,881
@ SuppressWarnings ( "unchecked" ) private void validateEvent ( Map < String , Object > event , int depth ) { if ( depth == 0 ) { if ( event == null || event . size ( ) == 0 ) { throw new InvalidEventException ( "You must specify a non-null, non-empty event." ) ; } if ( event . containsKey ( "keen" ) ) { throw new Inva...
Validates an event .
40,882
@ SuppressWarnings ( "unchecked" ) private void validateEventValue ( Object value , int depth ) { if ( value instanceof String ) { String strValue = ( String ) value ; if ( strValue . length ( ) >= 10000 ) { throw new InvalidEventException ( "An event cannot contain a string property value longer than 10," + "000 chara...
Validates a value within an event structure . This method will handle validating each element in a list as well as recursively validating nested maps .
40,883
private Map < String , List < Map < String , Object > > > buildEventMap ( String projectId , Map < String , List < Object > > eventHandles ) throws IOException { Map < String , List < Map < String , Object > > > result = new HashMap < String , List < Map < String , Object > > > ( ) ; for ( Map . Entry < String , List <...
Builds a map from collection name to a list of event maps given a map from collection name to a list of event handles . This method just uses the event store to retrieve each event by its handle .
40,884
private String publish ( KeenProject project , String eventCollection , Map < String , Object > event ) throws IOException { URL url = createURL ( project , eventCollection ) ; if ( url == null ) { throw new IllegalStateException ( "URL address is empty" ) ; } return publishObject ( project , url , event ) ; }
Publishes a single event to the Keen service .
40,885
private String publishAll ( KeenProject project , Map < String , List < Map < String , Object > > > events ) throws IOException { String urlString = String . format ( Locale . US , "%s/%s/projects/%s/events" , getBaseUrl ( ) , KeenConstants . API_VERSION , project . getProjectId ( ) ) ; URL url = new URL ( urlString ) ...
Publishes a batch of events to the Keen service .
40,886
private void handleSuccess ( KeenCallback callback , KeenProject project , String eventCollection , Map < String , Object > event , Map < String , Object > keenProperties ) { handleSuccess ( callback ) ; if ( callback != null ) { try { if ( callback instanceof KeenDetailedCallback ) { ( ( KeenDetailedCallback ) callbac...
Reports success to a callback . If the callback is null this is a no - op . Any exceptions thrown by the callback are silently ignored .
40,887
private Map < String , Object > getEvent ( Object handle ) throws IOException { String jsonEvent = eventStore . get ( handle ) ; StringReader reader = new StringReader ( jsonEvent ) ; Map < String , Object > event = jsonHandler . readJson ( reader ) ; KeenUtils . closeQuietly ( reader ) ; return event ; }
Get an event object from the eventStore .
40,888
private Map < String , Integer > getAttemptsMap ( String projectId , String eventCollection ) throws IOException { Map < String , Integer > attempts = new HashMap < String , Integer > ( ) ; if ( eventStore instanceof KeenAttemptCountingEventStore ) { KeenAttemptCountingEventStore res = ( KeenAttemptCountingEventStore )...
Gets the map of attempt counts from the eventStore
40,889
private void setAttemptsMap ( String projectId , String eventCollection , Map < String , Integer > attempts ) throws IOException { if ( eventStore instanceof KeenAttemptCountingEventStore ) { KeenAttemptCountingEventStore res = ( KeenAttemptCountingEventStore ) eventStore ; StringWriter writer = null ; try { writer = n...
Set the attempts Map in the eventStore
40,890
public boolean areParamsValid ( ) { if ( queryType == QueryType . COUNT ) { if ( eventCollection == null || eventCollection . isEmpty ( ) ) { return false ; } } if ( queryType == QueryType . COUNT_UNIQUE || queryType == QueryType . MINIMUM || queryType == QueryType . MAXIMUM || queryType == QueryType . AVERAGE || query...
Verifies whether the parameters are valid based on the input query name .
40,891
public static int fromHours ( int hours ) { int refreshRate = hours * RefreshRate . SECONDS_PER_HOUR ; RefreshRate . validateRefreshRate ( refreshRate ) ; return refreshRate ; }
Maximum is 24 hrs
40,892
protected HttpURLConnection openConnection ( Request request ) throws IOException { HttpURLConnection result ; if ( request . proxy != null ) { result = ( HttpURLConnection ) request . url . openConnection ( request . proxy ) ; } else { result = ( HttpURLConnection ) request . url . openConnection ( ) ; } result . setC...
Opens a connection based on the URL in the given request .
40,893
protected void sendRequest ( HttpURLConnection connection , Request request ) throws IOException { connection . setRequestMethod ( request . method ) ; connection . setRequestProperty ( "Accept" , "application/json" ) ; connection . setRequestProperty ( "Authorization" , request . authorization ) ; connection . setRequ...
Sends a request over a given connection .
40,894
private static FunnelResult constructFunnelResult ( Map < String , Object > responseMap ) { QueryResult funnelResult = constructQueryResult ( responseMap . get ( KeenQueryConstants . RESULT ) , false , false ) ; if ( ! ( funnelResult instanceof ListResult ) ) { throw new KeenQueryClientException ( "'result' property of...
Constructs a FunnelResult from a response object map . This map should include a result key and may include an optional actors key as well .
40,895
private static String readerToString ( Reader reader ) throws IOException { StringWriter writer = new StringWriter ( ) ; try { char [ ] buffer = new char [ COPY_BUFFER_SIZE ] ; while ( true ) { int bytesRead = reader . read ( buffer ) ; if ( bytesRead == - 1 ) { break ; } else { writer . write ( buffer , 0 , bytesRead ...
Converts a Reader to a String by copying the Reader s contents into a StringWriter via a buffer .
40,896
private static boolean requiresWrap ( Map map ) { for ( Object value : map . values ( ) ) { if ( value instanceof Collection || value instanceof Map || value instanceof Object [ ] ) { return true ; } } return false ; }
Checks whether a map requires any wrapping . This is used to avoid creating a copy of a map if all of its fields can be handled natively .
40,897
private static boolean requiresWrap ( Collection collection ) { for ( Object value : collection ) { if ( value instanceof Collection || value instanceof Map ) { return true ; } } return false ; }
Checks whether a collection requires any wrapping . This is used to avoid creating a copy of a collection if all of its fields can be handled natively .
40,898
URL getAnalysisUrl ( String projectId , String analysisPath ) throws KeenQueryClientException { try { return new URL ( String . format ( Locale . US , "%s/%s/projects/%s/queries/%s" , this . baseUrl , this . apiVersion , projectId , analysisPath ) ) ; } catch ( MalformedURLException ex ) { Logger . getLogger ( RequestU...
Get a formatted URL for an analysis request .
40,899
private Map < String , List < Object > > getHandlesFromProjectDirectory ( File projectDir ) throws IOException { File [ ] collectionDirs = getSubDirectories ( projectDir ) ; Map < String , List < Object > > handleMap = new HashMap < String , List < Object > > ( ) ; if ( collectionDirs != null ) { for ( File directory :...
Gets the handle map for all collections in the specified project cache directory .