idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
32,800
public static String getQualifierNamespace ( String qualifierAsString ) { int pos = qualifierAsString . indexOf ( DELIMITER , 1 ) ; if ( pos == - 1 ) { throw new IllegalArgumentException ( "Wrong qualifier format: '" + qualifierAsString + "'" ) ; } return qualifierAsString . substring ( 1 , pos ) ; }
Extracts qualifier namespace part from given qualifier string .
80
11
32,801
public static String getQualifierAction ( String qualifierAsString ) { int pos = qualifierAsString . lastIndexOf ( DELIMITER ) ; if ( pos == - 1 ) { throw new IllegalArgumentException ( "Wrong qualifier format: '" + qualifierAsString + "'" ) ; } return qualifierAsString . substring ( pos + 1 ) ; }
Extracts qualifier action part from given qualifier string .
78
11
32,802
public void add ( long instrument , long orderId , Side side , long price , long size ) { if ( orders . containsKey ( orderId ) ) { return ; } OrderBook book = books . get ( instrument ) ; if ( book == null ) { return ; } Order order = new Order ( book , side , price , size ) ; boolean bbo = book . add ( side , price , size ) ; orders . put ( orderId , order ) ; listener . update ( book , bbo ) ; }
Add an order to an order book .
108
8
32,803
public void modify ( long orderId , long size ) { Order order = orders . get ( orderId ) ; if ( order == null ) { return ; } OrderBook book = order . getOrderBook ( ) ; long newSize = Math . max ( 0 , size ) ; boolean bbo = book . update ( order . getSide ( ) , order . getPrice ( ) , newSize - order . getRemainingQuantity ( ) ) ; if ( newSize == 0 ) { orders . remove ( orderId ) ; } else { order . setRemainingQuantity ( newSize ) ; } listener . update ( book , bbo ) ; }
Modify an order in an order book . The order will retain its time priority . If the new size is zero the order is deleted from the order book .
135
32
32,804
public long execute ( long orderId , long quantity , long price ) { Order order = orders . get ( orderId ) ; if ( order == null ) { return 0 ; } return execute ( orderId , order , quantity , price ) ; }
Execute a quantity of an order in an order book . If the remaining quantity reaches zero the order is deleted from the order book .
51
27
32,805
public long cancel ( long orderId , long quantity ) { Order order = orders . get ( orderId ) ; if ( order == null ) { return 0 ; } OrderBook book = order . getOrderBook ( ) ; long remainingQuantity = order . getRemainingQuantity ( ) ; long canceledQuantity = Math . min ( quantity , remainingQuantity ) ; boolean bbo = book . update ( order . getSide ( ) , order . getPrice ( ) , - canceledQuantity ) ; if ( canceledQuantity == remainingQuantity ) { orders . remove ( orderId ) ; } else { order . reduce ( canceledQuantity ) ; } listener . update ( book , bbo ) ; return remainingQuantity - canceledQuantity ; }
Cancel a quantity of an order in an order book . If the remaining quantity reaches zero the order is deleted from the order book .
147
27
32,806
public void delete ( long orderId ) { Order order = orders . get ( orderId ) ; if ( order == null ) { return ; } OrderBook book = order . getOrderBook ( ) ; boolean bbo = book . update ( order . getSide ( ) , order . getPrice ( ) , - order . getRemainingQuantity ( ) ) ; orders . remove ( orderId ) ; listener . update ( book , bbo ) ; }
Delete an order from an order book .
94
8
32,807
public static Client rsocket ( ClientSettings clientSettings ) { RSocketClientCodec clientCodec = new RSocketClientCodec ( HeadersCodec . getInstance ( clientSettings . contentType ( ) ) , DataCodec . getInstance ( clientSettings . contentType ( ) ) ) ; RSocketClientTransport clientTransport = new RSocketClientTransport ( clientSettings , clientCodec , clientSettings . loopResources ( ) ) ; return new Client ( clientTransport , clientCodec , clientSettings . errorMapper ( ) ) ; }
Client on rsocket client transport .
117
7
32,808
public static Client websocket ( ClientSettings clientSettings ) { WebsocketClientCodec clientCodec = new WebsocketClientCodec ( DataCodec . getInstance ( clientSettings . contentType ( ) ) ) ; WebsocketClientTransport clientTransport = new WebsocketClientTransport ( clientSettings , clientCodec , clientSettings . loopResources ( ) ) ; return new Client ( clientTransport , clientCodec , clientSettings . errorMapper ( ) ) ; }
Client on websocket client transport .
100
7
32,809
public static Client http ( ClientSettings clientSettings ) { HttpClientCodec clientCodec = new HttpClientCodec ( DataCodec . getInstance ( clientSettings . contentType ( ) ) ) ; ClientTransport clientTransport = new HttpClientTransport ( clientSettings , clientCodec , clientSettings . loopResources ( ) ) ; return new Client ( clientTransport , clientCodec , clientSettings . errorMapper ( ) ) ; }
Client on http client transport .
97
6
32,810
public static void main ( String [ ] args ) throws Exception { ConfigRegistry configRegistry = ConfigBootstrap . configRegistry ( ) ; Config config = configRegistry . objectProperty ( "io.scalecube.services.examples" , Config . class ) . value ( ) . orElseThrow ( ( ) -> new IllegalStateException ( "Couldn't load config" ) ) ; LOGGER . info ( DECORATOR ) ; LOGGER . info ( "Starting Examples services on {}" , config ) ; LOGGER . info ( DECORATOR ) ; int numOfThreads = Optional . ofNullable ( config . numOfThreads ( ) ) . orElse ( Runtime . getRuntime ( ) . availableProcessors ( ) ) ; LOGGER . info ( "Number of worker threads: " + numOfThreads ) ; Microservices . builder ( ) . discovery ( serviceEndpoint -> serviceDiscovery ( serviceEndpoint , config ) ) . transport ( opts -> serviceTransport ( numOfThreads , opts , config ) ) . services ( new BenchmarkServiceImpl ( ) , new GreetingServiceImpl ( ) ) . startAwait ( ) ; Thread . currentThread ( ) . join ( ) ; }
Main method of gateway runner .
263
6
32,811
public < T > Gauge < T > register ( final String component , final String methodName , final Gauge < T > gauge ) { registry . register ( MetricRegistry . name ( component , methodName ) , new Gauge < T > ( ) { @ Override public T getValue ( ) { return gauge . getValue ( ) ; } } ) ; return gauge ; }
Register a Gauge and service registry .
81
8
32,812
public static Timer timer ( Metrics metrics , String component , String methodName ) { if ( metrics != null ) { return metrics . getTimer ( component , methodName ) ; } else { return null ; } }
if metrics is not null returns a Timer instance for a given component and method name .
45
18
32,813
public static Counter counter ( Metrics metrics , String component , String methodName ) { if ( metrics != null ) { return metrics . getCounter ( component , methodName ) ; } else { return null ; } }
if metrics is not null returns a Counter instance for a given component and method name .
44
17
32,814
public Order add ( long orderId , long size ) { Order order = new Order ( this , orderId , size ) ; orders . add ( order ) ; return order ; }
Add a new order .
37
5
32,815
public long match ( long orderId , Side side , long size , EmitterProcessor < MatchOrder > matchEmmiter ) { long quantity = size ; while ( quantity > 0 && ! orders . isEmpty ( ) ) { Order order = orders . get ( 0 ) ; long orderQuantity = order . size ( ) ; if ( orderQuantity > quantity ) { order . reduce ( quantity ) ; matchEmmiter . onNext ( new MatchOrder ( order . id ( ) , orderId , side , price , quantity , order . size ( ) ) ) ; quantity = 0 ; } else { orders . remove ( 0 ) ; matchEmmiter . onNext ( new MatchOrder ( order . id ( ) , orderId , side , price , orderQuantity , 0 ) ) ; quantity -= orderQuantity ; } } return quantity ; }
Match order if possible .
175
5
32,816
public static DelegatedLoopResources newServerLoopResources ( EventLoopGroup workerGroup ) { EventLoopGroup bossGroup = Epoll . isAvailable ( ) ? new EpollEventLoopGroup ( BOSS_THREADS_NUM , BOSS_THREAD_FACTORY ) : new NioEventLoopGroup ( BOSS_THREADS_NUM , BOSS_THREAD_FACTORY ) ; return new DelegatedLoopResources ( bossGroup , workerGroup ) ; }
Creates new loop resources for server side .
103
9
32,817
public boolean hasData ( Class < ? > dataClass ) { if ( dataClass == null ) { return false ; } return dataClass . isPrimitive ( ) ? hasData ( ) : dataClass . isInstance ( data ) ; }
Boolean method telling message contains data of given type or not .
50
13
32,818
public Collection < ServiceReference > serviceReferences ( ) { return serviceRegistrations . stream ( ) . flatMap ( sr -> sr . methods ( ) . stream ( ) . map ( sm -> new ServiceReference ( sm , sr , this ) ) ) . collect ( Collectors . toList ( ) ) ; }
Creates collection of service references from this service endpoint .
65
11
32,819
public Mono < Void > oneWay ( ServiceMessage request ) { return Mono . defer ( ( ) -> requestOne ( request , Void . class ) . then ( ) ) ; }
Issues fire - and - forget request .
37
9
32,820
public Mono < ServiceMessage > requestOne ( ServiceMessage request , Class < ? > responseType ) { return Mono . defer ( ( ) -> { String qualifier = request . qualifier ( ) ; if ( methodRegistry . containsInvoker ( qualifier ) ) { // local service. return methodRegistry . getInvoker ( request . qualifier ( ) ) . invokeOne ( request , ServiceMessageCodec :: decodeData ) . map ( this :: throwIfError ) ; } else { return addressLookup ( request ) . flatMap ( address -> requestOne ( request , responseType , address ) ) ; // remote service } } ) ; }
Issues request - and - reply request .
132
9
32,821
public Mono < ServiceMessage > requestOne ( ServiceMessage request , Class < ? > responseType , Address address ) { return Mono . defer ( ( ) -> { requireNonNull ( address , "requestOne address parameter is required and must not be null" ) ; requireNonNull ( transport , "transport is required and must not be null" ) ; return transport . create ( address ) . requestResponse ( request ) . map ( message -> ServiceMessageCodec . decodeData ( message , responseType ) ) . map ( this :: throwIfError ) ; } ) ; }
Given an address issues request - and - reply request to a remote address .
119
15
32,822
public Flux < ServiceMessage > requestMany ( ServiceMessage request , Class < ? > responseType ) { return Flux . defer ( ( ) -> { String qualifier = request . qualifier ( ) ; if ( methodRegistry . containsInvoker ( qualifier ) ) { // local service. return methodRegistry . getInvoker ( request . qualifier ( ) ) . invokeMany ( request , ServiceMessageCodec :: decodeData ) . map ( this :: throwIfError ) ; } else { return addressLookup ( request ) . flatMapMany ( address -> requestMany ( request , responseType , address ) ) ; // remote service } } ) ; }
Issues request to service which returns stream of service messages back .
135
13
32,823
public Flux < ServiceMessage > requestMany ( ServiceMessage request , Class < ? > responseType , Address address ) { return Flux . defer ( ( ) -> { requireNonNull ( address , "requestMany address parameter is required and must not be null" ) ; requireNonNull ( transport , "transport is required and must not be null" ) ; return transport . create ( address ) . requestStream ( request ) . map ( message -> ServiceMessageCodec . decodeData ( message , responseType ) ) . map ( this :: throwIfError ) ; } ) ; }
Given an address issues request to remote service which returns stream of service messages back .
121
16
32,824
public Flux < ServiceMessage > requestBidirectional ( Publisher < ServiceMessage > publisher , Class < ? > responseType ) { return Flux . from ( publisher ) . switchOnFirst ( ( first , messages ) -> { if ( first . hasValue ( ) ) { ServiceMessage request = first . get ( ) ; String qualifier = request . qualifier ( ) ; if ( methodRegistry . containsInvoker ( qualifier ) ) { // local service. return methodRegistry . getInvoker ( qualifier ) . invokeBidirectional ( messages , ServiceMessageCodec :: decodeData ) . map ( this :: throwIfError ) ; } else { // remote service return addressLookup ( request ) . flatMapMany ( address -> requestBidirectional ( messages , responseType , address ) ) ; } } return messages ; } ) ; }
Issues stream of service requests to service which returns stream of service messages back .
177
16
32,825
public Flux < ServiceMessage > requestBidirectional ( Publisher < ServiceMessage > publisher , Class < ? > responseType , Address address ) { return Flux . defer ( ( ) -> { requireNonNull ( address , "requestBidirectional address parameter is required and must not be null" ) ; requireNonNull ( transport , "transport is required and must not be null" ) ; return transport . create ( address ) . requestChannel ( publisher ) . map ( message -> ServiceMessageCodec . decodeData ( message , responseType ) ) . map ( this :: throwIfError ) ; } ) ; }
Given an address issues stream of service requests to service which returns stream of service messages back .
130
18
32,826
@ SuppressWarnings ( "unchecked" ) public < T > T api ( Class < T > serviceInterface ) { final ServiceCall serviceCall = this ; final Map < Method , MethodInfo > genericReturnTypes = Reflect . methodsInfo ( serviceInterface ) ; // noinspection unchecked return ( T ) Proxy . newProxyInstance ( getClass ( ) . getClassLoader ( ) , new Class [ ] { serviceInterface } , ( proxy , method , params ) -> { final MethodInfo methodInfo = genericReturnTypes . get ( method ) ; final Class < ? > returnType = methodInfo . parameterizedReturnType ( ) ; final boolean isServiceMessage = methodInfo . isRequestTypeServiceMessage ( ) ; Optional < Object > check = toStringOrEqualsOrHashCode ( method . getName ( ) , serviceInterface , params ) ; if ( check . isPresent ( ) ) { return check . get ( ) ; // toString, hashCode was invoked. } switch ( methodInfo . communicationMode ( ) ) { case FIRE_AND_FORGET : return serviceCall . oneWay ( toServiceMessage ( methodInfo , params ) ) ; case REQUEST_RESPONSE : return serviceCall . requestOne ( toServiceMessage ( methodInfo , params ) , returnType ) . transform ( asMono ( isServiceMessage ) ) ; case REQUEST_STREAM : return serviceCall . requestMany ( toServiceMessage ( methodInfo , params ) , returnType ) . transform ( asFlux ( isServiceMessage ) ) ; case REQUEST_CHANNEL : // this is REQUEST_CHANNEL so it means params[0] must be a publisher - its safe to // cast. return serviceCall . requestBidirectional ( Flux . from ( ( Publisher ) params [ 0 ] ) . map ( data -> toServiceMessage ( methodInfo , data ) ) , returnType ) . transform ( asFlux ( isServiceMessage ) ) ; default : throw new IllegalArgumentException ( "Communication mode is not supported: " + method ) ; } } ) ; }
Create proxy creates a java generic proxy instance by a given service interface .
441
14
32,827
private Optional < Object > toStringOrEqualsOrHashCode ( String method , Class < ? > serviceInterface , Object ... args ) { switch ( method ) { case "toString" : return Optional . of ( serviceInterface . toString ( ) ) ; case "equals" : return Optional . of ( serviceInterface . equals ( args [ 0 ] ) ) ; case "hashCode" : return Optional . of ( serviceInterface . hashCode ( ) ) ; default : return Optional . empty ( ) ; } }
check and handle toString or equals or hashcode method where invoked .
108
14
32,828
public static Microservices inject ( Microservices microservices , Collection < Object > services ) { services . forEach ( service -> Arrays . stream ( service . getClass ( ) . getDeclaredFields ( ) ) . forEach ( field -> injectField ( microservices , field , service ) ) ) ; services . forEach ( service -> processAfterConstruct ( microservices , service ) ) ; return microservices ; }
Inject instances to the microservices instance . either Microservices or ServiceProxy . Scan all local service instances and inject a service proxy .
87
27
32,829
public static Type parameterizedType ( Object object ) { if ( object != null ) { Type type = object . getClass ( ) . getGenericSuperclass ( ) ; if ( type instanceof ParameterizedType ) { return ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; } } return Object . class ; }
Util function that returns the parameterizedType of a given object .
77
14
32,830
public static Type parameterizedRequestType ( Method method ) { if ( method != null && method . getGenericParameterTypes ( ) . length > 0 ) { Type type = method . getGenericParameterTypes ( ) [ 0 ] ; if ( type instanceof ParameterizedType ) { return ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; } } return Object . class ; }
Util function that returns the parameterized of the request Type of a given object .
89
17
32,831
public static Collection < Class < ? > > serviceInterfaces ( Object serviceObject ) { Class < ? > [ ] interfaces = serviceObject . getClass ( ) . getInterfaces ( ) ; return Arrays . stream ( interfaces ) . filter ( interfaceClass -> interfaceClass . isAnnotationPresent ( Service . class ) ) . collect ( Collectors . toList ( ) ) ; }
Util function to get service interfaces collections from service instance .
80
12
32,832
public static void validateMethodOrThrow ( Method method ) { Class < ? > returnType = method . getReturnType ( ) ; if ( returnType . equals ( Void . TYPE ) ) { return ; } else if ( ! Publisher . class . isAssignableFrom ( returnType ) ) { throw new UnsupportedOperationException ( "Service method return type can be Publisher only" ) ; } if ( method . getParameterCount ( ) > 1 ) { throw new UnsupportedOperationException ( "Service method can accept 0 or 1 parameters only" ) ; } }
Util function to perform basic validation of service message request .
117
12
32,833
public static void main ( String [ ] args ) throws InterruptedException { Microservices ms1 = Microservices . builder ( ) . discovery ( ScalecubeServiceDiscovery :: new ) . transport ( ServiceTransports :: rsocketServiceTransport ) . defaultErrorMapper ( new ServiceAProviderErrorMapper ( ) ) // default mapper for whole node . services ( ServiceInfo . fromServiceInstance ( new ServiceAImpl ( ) ) . errorMapper ( new ServiceAProviderErrorMapper ( ) ) // mapper per service instance . build ( ) ) . startAwait ( ) ; System . err . println ( "ms1 started: " + ms1 . serviceAddress ( ) ) ; Microservices ms2 = Microservices . builder ( ) . discovery ( serviceEndpoint -> serviceDiscovery ( serviceEndpoint , ms1 ) ) . transport ( ServiceTransports :: rsocketServiceTransport ) . services ( call -> { ServiceA serviceA = call . errorMapper ( new ServiceAClientErrorMapper ( ) ) // service client error mapper . api ( ServiceA . class ) ; ServiceB serviceB = new ServiceBImpl ( serviceA ) ; return Collections . singleton ( ServiceInfo . fromServiceInstance ( serviceB ) . build ( ) ) ; } ) . startAwait ( ) ; System . err . println ( "ms2 started: " + ms2 . serviceAddress ( ) ) ; ms2 . call ( ) . api ( ServiceB . class ) . doAnotherStuff ( 0 ) . subscribe ( System . out :: println , th -> System . err . println ( "No service client mapper is defined for ServiceB, " + "so default scalecube mapper is used! -> " + th ) , ( ) -> System . out . println ( "Completed!" ) ) ; Thread . currentThread ( ) . join ( ) ; }
Example runner .
397
3
32,834
public Mono < ServiceMessage > invokeOne ( ServiceMessage message , BiFunction < ServiceMessage , Class < ? > , ServiceMessage > dataDecoder ) { return Mono . defer ( ( ) -> Mono . from ( invoke ( toRequest ( message , dataDecoder ) ) ) ) . map ( this :: toResponse ) . onErrorResume ( throwable -> Mono . just ( errorMapper . toMessage ( throwable ) ) ) ; }
Invokes service method with single response .
93
8
32,835
public Flux < ServiceMessage > invokeMany ( ServiceMessage message , BiFunction < ServiceMessage , Class < ? > , ServiceMessage > dataDecoder ) { return Flux . defer ( ( ) -> Flux . from ( invoke ( toRequest ( message , dataDecoder ) ) ) ) . map ( this :: toResponse ) . onErrorResume ( throwable -> Flux . just ( errorMapper . toMessage ( throwable ) ) ) ; }
Invokes service method with message stream response .
97
9
32,836
public Flux < ServiceMessage > invokeBidirectional ( Publisher < ServiceMessage > publisher , BiFunction < ServiceMessage , Class < ? > , ServiceMessage > dataDecoder ) { return Flux . from ( publisher ) . map ( message -> toRequest ( message , dataDecoder ) ) . transform ( this :: invoke ) . map ( this :: toResponse ) . onErrorResume ( throwable -> Flux . just ( errorMapper . toMessage ( throwable ) ) ) ; }
Invokes service method with bidirectional communication .
105
10
32,837
public ServiceMessage decode ( ByteBuf dataBuffer , ByteBuf headersBuffer ) throws MessageCodecException { ServiceMessage . Builder builder = ServiceMessage . builder ( ) ; if ( dataBuffer . isReadable ( ) ) { builder . data ( dataBuffer ) ; } if ( headersBuffer . isReadable ( ) ) { try ( ByteBufInputStream stream = new ByteBufInputStream ( headersBuffer , true ) ) { builder . headers ( headersCodec . decode ( stream ) ) ; } catch ( Throwable ex ) { ReferenceCountUtil . safestRelease ( dataBuffer ) ; // release data buf as well throw new MessageCodecException ( "Failed to decode message headers" , ex ) ; } } return builder . build ( ) ; }
Decode buffers .
161
4
32,838
public static ServiceMessage decodeData ( ServiceMessage message , Class < ? > dataType ) throws MessageCodecException { if ( dataType == null || ! message . hasData ( ByteBuf . class ) || ( ( ByteBuf ) message . data ( ) ) . readableBytes ( ) == 0 ) { return message ; } Object data ; Class < ? > targetType = message . isError ( ) ? ErrorData . class : dataType ; ByteBuf dataBuffer = message . data ( ) ; try ( ByteBufInputStream inputStream = new ByteBufInputStream ( dataBuffer , true ) ) { DataCodec dataCodec = DataCodec . getInstance ( message . dataFormatOrDefault ( ) ) ; data = dataCodec . decode ( inputStream , targetType ) ; } catch ( Throwable ex ) { throw new MessageCodecException ( "Failed to decode data on message q=" + message . qualifier ( ) , ex ) ; } return ServiceMessage . from ( message ) . data ( data ) . build ( ) ; }
Decode message .
224
4
32,839
public void enter ( long orderId , Side side , long price , long size ) { if ( orders . containsKey ( orderId ) ) { return ; } if ( side == Side . BUY ) { buy ( orderId , price , size ) ; } else { sell ( orderId , price , size ) ; } }
Enter an order to this order book .
68
8
32,840
public void cancel ( long orderId , long size ) { Order order = orders . get ( orderId ) ; if ( order == null ) { return ; } long remainingQuantity = order . size ( ) ; if ( size >= remainingQuantity ) { return ; } if ( size > 0 ) { order . resize ( size ) ; } else { delete ( order ) ; orders . remove ( orderId ) ; } cancelListener . onNext ( new CancelOrder ( orderId , remainingQuantity - size , size ) ) ; }
Cancel a quantity of an order in this order book . The size refers to the new order size . If the new order size is set to zero the order is deleted from this order book .
108
39
32,841
public static < T > Optional < T > findFirst ( Class < T > clazz ) { ServiceLoader < T > load = ServiceLoader . load ( clazz ) ; return StreamSupport . stream ( load . spliterator ( ) , false ) . findFirst ( ) ; }
Finds the first implementation of the given service type and creates its instance .
58
15
32,842
public static < T > Optional < T > findFirst ( Class < T > clazz , Predicate < ? super T > predicate ) { ServiceLoader < T > load = ServiceLoader . load ( clazz ) ; Stream < T > stream = StreamSupport . stream ( load . spliterator ( ) , false ) ; return stream . filter ( predicate ) . findFirst ( ) ; }
Finds the first implementation of the given service type using the given predicate to filter out found service types and creates its instance .
80
25
32,843
public static < T > Stream < T > findAll ( Class < T > clazz ) { ServiceLoader < T > load = ServiceLoader . load ( clazz ) ; return StreamSupport . stream ( load . spliterator ( ) , false ) ; }
Finds all implementations of the given service type and creates their instances .
53
14
32,844
@ RequiresTransaction public void put ( String key , Document document ) { database . put ( key , document ) ; }
Store the supplied document and metadata at the given key .
24
11
32,845
public < V > V runInTransaction ( Callable < V > operation , int retryCountOnLockTimeout , String ... keysToLock ) { // Start a transaction ... Transactions txns = repoEnv . getTransactions ( ) ; int retryCount = retryCountOnLockTimeout ; try { Transactions . Transaction txn = txns . begin ( ) ; if ( keysToLock . length > 0 ) { List < String > keysList = Arrays . asList ( keysToLock ) ; boolean locksAcquired = false ; while ( ! locksAcquired && retryCountOnLockTimeout -- >= 0 ) { locksAcquired = lockDocuments ( keysList ) ; } if ( ! locksAcquired ) { txn . rollback ( ) ; throw new org . modeshape . jcr . TimeoutException ( "Cannot acquire locks on: " + Arrays . toString ( keysToLock ) + " after " + retryCount + " attempts" ) ; } } try { V result = operation . call ( ) ; txn . commit ( ) ; return result ; } catch ( Exception e ) { // always rollback txn . rollback ( ) ; // throw as is (see below) throw e ; } } catch ( IllegalStateException | SystemException | NotSupportedException err ) { throw new SystemFailureException ( err ) ; } catch ( RuntimeException re ) { throw re ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Runs the given operation within a transaction after optionally locking some keys .
318
14
32,846
public void setStrategy ( double median , double standardDeviation , int sigma ) { this . bucketingStrategy = new StandardDeviationBucketingStrategy ( median , standardDeviation , sigma ) ; this . bucketWidth = null ; }
Set the histogram to use the standard deviation to determine the bucket sizes .
54
15
32,847
public void setStrategy ( T minimum , T maximum ) { this . bucketingStrategy = new ExplicitBucketingStrategy ( minimum , maximum ) ; this . bucketWidth = null ; }
Set the histogram to use the supplied minimum and maximum values to determine the bucket size .
41
18
32,848
public Histogram < T > setSignificantFigures ( int significantFigures ) { if ( significantFigures != this . significantFigures ) { this . significantFigures = significantFigures ; this . bucketWidth = null ; this . buckets . clear ( ) ; } return this ; }
Set the number of significant figures used in the calculation of the bucket widths .
61
16
32,849
public Histogram < T > setBucketCount ( int count ) { if ( count != this . bucketCount ) { this . bucketCount = count ; this . bucketWidth = null ; this . buckets . clear ( ) ; } return this ; }
Set the number of buckets that this histogram will use .
52
12
32,850
@ Override public synchronized void start ( BootstrapContext ctx ) throws ResourceAdapterInternalException { if ( engine == null ) { engine = new ModeShapeEngine ( ) ; engine . start ( ) ; } }
This is called when a resource adapter instance is bootstrapped .
44
13
32,851
@ Override public synchronized void stop ( ) { if ( engine != null ) { Future < Boolean > shutdown = engine . shutdown ( ) ; final int SHUTDOWN_TIMEOUT = 30 ; try { LOGGER . debug ( "Shutting down engine to stop resource adapter" ) ; if ( ! shutdown . get ( SHUTDOWN_TIMEOUT , TimeUnit . SECONDS ) ) { // ModeShapeEngine somehow remained running, nothing to be done about it. LOGGER . error ( JcaI18n . unableToStopEngine ) ; } } catch ( TimeoutException e ) { // Exception can be expected, but stack trace is logged to find where limit was defined LOGGER . error ( e , JcaI18n . unableToStopEngineWithinTimeLimit , SHUTDOWN_TIMEOUT ) ; } catch ( InterruptedException e ) { LOGGER . error ( e , JcaI18n . interruptedWhileStoppingJcaAdapter , e . getMessage ( ) ) ; } catch ( ExecutionException e ) { LOGGER . error ( e , JcaI18n . errorWhileStoppingJcaAdapter , e . getMessage ( ) ) ; } engine = null ; } }
This is called when a resource adapter instance is undeployed or during application server shutdown .
252
18
32,852
public Serializer < ? > serializerFor ( TypeFactory < ? > type ) { if ( type instanceof TupleFactory ) { return ( ( TupleFactory < ? > ) type ) . getSerializer ( this ) ; } return serializers . serializerFor ( type . getType ( ) ) ; }
Obtain a serializer for the given value type .
66
11
32,853
public BTreeKeySerializer < ? > bTreeKeySerializerFor ( TypeFactory < ? > type , boolean pack ) { return serializers . bTreeKeySerializerFor ( type . getType ( ) , type . getComparator ( ) , pack ) ; }
Obtain a serializer for the given key type .
57
11
32,854
JcrNodeDefinition getNodeDefinition ( NodeDefinitionId definitionId ) { if ( definitionId == null ) return null ; return nodeTypes ( ) . getChildNodeDefinition ( definitionId ) ; }
Get the node definition given the supplied identifier .
41
9
32,855
JcrPropertyDefinition getPropertyDefinition ( PropertyDefinitionId definitionId ) { if ( definitionId == null ) return null ; return nodeTypes ( ) . getPropertyDefinition ( definitionId ) ; }
Get the property definition given the supplied identifier .
40
9
32,856
public boolean isDerivedFrom ( String [ ] testTypeNames , String primaryTypeName , String [ ] mixinNames ) throws RepositoryException { CheckArg . isNotEmpty ( testTypeNames , "testTypeNames" ) ; CheckArg . isNotEmpty ( primaryTypeName , "primaryTypeName" ) ; NameFactory nameFactory = context ( ) . getValueFactories ( ) . getNameFactory ( ) ; Name [ ] typeNames = nameFactory . create ( testTypeNames ) ; // first check primary type for ( Name typeName : typeNames ) { JcrNodeType nodeType = getNodeType ( typeName ) ; if ( ( nodeType != null ) && nodeType . isNodeType ( primaryTypeName ) ) { return true ; } } // now check mixins if ( mixinNames != null ) { for ( String mixin : mixinNames ) { for ( Name typeName : typeNames ) { JcrNodeType nodeType = getNodeType ( typeName ) ; if ( ( nodeType != null ) && nodeType . isNodeType ( mixin ) ) { return true ; } } } } return false ; }
Determine if any of the test type names are equal to or have been derived from the primary type or any of the mixins .
244
28
32,857
public static int valueFromName ( String name ) { if ( name . equals ( TYPENAME_SIMPLE_REFERENCE ) ) { return SIMPLE_REFERENCE ; } return javax . jcr . PropertyType . valueFromName ( name ) ; }
Returns the numeric constant value of the type with the specified name .
59
13
32,858
protected CachedNode nodeInWorkspace ( AbstractSessionCache session ) { return isNew ( ) ? null : session . getWorkspace ( ) . getNode ( key ) ; }
Get the CachedNode within the workspace cache .
38
10
32,859
protected final Segment getSegment ( NodeCache cache , CachedNode parent ) { if ( parent != null ) { ChildReference ref = parent . getChildReferences ( cache ) . getChild ( key ) ; if ( ref == null ) { // This node doesn't exist in the parent throw new NodeNotFoundInParentException ( key , parent . getKey ( ) ) ; } return ref . getSegment ( ) ; } // This is the root node ... return workspace ( cache ) . childReferenceForRoot ( ) . getSegment ( ) ; }
Get the segment for this node .
117
7
32,860
private void emitValue ( Value value , ContentHandler contentHandler , int propertyType , boolean skipBinary ) throws RepositoryException , SAXException { if ( PropertyType . BINARY == propertyType ) { startElement ( contentHandler , JcrSvLexicon . VALUE , null ) ; // Per section 6.5 of the 1.0.1 spec, we need to emit one empty-value tag for each value if the property is // multi-valued and skipBinary is true if ( ! skipBinary ) { byte [ ] bytes = new byte [ BASE_64_BUFFER_SIZE ] ; int len ; Binary binary = value . getBinary ( ) ; try { InputStream stream = new Base64 . InputStream ( binary . getStream ( ) , Base64 . ENCODE ) ; try { while ( - 1 != ( len = stream . read ( bytes ) ) ) { contentHandler . characters ( new String ( bytes , 0 , len ) . toCharArray ( ) , 0 , len ) ; } } finally { stream . close ( ) ; } } catch ( IOException ioe ) { throw new RepositoryException ( ioe ) ; } finally { binary . dispose ( ) ; } } endElement ( contentHandler , JcrSvLexicon . VALUE ) ; } else { emitValue ( value . getString ( ) , contentHandler ) ; } }
Fires the appropriate SAX events on the content handler to build the XML elements for the value .
294
20
32,861
private Node nodeFor ( ITransaction transaction , ResolvedRequest request ) throws RepositoryException { return ( ( JcrSessionTransaction ) transaction ) . nodeFor ( request ) ; }
Get the node that corresponds to the resolved request using the supplied active transaction .
37
15
32,862
private String [ ] childrenFor ( ITransaction transaction , ResolvedRequest request ) throws RepositoryException { return ( ( JcrSessionTransaction ) transaction ) . childrenFor ( request ) ; }
Determine the names of the children given the supplied request
39
12
32,863
public RestQueryResult addColumn ( String name , String type ) { if ( ! StringUtil . isBlank ( name ) ) { columns . put ( name , type ) ; } return this ; }
Adds a new column to this result .
43
8
32,864
static < T > LocalDuplicateIndex < T > create ( String name , String workspaceName , DB db , Converter < T > converter , Serializer < T > valueSerializer , Comparator < T > comparator ) { return new LocalDuplicateIndex <> ( name , workspaceName , db , converter , valueSerializer , comparator ) ; }
Create a new index that allows duplicate values across all keys .
77
12
32,865
public String currentTransactionId ( ) { try { javax . transaction . Transaction txn = txnMgr . getTransaction ( ) ; return txn != null ? txn . toString ( ) : null ; } catch ( SystemException e ) { return null ; } }
Get a string representation of the current transaction if there already is an existing transaction .
59
16
32,866
public Transaction begin ( ) throws NotSupportedException , SystemException , RollbackException { // check if there isn't an active transaction already NestableThreadLocalTransaction localTx = LOCAL_TRANSACTION . get ( ) ; if ( localTx != null ) { // we have an existing local transaction so we need to be aware of nesting by calling 'begin' if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Found active ModeShape transaction '{0}' " , localTx ) ; } return localTx . begin ( ) ; } // Get the transaction currently associated with this thread (if there is one) ... javax . transaction . Transaction txn = txnMgr . getTransaction ( ) ; if ( txn != null && Status . STATUS_ACTIVE != txn . getStatus ( ) ) { // there is a user transaction which is not valid, so abort everything throw new IllegalStateException ( JcrI18n . errorInvalidUserTransaction . text ( txn ) ) ; } if ( txn == null ) { // There is no transaction or a leftover one which isn't active, so start a local one ... txnMgr . begin ( ) ; // create our wrapper ... localTx = new NestableThreadLocalTransaction ( txnMgr ) ; localTx . begin ( ) ; // notify the listener localTx . started ( ) ; return logTransactionInformation ( localTx ) ; } // There's an existing tx, meaning user transactions are being used SynchronizedTransaction synchronizedTransaction = transactionTable . get ( txn ) ; if ( synchronizedTransaction != null ) { // notify the listener synchronizedTransaction . started ( ) ; // we've already started our own transaction so just return it as is return logTransactionInformation ( synchronizedTransaction ) ; } else { synchronizedTransaction = new SynchronizedTransaction ( txnMgr , txn ) ; transactionTable . put ( txn , synchronizedTransaction ) ; // and register a synchronization txn . registerSynchronization ( synchronizedTransaction ) ; // and notify the listener synchronizedTransaction . started ( ) ; return logTransactionInformation ( synchronizedTransaction ) ; } }
Starts a new transaction if one does not already exist and associate it with the calling thread .
446
19
32,867
public void commit ( ) throws HeuristicRollbackException , RollbackException , HeuristicMixedException , SystemException { Transaction transaction = currentTransaction ( ) ; if ( transaction == null ) { throw new IllegalStateException ( "No active transaction" ) ; } transaction . commit ( ) ; }
Commits the current transaction if one exists .
61
9
32,868
public void rollback ( ) throws SystemException { Transaction transaction = currentTransaction ( ) ; if ( transaction == null ) { throw new IllegalStateException ( "No active transaction" ) ; } transaction . rollback ( ) ; }
Rolls back the current transaction if one exists .
47
10
32,869
protected NodeTypes without ( Collection < JcrNodeType > removedNodeTypes ) { if ( removedNodeTypes . isEmpty ( ) ) return this ; Collection < JcrNodeType > nodeTypes = new HashSet < JcrNodeType > ( this . nodeTypes . values ( ) ) ; nodeTypes . removeAll ( removedNodeTypes ) ; return new NodeTypes ( this . context , nodeTypes , getVersion ( ) + 1 ) ; }
Obtain a new version of this cache with the specified node types removed from the new cache .
93
19
32,870
protected NodeTypes with ( Collection < JcrNodeType > addedNodeTypes ) { if ( addedNodeTypes . isEmpty ( ) ) return this ; Collection < JcrNodeType > nodeTypes = new HashSet < JcrNodeType > ( this . nodeTypes . values ( ) ) ; // if there are updated node types, remove them first (hashcode is based on name alone), // else addAll() will ignore the changes. nodeTypes . removeAll ( addedNodeTypes ) ; nodeTypes . addAll ( addedNodeTypes ) ; return new NodeTypes ( this . context , nodeTypes , getVersion ( ) + 1 ) ; }
Obtain a new version of this cache with the specified node types added to the new cache .
134
19
32,871
public boolean isTypeOrSubtype ( Name nodeTypeName , Name candidateSupertypeName ) { if ( JcrNtLexicon . BASE . equals ( candidateSupertypeName ) ) { // If the candidate is 'nt:base', then every node type is a subtype ... return true ; } if ( nodeTypeName . equals ( candidateSupertypeName ) ) return true ; JcrNodeType nodeType = getNodeType ( nodeTypeName ) ; return nodeType != null && nodeType . isNodeType ( candidateSupertypeName ) ; }
Determine whether the node s given node type matches or extends the node type with the supplied name .
116
21
32,872
public boolean isTypeOrSubtype ( Set < Name > nodeTypeNames , Name candidateSupertypeName ) { for ( Name nodeTypeName : nodeTypeNames ) { if ( isTypeOrSubtype ( nodeTypeName , candidateSupertypeName ) ) return true ; } return false ; }
Determine whether at least one of the node s given node types matches or extends the node type with the supplied name .
61
25
32,873
public boolean allowsNameSiblings ( Name primaryType , Set < Name > mixinTypes ) { if ( isUnorderedCollection ( primaryType , mixinTypes ) ) { // regardless of the actual types, if at least one of them is an unordered collection, SNS are not allowed return false ; } if ( nodeTypeNamesThatAllowSameNameSiblings . contains ( primaryType ) ) return true ; if ( mixinTypes != null && ! mixinTypes . isEmpty ( ) ) { for ( Name mixinType : mixinTypes ) { if ( nodeTypeNamesThatAllowSameNameSiblings . contains ( mixinType ) ) return true ; } } return false ; }
Determine if either the primary type or any of the mixin types allows SNS .
144
19
32,874
public int getBucketIdLengthForUnorderedCollection ( Name nodeTypeName , Set < Name > mixinTypes ) { Set < Name > allTypes = new LinkedHashSet <> ( ) ; allTypes . add ( nodeTypeName ) ; if ( mixinTypes != null && ! mixinTypes . isEmpty ( ) ) { allTypes . addAll ( mixinTypes ) ; } for ( Name typeName : allTypes ) { if ( isTypeOrSubtype ( typeName , ModeShapeLexicon . TINY_UNORDERED_COLLECTION ) ) { return 1 ; } else if ( isTypeOrSubtype ( typeName , ModeShapeLexicon . SMALL_UNORDERED_COLLECTION ) ) { return 2 ; } else if ( isTypeOrSubtype ( typeName , ModeShapeLexicon . LARGE_UNORDERED_COLLECTION ) ) { return 3 ; } else if ( isTypeOrSubtype ( typeName , ModeShapeLexicon . HUGE_UNORDERED_COLLECTION ) ) { return 4 ; } } throw new IllegalArgumentException ( "None of the node types are known unordered collection types: " + allTypes ) ; }
Determine the length of a bucket ID for an unordered collection based on its type and possible mixins .
261
23
32,875
public boolean isReferenceProperty ( Name nodeTypeName , Name propertyName ) { JcrNodeType type = getNodeType ( nodeTypeName ) ; if ( type != null ) { for ( JcrPropertyDefinition propDefn : type . allPropertyDefinitions ( propertyName ) ) { int requiredType = propDefn . getRequiredType ( ) ; if ( requiredType == PropertyType . REFERENCE || requiredType == PropertyType . WEAKREFERENCE || requiredType == org . modeshape . jcr . api . PropertyType . SIMPLE_REFERENCE ) { return true ; } } } return false ; }
Determine if the named property on the node type is a reference property .
133
16
32,876
public boolean hasMandatoryPropertyDefinitions ( Name primaryType , Set < Name > mixinTypes ) { if ( mandatoryPropertiesNodeTypes . containsKey ( primaryType ) ) return true ; for ( Name mixinType : mixinTypes ) { if ( mandatoryPropertiesNodeTypes . containsKey ( mixinType ) ) return true ; } return false ; }
Determine if the named primary node type or mixin types has at least one mandatory property definitions declared on it or any of its supertypes .
76
30
32,877
public boolean hasMandatoryChildNodeDefinitions ( Name primaryType , Set < Name > mixinTypes ) { if ( mandatoryChildrenNodeTypes . containsKey ( primaryType ) ) return true ; for ( Name mixinType : mixinTypes ) { if ( mandatoryChildrenNodeTypes . containsKey ( mixinType ) ) return true ; } return false ; }
Determine if the named primary node type or mixin types has at least one mandatory child node definitions declared on it or any of its supertypes .
75
31
32,878
public boolean isQueryable ( Name nodeTypeName , Set < Name > mixinTypes ) { if ( nonQueryableNodeTypes . contains ( nodeTypeName ) ) { return false ; } if ( ! mixinTypes . isEmpty ( ) ) { for ( Name mixinType : mixinTypes ) { if ( nonQueryableNodeTypes . contains ( mixinType ) ) { return false ; } } } return true ; }
Check if the node type and mixin types are queryable or not .
91
15
32,879
boolean canRemoveItem ( Name primaryTypeNameOfParent , List < Name > mixinTypeNamesOfParent , Name itemName , boolean skipProtected ) { // First look in the primary type for a matching property definition... JcrNodeType primaryType = getNodeType ( primaryTypeNameOfParent ) ; if ( primaryType != null ) { for ( JcrPropertyDefinition definition : primaryType . allPropertyDefinitions ( itemName ) ) { // Skip protected definitions ... if ( skipProtected && definition . isProtected ( ) ) continue ; // If this definition is not mandatory, then we have found that we CAN remove the property ... return ! definition . isMandatory ( ) ; } } // Then, look in the primary type for a matching child node definition... if ( primaryType != null ) { for ( JcrNodeDefinition definition : primaryType . allChildNodeDefinitions ( itemName ) ) { // Skip protected definitions ... if ( skipProtected && definition . isProtected ( ) ) continue ; // If this definition is not mandatory, then we have found that we CAN remove all children ... return ! definition . isMandatory ( ) ; } } // Then, look in the mixin types for a matching property definition... if ( mixinTypeNamesOfParent != null && ! mixinTypeNamesOfParent . isEmpty ( ) ) { for ( Name mixinTypeName : mixinTypeNamesOfParent ) { JcrNodeType mixinType = getNodeType ( mixinTypeName ) ; if ( mixinType == null ) continue ; for ( JcrPropertyDefinition definition : mixinType . allPropertyDefinitions ( itemName ) ) { // Skip protected definitions ... if ( skipProtected && definition . isProtected ( ) ) continue ; // If this definition is not mandatory, then we have found that we CAN remove the property ... return ! definition . isMandatory ( ) ; } } } // Then, look in the mixin types for a matching child node definition... if ( mixinTypeNamesOfParent != null && ! mixinTypeNamesOfParent . isEmpty ( ) ) { for ( Name mixinTypeName : mixinTypeNamesOfParent ) { JcrNodeType mixinType = getNodeType ( mixinTypeName ) ; if ( mixinType == null ) continue ; for ( JcrNodeDefinition definition : mixinType . allChildNodeDefinitions ( itemName ) ) { // Skip protected definitions ... if ( skipProtected && definition . isProtected ( ) ) continue ; // If this definition is not mandatory, then we have found that we CAN remove all children ... return ! definition . isMandatory ( ) ; } } } // Nothing was found, so look for residual item definitions ... if ( ! itemName . equals ( JcrNodeType . RESIDUAL_NAME ) ) return canRemoveItem ( primaryTypeNameOfParent , mixinTypeNamesOfParent , JcrNodeType . RESIDUAL_NAME , skipProtected ) ; return false ; }
Determine if the node and property definitions of the supplied primary type and mixin types allow the item with the supplied name to be removed .
633
29
32,880
protected JcrNodeType findTypeInMapOrList ( Name typeName , Collection < JcrNodeType > pendingList ) { for ( JcrNodeType pendingNodeType : pendingList ) { if ( pendingNodeType . getInternalName ( ) . equals ( typeName ) ) { return pendingNodeType ; } } return nodeTypes . get ( typeName ) ; }
Finds the named type in the given collection of types pending registration if it exists else returns the type definition from the repository
78
24
32,881
protected List < JcrNodeType > supertypesFor ( NodeTypeDefinition nodeType , Collection < JcrNodeType > pendingTypes ) throws RepositoryException { assert nodeType != null ; List < JcrNodeType > supertypes = new LinkedList < JcrNodeType > ( ) ; boolean isMixin = nodeType . isMixin ( ) ; boolean needsPrimaryAncestor = ! isMixin ; String nodeTypeName = nodeType . getName ( ) ; for ( String supertypeNameStr : nodeType . getDeclaredSupertypeNames ( ) ) { Name supertypeName = nameFactory . create ( supertypeNameStr ) ; JcrNodeType supertype = findTypeInMapOrList ( supertypeName , pendingTypes ) ; if ( supertype == null ) { throw new InvalidNodeTypeDefinitionException ( JcrI18n . invalidSupertypeName . text ( supertypeNameStr , nodeTypeName ) ) ; } needsPrimaryAncestor &= supertype . isMixin ( ) ; supertypes . add ( supertype ) ; } // primary types (other than nt:base) always have at least one ancestor that's a primary type - nt:base if ( needsPrimaryAncestor ) { Name nodeName = nameFactory . create ( nodeTypeName ) ; if ( ! JcrNtLexicon . BASE . equals ( nodeName ) ) { JcrNodeType ntBase = findTypeInMapOrList ( JcrNtLexicon . BASE , pendingTypes ) ; assert ntBase != null ; supertypes . add ( 0 , ntBase ) ; } } return supertypes ; }
Returns the list of node types for the supertypes defined in the given node type .
350
17
32,882
final Collection < JcrNodeType > subtypesFor ( JcrNodeType nodeType ) { List < JcrNodeType > subtypes = new LinkedList < JcrNodeType > ( ) ; for ( JcrNodeType type : this . nodeTypes . values ( ) ) { if ( type . supertypes ( ) . contains ( nodeType ) ) { subtypes . add ( type ) ; } } return subtypes ; }
Returns the list of subtypes for the given node .
92
11
32,883
final Collection < JcrNodeType > declaredSubtypesFor ( JcrNodeType nodeType ) { CheckArg . isNotNull ( nodeType , "nodeType" ) ; String nodeTypeName = nodeType . getName ( ) ; List < JcrNodeType > subtypes = new LinkedList < JcrNodeType > ( ) ; for ( JcrNodeType type : this . nodeTypes . values ( ) ) { if ( Arrays . asList ( type . getDeclaredSupertypeNames ( ) ) . contains ( nodeTypeName ) ) { subtypes . add ( type ) ; } } return subtypes ; }
Returns the list of declared subtypes for the given node .
134
12
32,884
protected void validate ( JcrNodeType nodeType , List < JcrNodeType > supertypes , List < JcrNodeType > pendingTypes ) throws RepositoryException { validateSupertypes ( supertypes ) ; List < Name > supertypeNames = new ArrayList < Name > ( supertypes . size ( ) ) ; for ( JcrNodeType supertype : supertypes ) { supertypeNames . add ( supertype . getInternalName ( ) ) ; } boolean foundExact = false ; boolean foundResidual = false ; boolean foundSNS = false ; Name primaryItemName = nodeType . getInternalPrimaryItemName ( ) ; for ( JcrNodeDefinition node : nodeType . getDeclaredChildNodeDefinitions ( ) ) { validateChildNodeDefinition ( node , supertypeNames , pendingTypes ) ; if ( node . isResidual ( ) ) { foundResidual = true ; } if ( primaryItemName != null && primaryItemName . equals ( node . getInternalName ( ) ) ) { foundExact = true ; } if ( node . allowsSameNameSiblings ( ) ) { foundSNS = true ; } } for ( JcrPropertyDefinition prop : nodeType . getDeclaredPropertyDefinitions ( ) ) { validatePropertyDefinition ( prop , supertypeNames , pendingTypes ) ; if ( prop . isResidual ( ) ) { foundResidual = true ; } if ( primaryItemName != null && primaryItemName . equals ( prop . getInternalName ( ) ) ) { if ( foundExact ) { throw new RepositoryException ( JcrI18n . ambiguousPrimaryItemName . text ( primaryItemName ) ) ; } foundExact = true ; } } if ( primaryItemName != null && ! foundExact && ! foundResidual ) { throw new RepositoryException ( JcrI18n . invalidPrimaryItemName . text ( primaryItemName ) ) ; } Name internalName = nodeType . getInternalName ( ) ; if ( isUnorderedCollection ( internalName , supertypeNames ) ) { boolean isVersionable = isVersionable ( internalName , supertypeNames ) ; if ( isVersionable || foundSNS || nodeType . hasOrderableChildNodes ( ) ) { throw new RepositoryException ( JcrI18n . invalidUnorderedCollectionType . text ( internalName . toString ( ) ) ) ; } } }
Validates that the given node type definition is valid under the ModeShape and JCR type rules within the given context .
512
24
32,885
public boolean isCaseSensitive ( ) { switch ( getJcrType ( ) ) { case PropertyType . DOUBLE : case PropertyType . LONG : case PropertyType . DECIMAL : case PropertyType . WEAKREFERENCE : case PropertyType . REFERENCE : // conversion is case-insensitive case PropertyType . BOOLEAN : // conversion is case-insensitive return false ; } return true ; }
Get the indicator if the value is case sensitive
90
9
32,886
public boolean isSigned ( ) { switch ( getJcrType ( ) ) { case PropertyType . DOUBLE : case PropertyType . LONG : case PropertyType . DECIMAL : case PropertyType . DATE : return true ; } return false ; }
Get the indicator if the value is considered a signed value .
55
12
32,887
public static < T > Iterable < T > concat ( final Iterable < T > a , final Iterable < T > b ) { assert ( a != null ) ; assert ( b != null ) ; return ( ) -> Collections . concat ( a . iterator ( ) , b . iterator ( ) ) ; }
Concatenate two Iterable sources
67
8
32,888
public static < T > Iterator < T > concat ( final Iterator < T > a , final Iterator < T > b ) { assert ( a != null ) ; assert ( b != null ) ; return new Iterator < T > ( ) { @ Override public boolean hasNext ( ) { return a . hasNext ( ) || b . hasNext ( ) ; } @ Override public T next ( ) { if ( a . hasNext ( ) ) { return a . next ( ) ; } return b . next ( ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Concatenate two Iterators
137
7
32,889
public EsIndexColumn column ( String name ) { return columns . get ( noprefix ( name , EsIndexColumn . LENGTH_PREFIX , EsIndexColumn . LOWERCASE_PREFIX , EsIndexColumn . UPPERCASE_PREFIX ) ) ; }
Gets column with given name .
62
7
32,890
private String noprefix ( String name , String ... prefix ) { for ( int i = 0 ; i < prefix . length ; i ++ ) { if ( name . startsWith ( prefix [ i ] ) ) { name = name . replaceAll ( prefix [ i ] , "" ) ; } } return name ; }
Cuts name prefix for the pseudo column case .
67
10
32,891
public EsRequest mappings ( String type ) { EsRequest mappings = new EsRequest ( ) ; EsRequest mappingsValue = new EsRequest ( ) ; EsRequest mtype = new EsRequest ( ) ; EsRequest properties = new EsRequest ( ) ; for ( EsIndexColumn col : columns ( ) ) { properties . put ( col . getName ( ) , fieldMapping ( col . getType ( ) ) ) ; properties . put ( col . getLowerCaseFieldName ( ) , fieldMapping ( PropertyType . STRING ) ) ; properties . put ( col . getUpperCaseFieldName ( ) , fieldMapping ( PropertyType . STRING ) ) ; properties . put ( col . getLengthFieldName ( ) , fieldMapping ( PropertyType . LONG ) ) ; } mtype . put ( "properties" , properties ) ; mappingsValue . put ( type , mtype ) ; mappings . put ( "mappings" , mappingsValue ) ; return mappings ; }
Provides Elasticsearch mapping definition for the given type and this columns .
212
14
32,892
private EsRequest fieldMapping ( PropertyType type ) { EsRequest mappings = new EsRequest ( ) ; switch ( type ) { case BINARY : mappings . put ( "type" , "binary" ) ; break ; case BOOLEAN : mappings . put ( "type" , "boolean" ) ; break ; case DATE : mappings . put ( "type" , "long" ) ; break ; case LONG : case DECIMAL : mappings . put ( "type" , "long" ) ; break ; case DOUBLE : mappings . put ( "type" , "double" ) ; break ; default : mappings . put ( "type" , "string" ) ; mappings . put ( "analyzer" , "whitespace" ) ; } return mappings ; }
Creates mapping definition for the specified column type .
176
10
32,893
public void setControls ( FormItem ... items ) { FormItem [ ] controls = new FormItem [ items . length + 3 ] ; int i = 0 ; for ( FormItem item : items ) { controls [ i ++ ] = item ; } controls [ i ++ ] = new SpacerItem ( ) ; controls [ i ++ ] = confirmButton ; controls [ i ++ ] = cancelButton ; form . setItems ( controls ) ; }
Adds controls to this dialog .
92
6
32,894
public static void unzip ( InputStream zipFile , String dest ) throws IOException { byte [ ] buffer = new byte [ 1024 ] ; //create output directory is not exists File folder = new File ( dest ) ; if ( folder . exists ( ) ) { FileUtil . delete ( folder ) ; } folder . mkdir ( ) ; //get the zip file content try ( ZipInputStream zis = new ZipInputStream ( zipFile ) ) { //get the zipped file list entry ZipEntry ze = zis . getNextEntry ( ) ; File parent = new File ( dest ) ; while ( ze != null ) { String fileName = ze . getName ( ) ; if ( ze . isDirectory ( ) ) { File newFolder = new File ( parent , fileName ) ; newFolder . mkdir ( ) ; } else { File newFile = new File ( parent , fileName ) ; try ( FileOutputStream fos = new FileOutputStream ( newFile ) ) { int len ; while ( ( len = zis . read ( buffer ) ) > 0 ) { fos . write ( buffer , 0 , len ) ; } } } ze = zis . getNextEntry ( ) ; } zis . closeEntry ( ) ; } }
Unzip archive to the specified destination .
265
8
32,895
public static void zipDir ( String dirName , String nameZipFile ) throws IOException { try ( FileOutputStream fW = new FileOutputStream ( nameZipFile ) ; ZipOutputStream zip = new ZipOutputStream ( fW ) ) { addFolderToZip ( "" , dirName , zip ) ; } }
Compresses directory into zip archive .
67
7
32,896
public static void addFolderToZip ( String path , String srcFolder , ZipOutputStream zip ) throws IOException { File folder = new File ( srcFolder ) ; if ( folder . list ( ) . length == 0 ) { addFileToZip ( path , srcFolder , zip , true ) ; } else { for ( String fileName : folder . list ( ) ) { if ( path . equals ( "" ) ) { addFileToZip ( folder . getName ( ) , srcFolder + "/" + fileName , zip , false ) ; } else { addFileToZip ( path + "/" + folder . getName ( ) , srcFolder + "/" + fileName , zip , false ) ; } } } }
Adds folder to the archive .
152
6
32,897
public static void addFileToZip ( String path , String srcFile , ZipOutputStream zip , boolean flag ) throws IOException { File folder = new File ( srcFile ) ; if ( flag ) { zip . putNextEntry ( new ZipEntry ( path + "/" + folder . getName ( ) + "/" ) ) ; } else { if ( folder . isDirectory ( ) ) { addFolderToZip ( path , srcFile , zip ) ; } else { byte [ ] buf = new byte [ 1024 ] ; int len ; try ( FileInputStream in = new FileInputStream ( srcFile ) ) { zip . putNextEntry ( new ZipEntry ( path + "/" + folder . getName ( ) ) ) ; while ( ( len = in . read ( buf ) ) > 0 ) { zip . write ( buf , 0 , len ) ; } } } } }
Appends file to the archive .
185
7
32,898
public static String getExtension ( final String filename ) { Objects . requireNonNull ( filename , "filename cannot be null" ) ; int lastDotIdx = filename . lastIndexOf ( "." ) ; return lastDotIdx >= 0 ? filename . substring ( lastDotIdx ) : "" ; }
Returns the extension of a file including the dot .
69
10
32,899
public void read ( InputStream stream , Node outputNode ) throws Exception { read ( new InputSource ( stream ) , outputNode ) ; }
Read the document from the supplied stream and produce the derived content .
29
13