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 can not be cast to %s" , typeName , instance . getClass ( ) , clazz ) ; } }
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 . substring ( 0 , separatorIndex ) . trim ( ) . replace ( "$HOST" , address . getAddress ( ) . getHostAddress ( ) ) ; NetworkAddress origin = NetworkAddress . create ( address . getAddress ( ) . getHostAddress ( ) ) ; CouchbaseBucketConfig config = ( CouchbaseBucketConfig ) BucketConfigParser . parse ( rawConfig , environment , origin ) ; synchronized ( currentBucketConfigRev ) { if ( config . rev ( ) > currentBucketConfigRev . get ( ) ) { LOGGER . trace ( "Publishing bucket config: {}" , RedactableArgument . system ( rawConfig ) ) ; currentBucketConfigRev . set ( config . rev ( ) ) ; configStream . onNext ( config ) ; } else { LOGGER . trace ( "Ignoring config, since rev has not changed." ) ; } } responseContent . clear ( ) ; responseContent . writeBytes ( currentChunk . substring ( separatorIndex + 4 ) . getBytes ( CharsetUtil . UTF_8 ) ) ; } }
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 ( ) ; String pkg = ProtoUtil . getPackage ( proto ) ; if ( pkg . isEmpty ( ) ) { canonicalName = name ; } else { canonicalName = pkg + '.' + name ; } } return canonicalName ; }
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 ( ) ; DcpControlRequest . init ( request ) ; DcpControlRequest . key ( setting . getKey ( ) , request ) ; DcpControlRequest . value ( Unpooled . copiedBuffer ( setting . getValue ( ) , CharsetUtil . UTF_8 ) , request ) ; ctx . writeAndFlush ( request ) ; } else { originalPromise ( ) . setSuccess ( ) ; ctx . pipeline ( ) . remove ( this ) ; ctx . fireChannelActive ( ) ; LOGGER . debug ( "Negotiated all DCP Control settings against Node {}" , ctx . channel ( ) . remoteAddress ( ) ) ; } }
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 ( Exception ex ) { throw new RuntimeException ( "Could not decode SessionState from JSON." , ex ) ; } }
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 eventSeqnoIsGreaterThanRollbackSeqno = Long . compareUnsigned ( event . seqno , toSeqno ) > 0 ; if ( eventSeqnoIsGreaterThanRollbackSeqno ) { LOGGER . trace ( "Dropping event with seqno {} from stream buffer for partition {}" , event . seqno , vbucket ) ; event . discard ( ) ; i . remove ( ) ; } } } }
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 { switch ( event . type ) { case DATA : dataEventHandler . onEvent ( event . flowController , event . event ) ; break ; case CONTROL : controlEventHandler . onEvent ( event . flowController , event . event ) ; break ; case STREAM_END_OK : eventBus . publish ( new StreamEndEvent ( vbucket , StreamEndReason . OK ) ) ; break ; default : throw new RuntimeException ( "Unexpected event type: " + event . type ) ; } } catch ( Throwable t ) { LOGGER . error ( "Event handler threw exception" , t ) ; } } } }
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 ( "__bitField" + i ) ; } return result ; }
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 . getInstance ( CompilerRegistry . class ) ; ProtoCompiler compiler = registry . findCompiler ( configuration . getGenerator ( ) ) ; if ( compiler == null ) { throw new GeneratorException ( "Unknown template: %s | %s" , configuration . getGenerator ( ) , registry . availableCompilers ( ) ) ; } FileReader fileReader = fileReaderFactory . create ( configuration . getIncludePaths ( ) ) ; Map < String , Proto > importedFiles = new HashMap < > ( ) ; for ( String path : configuration . getProtoFiles ( ) ) { LOGGER . info ( "Parse {}" , path ) ; ProtoContext context = importer . importFile ( fileReader , path ) ; Proto proto = context . getProto ( ) ; importedFiles . put ( path , proto ) ; } ImmutableModule . Builder builder = ImmutableModule . builder ( ) ; builder . name ( configuration . getName ( ) ) ; builder . output ( configuration . getOutput ( ) ) ; builder . options ( configuration . getOptions ( ) ) ; for ( Proto proto : importedFiles . values ( ) ) { builder . addProtos ( proto ) ; } UsageIndex index = UsageIndex . build ( importedFiles . values ( ) ) ; builder . usageIndex ( index ) ; ImmutableModule module = builder . build ( ) ; for ( Proto proto : importedFiles . values ( ) ) { proto . setModule ( module ) ; } compiler . compile ( module ) ; }
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/json" ) ; addHttpBasicAuth ( ctx , request ) ; ctx . writeAndFlush ( request ) ; }
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 , false ) ; request . headers ( ) . add ( HttpHeaders . Names . AUTHORIZATION , "Basic " + encoded . toString ( CharsetUtil . UTF_8 ) ) ; encoded . release ( ) ; raw . release ( ) ; }
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 . userEventTriggered ( ctx , evt ) ; }
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 ( message ) ) { try { ByteBuf buffer = ctx . alloc ( ) . buffer ( ) ; DcpNoopResponse . init ( buffer ) ; MessageUtil . setOpaque ( MessageUtil . getOpaque ( message ) , buffer ) ; ctx . writeAndFlush ( buffer ) ; } finally { message . release ( ) ; } } else { try { LOGGER . warn ( "Unknown DCP Message, ignoring. \n{}" , MessageUtil . humanize ( message ) ) ; } finally { message . release ( ) ; } } }
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 is likely a configuration error." ) ; } this . application = tmpApp ; } return this . application ; }
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 < MediaType > ( ) ; supportedMediaTypes . add ( new MediaType ( "text" , "javascript" , Charset . forName ( "utf-8" ) ) ) ; supportedMediaTypes . add ( new MediaType ( "application" , "javascript" , Charset . forName ( "UTF-8" ) ) ) ; json . setSupportedMediaTypes ( supportedMediaTypes ) ; mc . add ( json ) ; restTemplate . setMessageConverters ( mc ) ; return restTemplate ; }
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 SimplePrincipalProvider ) { principals . add ( ( SimplePrincipalProvider ) principal ) ; } } return principals ; }
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 ; } } return null ; }
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 = new Persister ( ) ; URL configUrl = config . getClass ( ) . getClassLoader ( ) . getResource ( confingFilename ) ; if ( configUrl == null ) { configUrl = ClassLoader . getSystemClassLoader ( ) . getResource ( confingFilename ) ; } File configFile = new File ( configUrl . toURI ( ) ) ; serializer . read ( config , configFile ) ; logger . info ( "load config from {}" , configFile . getAbsolutePath ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "axu4j.xml\n{}" , config ) ; } } catch ( Exception e ) { logger . error ( "Fail to load axu4j.xml" , e ) ; } }
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 . wrap ( e , CryptoErrorCode . ALGORITHM_CANNOT_BE_FOUND ) ; } catch ( Exception e ) { throw SeedException . wrap ( e , CryptoErrorCode . UNEXPECTED_EXCEPTION ) ; } }
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 , EncryptionServiceFactory > encryptionServiceFactories = new HashMap < > ( ) ; if ( keyPairConfigurations != null && keyStores != null ) { for ( KeyPairConfig keyPairConfig : keyPairConfigurations ) { String keyStoreName = keyPairConfig . getKeyStoreName ( ) ; if ( ! encryptionServiceFactories . containsKey ( keyStoreName ) ) { EncryptionServiceFactory factory = new EncryptionServiceFactory ( cryptoConfig , keyStores . get ( keyStoreName ) ) ; encryptionServiceFactories . put ( keyStoreName , factory ) ; } EncryptionServiceFactory serviceFactory = encryptionServiceFactories . get ( keyStoreName ) ; EncryptionService encryptionService ; if ( keyPairConfig . getPassword ( ) != null ) { encryptionService = serviceFactory . create ( keyPairConfig . getAlias ( ) , keyPairConfig . getPassword ( ) . toCharArray ( ) ) ; } else { encryptionService = serviceFactory . create ( keyPairConfig . getAlias ( ) ) ; } if ( keyPairConfig . getQualifier ( ) != null ) { encryptionServices . put ( createKeyFromQualifier ( keyPairConfig . getQualifier ( ) ) , encryptionService ) ; } else { encryptionServices . put ( Key . get ( EncryptionService . class , Names . named ( keyPairConfig . getAlias ( ) ) ) , encryptionService ) ; } } } return encryptionServices ; }
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 . putAll ( other . map ) ; map . values ( ) . removeIf ( Objects :: isNull ) ; return this ; }
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 ( ) ) ; this . acceptPrefer . addAll ( hints . getAcceptPrefer ( ) ) ; mergeDocs ( hints ) ; preconditionReq . addAll ( hints . getPreconditionReq ( ) ) ; authReq . addAll ( hints . getAuthReq ( ) ) ; mergeStatus ( hints ) ; }
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 ) ; } String config = null ; if ( pair . length == 2 ) { config = StringUtils . clean ( pair [ 1 ] ) ; config = config . substring ( 0 , config . length ( ) - 1 ) ; config = StringUtils . clean ( config ) ; if ( config != null && config . startsWith ( "\"" ) && config . endsWith ( "\"" ) ) { String stripped = config . substring ( 1 , config . length ( ) - 1 ) ; stripped = StringUtils . clean ( stripped ) ; if ( stripped != null && stripped . indexOf ( '"' ) == - 1 ) { config = stripped ; } } } return new String [ ] { name , config } ; }
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 . substring ( 0 , p ) ; if ( ( p = credentials . indexOf ( ':' ) ) != - 1 ) { result [ 0 ] = credentials . substring ( 0 , p ) ; result [ 1 ] = credentials . substring ( p + 1 ) ; } else { result [ 0 ] = credentials ; result [ 1 ] = "" ; } return Optional . of ( result ) ; } } return Optional . empty ( ) ; }
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 ) ; if ( ( p = url . indexOf ( ':' ) ) != - 1 ) { result [ 0 ] = url . substring ( 0 , p ) ; result [ 1 ] = url . substring ( p + 1 ) ; } else { result [ 0 ] = url ; result [ 1 ] = defPort ; } p = result [ 0 ] . indexOf ( '/' ) ; if ( p != - 1 ) { result [ 0 ] = result [ 0 ] . substring ( 0 , p ) ; } p = result [ 1 ] . indexOf ( '/' ) ; if ( p != - 1 ) { result [ 1 ] = result [ 1 ] . substring ( 0 , p ) ; } return Optional . of ( result ) ; } return Optional . empty ( ) ; }
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 ( ) ; transactionLogger . log ( "invocation ended" , transactionLogger ) ; } catch ( Exception exception ) { doHandleException ( transactionLogger , exception , transactionMetadata , currentTransaction ) ; } return result ; }
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 uriTemplateBuilder . build ( ) . getTemplate ( ) ; }
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 . hints . merge ( resource . hints ( ) ) ; } }
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 != null ) { Map < String , Object > hintsRepresentation = hints . toRepresentation ( ) ; if ( ! hintsRepresentation . isEmpty ( ) ) { representation . put ( "hints" , hintsRepresentation ) ; } } return representation ; }
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 ScopePermission ( permission . getPermission ( ) , scope ) ; scopePermissions . add ( sp ) ; } } else { stringPermissions . add ( permission . getPermission ( ) ) ; } } }
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 exceptionTranslator . translate ( exception ) ; } } return SeedException . wrap ( exception , CoreErrorCode . UNEXPECTED_EXCEPTION ) ; } }
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 = ( ( 1.0d / timeToScrollOneItem ) * 1000 ) ; if ( newSpeed < ( 0.9f * mSpeed ) ) { mSpeed *= 0.9f ; } else if ( newSpeed > ( 1.1f * mSpeed ) ) { mSpeed *= 1.1f ; } else { mSpeed = newSpeed ; } } else { mSpeed = ( ( 1.0d / timeToScrollOneItem ) * 1000 ) ; } mPreviousFirstVisibleItem = firstVisibleItem ; mPreviousEventTime = currTime ; } }
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 ( mSimulateGridWithList ) { ViewGroup itemRow = ( ViewGroup ) item ; for ( int i = 0 ; i < itemRow . getChildCount ( ) ; i ++ ) doJazzinessImpl ( itemRow . getChildAt ( i ) , position , scrollDirection ) ; } else { doJazzinessImpl ( item , position , scrollDirection ) ; } mAlreadyAnimatedItems . add ( position ) ; } }
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 , eventCollection , event , keenProperties , new IllegalStateException ( "No project specified, but no default project found" ) ) ; return ; } KeenProject useProject = ( project == null ? defaultProject : project ) ; try { Map < String , Object > newEvent = validateAndBuildEvent ( useProject , eventCollection , event , keenProperties ) ; publish ( useProject , eventCollection , newEvent ) ; handleSuccess ( callback , project , eventCollection , event , keenProperties ) ; } catch ( Exception e ) { handleFailure ( callback , project , eventCollection , event , keenProperties , e ) ; } }
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" ) ) ; return ; } if ( ! isNetworkConnected ( ) ) { KeenLogging . log ( "Not sending events because there is no network connection. " + "Events will be retried next time `sendQueuedEvents` is called." ) ; handleFailure ( callback , new Exception ( "Network not connected." ) ) ; return ; } KeenProject useProject = ( project == null ? defaultProject : project ) ; try { String projectId = useProject . getProjectId ( ) ; Map < String , List < Object > > eventHandles = eventStore . getHandles ( projectId ) ; Map < String , List < Map < String , Object > > > events = buildEventMap ( projectId , eventHandles ) ; String response = publishAll ( useProject , events ) ; if ( response != null ) { try { handleAddEventsResponse ( eventHandles , response ) ; } catch ( Exception e ) { KeenLogging . log ( "Error handling response to batch publish: " + e . getMessage ( ) ) ; } } handleSuccess ( callback ) ; } catch ( Exception e ) { handleFailure ( callback , e ) ; } }
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." ) ; } validateEventCollection ( eventCollection ) ; validateEvent ( event ) ; KeenLogging . log ( String . format ( Locale . US , "Adding event to collection: %s" , eventCollection ) ) ; Map < String , Object > newEvent = new HashMap < String , Object > ( ) ; Map < String , Object > mergedKeenProperties = new HashMap < String , Object > ( ) ; if ( null != globalProperties ) { mergeGlobalProperties ( getGlobalProperties ( ) , mergedKeenProperties , newEvent ) ; } GlobalPropertiesEvaluator globalPropertiesEvaluator = getGlobalPropertiesEvaluator ( ) ; if ( globalPropertiesEvaluator != null ) { mergeGlobalProperties ( globalPropertiesEvaluator . getGlobalProperties ( eventCollection ) , mergedKeenProperties , newEvent ) ; } if ( keenProperties != null ) { mergedKeenProperties . putAll ( keenProperties ) ; } if ( ! mergedKeenProperties . containsKey ( "timestamp" ) ) { Calendar currentTime = Calendar . getInstance ( ) ; String timestamp = ISO_8601_FORMAT . format ( currentTime . getTime ( ) ) ; mergedKeenProperties . put ( "timestamp" , timestamp ) ; } newEvent . put ( "keen" , mergedKeenProperties ) ; newEvent . putAll ( event ) ; return newEvent ; }
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" ) ; if ( keen instanceof Map ) { keenProperties . putAll ( ( Map ) keen ) ; } newEvent . putAll ( globalProperties ) ; } }
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 new InvalidEventCollectionException ( "An event collection name cannot be longer than 256 characters." ) ; } }
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 InvalidEventException ( "An event cannot contain a root-level property named 'keen'." ) ; } } else if ( depth > KeenConstants . MAX_EVENT_DEPTH ) { throw new InvalidEventException ( "An event's depth (i.e. layers of nesting) cannot exceed " + KeenConstants . MAX_EVENT_DEPTH ) ; } for ( Map . Entry < String , Object > entry : event . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( key . contains ( "." ) ) { throw new InvalidEventException ( "An event cannot contain a property with the period (.) character in " + "it." ) ; } if ( key . length ( ) > 256 ) { throw new InvalidEventException ( "An event cannot contain a property name longer than 256 characters." ) ; } validateEventValue ( entry . getValue ( ) , depth ) ; } }
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 characters." ) ; } } else if ( value instanceof Map ) { validateEvent ( ( Map < String , Object > ) value , depth + 1 ) ; } else if ( value instanceof Iterable ) { for ( Object listElement : ( Iterable ) value ) { validateEventValue ( listElement , depth ) ; } } }
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 < Object > > entry : eventHandles . entrySet ( ) ) { String eventCollection = entry . getKey ( ) ; List < Object > handles = entry . getValue ( ) ; if ( handles == null || handles . size ( ) == 0 ) { continue ; } List < Map < String , Object > > events = new ArrayList < Map < String , Object > > ( handles . size ( ) ) ; Map < String , Integer > attempts ; if ( eventStore instanceof KeenAttemptCountingEventStore ) { synchronized ( attemptsLock ) { try { attempts = getAttemptsMap ( projectId , eventCollection ) ; } catch ( IOException ex ) { attempts = new HashMap < String , Integer > ( ) ; KeenLogging . log ( "Failed to read attempt counts map. Events will still be POSTed. " + "Exception: " + ex ) ; } for ( Object handle : handles ) { Map < String , Object > event = getEvent ( handle ) ; String attemptsKey = "" + handle . hashCode ( ) ; Integer remainingAttempts = attempts . get ( attemptsKey ) ; if ( remainingAttempts == null ) { remainingAttempts = 1 ; } remainingAttempts -- ; attempts . put ( attemptsKey , remainingAttempts ) ; if ( remainingAttempts >= 0 ) { events . add ( event ) ; } else { eventStore . remove ( handle ) ; attempts . remove ( attemptsKey ) ; } } try { setAttemptsMap ( projectId , eventCollection , attempts ) ; } catch ( IOException ex ) { KeenLogging . log ( "Failed to update event POST attempts counts while sending queued " + "events. Events will still be POSTed. Exception: " + ex ) ; } } } else { for ( Object handle : handles ) { events . add ( getEvent ( handle ) ) ; } } result . put ( eventCollection , events ) ; } return result ; }
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 ) ; return publishObject ( project , url , events ) ; }
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 ) callback ) . onSuccess ( project , eventCollection , event , keenProperties ) ; } } catch ( Exception userException ) { } } }
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 ) eventStore ; String attemptsJSON = res . getAttempts ( projectId , eventCollection ) ; if ( attemptsJSON != null ) { StringReader reader = new StringReader ( attemptsJSON ) ; Map < String , Object > attemptTmp = jsonHandler . readJson ( reader ) ; for ( Entry < String , Object > entry : attemptTmp . entrySet ( ) ) { if ( entry . getValue ( ) instanceof Number ) { attempts . put ( entry . getKey ( ) , ( ( Number ) entry . getValue ( ) ) . intValue ( ) ) ; } } } } return attempts ; }
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 = new StringWriter ( ) ; jsonHandler . writeJson ( writer , attempts ) ; String attemptsJSON = writer . toString ( ) ; res . setAttempts ( projectId , eventCollection , attemptsJSON ) ; } finally { KeenUtils . closeQuietly ( writer ) ; } } }
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 || queryType == QueryType . MEDIAN || queryType == QueryType . PERCENTILE || queryType == QueryType . SUM || queryType == QueryType . SELECT_UNIQUE || queryType == QueryType . STANDARD_DEVIATION ) { if ( eventCollection == null || eventCollection . isEmpty ( ) || targetProperty == null || targetProperty . isEmpty ( ) ) { return false ; } } if ( queryType == QueryType . PERCENTILE ) { return percentile != null ; } return true ; }
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 . setConnectTimeout ( request . connectTimeout ) ; result . setReadTimeout ( request . readTimeout ) ; return result ; }
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 . setRequestProperty ( "Keen-Sdk" , "java-" + KeenVersion . getSdkVersion ( ) ) ; if ( request . body != null ) { if ( HttpMethods . GET . equals ( request . method ) || HttpMethods . DELETE . equals ( request . method ) ) { throw new IllegalStateException ( "Trying to send a GET request with a request " + "body, which would result in sending a POST." ) ; } connection . setDoOutput ( true ) ; connection . setRequestProperty ( "Content-Type" , "application/json" ) ; request . body . writeTo ( connection . getOutputStream ( ) ) ; } else { connection . connect ( ) ; } }
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 response contained data of an unexpected format." ) ; } ListResult actorsResult = null ; if ( responseMap . containsKey ( KeenQueryConstants . ACTORS ) ) { QueryResult genericActorsResult = constructQueryResult ( responseMap . get ( KeenQueryConstants . ACTORS ) , false , false ) ; if ( ! ( genericActorsResult instanceof ListResult ) ) { throw new KeenQueryClientException ( "'actors' property of response contained data of an unexpected format." ) ; } actorsResult = ( ListResult ) genericActorsResult ; } return new FunnelResult ( ( ListResult ) funnelResult , actorsResult ) ; }
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 ) ; } } return writer . toString ( ) ; } finally { reader . close ( ) ; } }
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 ( RequestUrlBuilder . class . getName ( ) ) . log ( Level . SEVERE , "Failed to format query URL." , ex ) ; throw new KeenQueryClientException ( "Failed to format query URL." , ex ) ; } }
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 : collectionDirs ) { String collectionName = directory . getName ( ) ; File [ ] files = getFilesInDir ( directory ) ; if ( files != null ) { List < Object > handleList = new ArrayList < Object > ( ) ; handleList . addAll ( Arrays . asList ( files ) ) ; handleMap . put ( collectionName , handleList ) ; } else { KeenLogging . log ( "Directory was null while getting event handles: " + collectionName ) ; } } } return handleMap ; }
Gets the handle map for all collections in the specified project cache directory .