idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
2,100
private void addResponsesToAction ( ControllerRouteModel < Raml > elem , Action action ) { LOGGER . debug ( "responsesMimes.size:" + elem . getResponseMimes ( ) . size ( ) ) ; List < String > mimes = new ArrayList < > ( ) ; mimes . addAll ( elem . getResponseMimes ( ) ) ; if ( mimes . isEmpty ( ) ) { return ; } int i = 0 ; for ( String code : elem . getResponseCodes ( ) ) { LOGGER . debug ( "code:" + code ) ; String mime ; if ( mimes . size ( ) > i ) { mime = mimes . get ( i ) ; } else { mime = mimes . get ( 0 ) ; } Response resp = new Response ( ) ; if ( elem . getResponseDescriptions ( ) . size ( ) > i ) { resp . setDescription ( elem . getResponseDescriptions ( ) . get ( i ) ) ; } if ( elem . getResponseBodies ( ) . size ( ) > i ) { MimeType mimeType = new MimeType ( mime ) ; mimeType . setExample ( elem . getResponseBodies ( ) . get ( i ) . toString ( ) ) ; resp . setBody ( Collections . singletonMap ( mime , mimeType ) ) ; } action . getResponses ( ) . put ( code , resp ) ; i ++ ; } }
Add the response specification to the given action .
2,101
private void addActionFromRouteElem ( ControllerRouteModel < Raml > elem , Resource resource ) { Action action = new Action ( ) ; action . setType ( ActionType . valueOf ( elem . getHttpMethod ( ) . name ( ) ) ) ; action . setDescription ( elem . getDescription ( ) ) ; addBodyToAction ( elem , action ) ; addResponsesToAction ( elem , action ) ; for ( RouteParamModel < Raml > param : elem . getParams ( ) ) { AbstractParam ap = null ; switch ( param . getParamType ( ) ) { case FORM : MimeType formMime = action . getBody ( ) . get ( "application/x-www-form-urlencoded" ) ; if ( formMime == null ) { formMime = new MimeType ( "application/x-www-form-urlencoded" ) ; } if ( formMime . getFormParameters ( ) == null ) { formMime . setFormParameters ( new LinkedHashMap < String , List < FormParameter > > ( 2 ) ) ; } ap = new FormParameter ( ) ; formMime . getFormParameters ( ) . put ( param . getName ( ) , singletonList ( ( FormParameter ) ap ) ) ; break ; case PARAM : case PATH_PARAM : if ( ! ancestorOrIHasParam ( resource , param . getName ( ) ) ) { ap = new UriParameter ( ) ; resource . getUriParameters ( ) . put ( param . getName ( ) , ( UriParameter ) ap ) ; } break ; case QUERY : ap = new QueryParameter ( ) ; action . getQueryParameters ( ) . put ( param . getName ( ) , ( QueryParameter ) ap ) ; break ; case BODY : default : break ; } if ( ap == null ) { continue ; } ParamType type = typeConverter ( param . getValueType ( ) ) ; if ( type != null ) { ap . setType ( type ) ; } if ( param . isMandatory ( ) ) { ap . setRequired ( true ) ; } else { ap . setRequired ( false ) ; } if ( param . getMin ( ) != null ) { ap . setMinimum ( BigDecimal . valueOf ( param . getMin ( ) ) ) ; } if ( param . getMax ( ) != null ) { ap . setMinimum ( BigDecimal . valueOf ( param . getMax ( ) ) ) ; } if ( param . getDefaultValue ( ) != null ) { ap . setRequired ( false ) ; ap . setDefaultValue ( param . getDefaultValue ( ) ) ; } } resource . getActions ( ) . put ( action . getType ( ) , action ) ; }
Set the resource action from the wisdom route element .
2,102
private static Boolean ancestorOrIHasParam ( final Resource resource , String uriParamName ) { Resource ancestor = resource ; while ( ancestor != null ) { if ( ancestor . getUriParameters ( ) . containsKey ( uriParamName ) ) { return true ; } ancestor = ancestor . getParentResource ( ) ; } return false ; }
Check if the given resource or its ancestor have the uri param of given name .
2,103
private static ParamType typeConverter ( String typeName ) { if ( typeName == null || typeName . isEmpty ( ) ) { return null ; } if ( "Number" . equals ( typeName ) || "Long" . equalsIgnoreCase ( typeName ) || "Integer" . equals ( typeName ) || "int" . equals ( typeName ) ) { return ParamType . NUMBER ; } if ( "Boolean" . equalsIgnoreCase ( typeName ) ) { return ParamType . BOOLEAN ; } if ( "String" . equals ( typeName ) ) { return ParamType . STRING ; } if ( "Date" . equals ( typeName ) ) { return ParamType . DATE ; } if ( "File" . equals ( typeName ) ) { return ParamType . FILE ; } return null ; }
Convert a string version of the type name into a ParamType enum or null if nothing correspond .
2,104
public < T > T newInstance ( Context context , Class < T > type ) throws IllegalArgumentException { for ( ParameterFactory factory : factories ) { if ( factory . getType ( ) . equals ( type ) ) { return ( T ) factory . newInstance ( context ) ; } } throw new IllegalArgumentException ( "Unable to find a ParameterFactory able to create instance of " + type . getName ( ) ) ; }
Creates an instance of T from the given HTTP content . Unlike converters it does not handler generics or collections .
2,105
@ SuppressWarnings ( "unchecked" ) private < T > ParameterConverter < T > getConverter ( Class < T > type ) { if ( type == String . class ) { return ( ParameterConverter < T > ) StringConverter . INSTANCE ; } for ( ParameterConverter pc : converters ) { if ( pc . getType ( ) . equals ( type ) ) { return pc ; } } if ( type == Boolean . class ) { return ( ParameterConverter < T > ) BooleanConverter . INSTANCE ; } ParameterConverter < T > converter = ConstructorBasedConverter . getIfEligible ( type ) ; if ( converter != null ) { return converter ; } converter = ValueOfBasedConverter . getIfEligible ( type ) ; if ( converter != null ) { return converter ; } converter = FromBasedConverter . getIfEligible ( type ) ; if ( converter != null ) { return converter ; } converter = FromStringBasedConverter . getIfEligible ( type ) ; if ( converter != null ) { return converter ; } if ( type == Character . class ) { return ( ParameterConverter < T > ) CharacterConverter . INSTANCE ; } throw new NoSuchElementException ( "Cannot find a converter able to create instance of " + type . getName ( ) ) ; }
Searches a suitable converter to convert String to the given type .
2,106
public void start ( ) { metrics . register ( "executors" , new MetricSet ( ) { public Map < String , Metric > getMetrics ( ) { return ImmutableMap . < String , Metric > of ( "executors.count" , new Gauge < Integer > ( ) { public Integer getValue ( ) { return getExecutors ( ) . length ; } } , "schedulers.count" , new Gauge < Integer > ( ) { public Integer getValue ( ) { return getSchedulers ( ) . length ; } } , "hung.count" , new Gauge < Integer > ( ) { public Integer getValue ( ) { return getHungTasks ( ) ; } } , "completed.count" , new Gauge < Integer > ( ) { public Integer getValue ( ) { return getCompletedTasks ( ) ; } } ) ; } } ) ; for ( ManagedExecutorService service : executors ) { metrics . register ( service . name ( ) , metricsForExecutor ( service ) ) ; } for ( ManagedExecutorService service : schedulers ) { metrics . register ( service . name ( ) , metricsForExecutor ( service ) ) ; } }
Starts the extension . It registers the different metrics into the metric registry .
2,107
@ Route ( method = HttpMethod . GET , uri = "/monitor/executors.json" ) public Result data ( ) { return ok ( ImmutableMap . builder ( ) . put ( "executors" , getExecutorsAsMap ( executors ) ) . put ( "schedulers" , getExecutorsAsMap ( schedulers ) ) . put ( "hung" , getHungTasks ( ) ) . put ( "completed" , getCompletedTasks ( ) ) . build ( ) ) ; }
Retrieves the metrics about the executors . This method is intended to be used to handled an AJAX call .
2,108
public ReadStream < Buffer > handler ( Handler < Buffer > handler ) { if ( handler == null ) { throw new IllegalArgumentException ( "handler" ) ; } this . dataHandler = handler ; doRead ( ) ; return this ; }
Set a data handler . As data is read the handler will be called with the data .
2,109
private void doRead ( ) { if ( context == null ) { context = vertx . getOrCreateContext ( ) ; } if ( state == STATUS_ACTIVE ) { final Handler < Buffer > dataHandler = this . dataHandler ; final Handler < Void > closeHandler = this . closeHandler ; executor . submit ( ( Runnable ) ( ) -> { try { final byte [ ] bytes = readChunk ( ) ; if ( bytes == null || bytes . length == 0 ) { state = STATUS_CLOSED ; IOUtils . closeQuietly ( in ) ; context . runOnContext ( event -> { if ( closeHandler != null ) { closeHandler . handle ( null ) ; } } ) ; } else { context . runOnContext ( event -> { dataHandler . handle ( Buffer . buffer ( bytes ) ) ; doRead ( ) ; } ) ; } } catch ( final Exception e ) { state = STATUS_CLOSED ; IOUtils . closeQuietly ( in ) ; context . runOnContext ( event -> { if ( failureHandler != null ) { failureHandler . handle ( e ) ; } } ) ; } } ) ; } }
The method actually reading the stream . Except the first calls this method is executed within an Akka thread .
2,110
public AsyncInputStream resume ( ) { switch ( state ) { case STATUS_CLOSED : throw new IllegalStateException ( "Cannot resume, already closed" ) ; case STATUS_PAUSED : state = STATUS_ACTIVE ; doRead ( ) ; } return this ; }
Resumes the reading .
2,111
private byte [ ] readChunk ( ) throws Exception { if ( isEndOfInput ( ) ) { return EMPTY_BYTE_ARRAY ; } try { byte [ ] tmp = new byte [ chunkSize ] ; int readBytes = in . read ( tmp ) ; if ( readBytes <= 0 ) { return null ; } byte [ ] buffer = new byte [ readBytes ] ; System . arraycopy ( tmp , 0 , buffer , 0 , readBytes ) ; offset += readBytes ; return buffer ; } catch ( IOException e ) { IOUtils . closeQuietly ( in ) ; throw e ; } }
Reads a chunk .
2,112
public Pipeline watch ( ) { error = new File ( baseDir , "target/pipeline" ) ; FileUtils . deleteQuietly ( error ) ; mojo . getLog ( ) . debug ( "Creating the target/pipeline directory : " + error . mkdirs ( ) ) ; watcher = new FileAlterationMonitor ( Integer . getInteger ( "watch.period" , 2 ) * 1000 ) ; watcher . setThreadFactory ( new DefensiveThreadFactory ( "wisdom-pipeline-watcher" , mojo ) ) ; FileAlterationObserver srcObserver = new FileAlterationObserver ( new File ( baseDir , "src" ) , TrueFileFilter . INSTANCE ) ; PipelineWatcher listener = new PipelineWatcher ( this ) ; srcObserver . addListener ( listener ) ; watcher . addObserver ( srcObserver ) ; if ( pomFileMonitoring ) { FileAlterationObserver pomObserver = new FileAlterationObserver ( baseDir , new FileFilter ( ) { public boolean accept ( File file ) { return file . equals ( new File ( baseDir , "pom.xml" ) ) ; } } ) ; pomObserver . addListener ( listener ) ; watcher . addObserver ( pomObserver ) ; } try { mojo . getLog ( ) . info ( "Start watching " + baseDir . getAbsolutePath ( ) ) ; watcher . start ( ) ; } catch ( Exception e ) { mojo . getLog ( ) . error ( "Cannot start the watcher" , e ) ; } return this ; }
Starts the watching .
2,113
@ SuppressWarnings ( "unchecked" ) private void createErrorFile ( Watcher watcher , WatchingException e ) { mojo . getLog ( ) . debug ( "Creating error file for '" + e . getMessage ( ) + "' happening at " + e . getLine ( ) + ":" + e . getCharacter ( ) + " of " + e . getFile ( ) + ", created by watcher : " + watcher ) ; JSONObject obj = new JSONObject ( ) ; obj . put ( "message" , e . getMessage ( ) ) ; if ( watcher instanceof WatcherDelegate ) { obj . put ( "watcher" , ( ( WatcherDelegate ) watcher ) . getDelegate ( ) . getClass ( ) . getName ( ) ) ; } else { obj . put ( "watcher" , watcher . getClass ( ) . getName ( ) ) ; } if ( e . getFile ( ) != null ) { obj . put ( "file" , e . getFile ( ) . getAbsolutePath ( ) ) ; } if ( e . getLine ( ) != - 1 ) { obj . put ( "line" , e . getLine ( ) ) ; } if ( e . getCharacter ( ) != - 1 ) { obj . put ( "character" , e . getCharacter ( ) ) ; } if ( e . getCause ( ) != null ) { obj . put ( "cause" , e . getCause ( ) . getMessage ( ) ) ; } if ( e . getTitle ( ) != null ) { obj . put ( "title" , e . getTitle ( ) ) ; } try { FileUtils . writeStringToFile ( getErrorFileForWatcher ( watcher ) , obj . toJSONString ( ) , false ) ; } catch ( IOException e1 ) { mojo . getLog ( ) . error ( "Cannot write the error file" , e1 ) ; } }
Creates the error file storing the information from the given exception in JSON . This file is consumed by the Wisdom server to generate an error page reporting the watching exception .
2,114
private void cleanupErrorFile ( Watcher watcher ) { File file = getErrorFileForWatcher ( watcher ) ; FileUtils . deleteQuietly ( file ) ; }
Method called on each event before the processing deleting the error file is this file exists .
2,115
public void onFileChange ( File file ) { mojo . getLog ( ) . info ( EMPTY_STRING ) ; mojo . getLog ( ) . info ( "The watcher has detected a change in " + file . getAbsolutePath ( ) ) ; mojo . getLog ( ) . info ( EMPTY_STRING ) ; for ( Watcher watcher : watchers ) { if ( watcher . accept ( file ) ) { cleanupErrorFile ( watcher ) ; boolean continueProcessing ; try { continueProcessing = watcher . fileUpdated ( file ) ; } catch ( WatchingException e ) { mojo . getLog ( ) . debug ( watcher + " has thrown an exception while handling the " + file . getName ( ) + EMPTY_STRING + " update" , e ) ; mojo . getLog ( ) . error ( String . format ( WATCHING_EXCEPTION_MESSAGE , e . getMessage ( ) ) ) ; createErrorFile ( watcher , e ) ; continueProcessing = false ; } if ( ! continueProcessing ) { break ; } } } mojo . getLog ( ) . info ( EMPTY_STRING ) ; mojo . getLog ( ) . info ( EMPTY_STRING ) ; }
The FAM has detected a change in a file . It dispatches this event to the watchers plugged on the current pipeline .
2,116
private static void addMimeToCompressedWithExtension ( String extension ) { String mime = EXTENSIONS . get ( extension ) ; if ( mime != null && ! COMPRESSED_MIME . contains ( mime ) ) { COMPRESSED_MIME . add ( mime ) ; } }
Adds a mime - type to the compressed list .
2,117
private static void addMimeGroups ( String ... groups ) { for ( String mimeType : EXTENSIONS . values ( ) ) { for ( String group : groups ) { if ( mimeType . startsWith ( group ) && ! COMPRESSED_MIME . contains ( mimeType ) ) { COMPRESSED_MIME . add ( mimeType ) ; } } } }
Adds a group to the compressed list .
2,118
public Runnable function ( ) { return new Runnable ( ) { public void run ( ) { try { method . invoke ( scheduled ) ; } catch ( IllegalAccessException e ) { WisdomTaskScheduler . getLogger ( ) . error ( "Error while accessing to the scheduled method {}.{}" , scheduled . getClass ( ) . getName ( ) , method . getName ( ) , e ) ; } catch ( InvocationTargetException e ) { WisdomTaskScheduler . getLogger ( ) . error ( "Error in scheduled method {}.{}" , scheduled . getClass ( ) . getName ( ) , method . getName ( ) , e ) ; } } } ; }
Gets the runnable invoking the scheduled method .
2,119
public void updateHeaders ( RequestContext context , Multimap < String , String > headers ) { if ( ! proxyPassReverse ) { return ; } for ( Map . Entry < String , String > h : new LinkedHashSet < > ( headers . entries ( ) ) ) { if ( REVERSE_PROXY_HEADERS . contains ( h . getKey ( ) ) ) { URI location = URI . create ( h . getValue ( ) ) . normalize ( ) ; if ( location . isAbsolute ( ) && isBackendLocation ( location ) ) { String initial = context . request ( ) . uri ( ) ; URI uri = URI . create ( initial ) ; try { URI newURI = new URI ( uri . getScheme ( ) , uri . getUserInfo ( ) , uri . getHost ( ) , uri . getPort ( ) , location . getPath ( ) , location . getQuery ( ) , location . getFragment ( ) ) ; headers . remove ( h . getKey ( ) , h . getValue ( ) ) ; headers . put ( h . getKey ( ) , newURI . toString ( ) ) ; } catch ( URISyntaxException e ) { logger . error ( "Cannot manipulate the header {} (value={}) to enforce reverse routing" , h . getKey ( ) , h . getValue ( ) , e ) ; } } } } }
Callback that can be overridden to customize the header ot the request . This method implements the reverse routing . It updates URLs contained in the headers .
2,120
public synchronized void addMember ( BalancerMember member ) { if ( member . getBalancerName ( ) . equals ( name ) ) { logger . info ( "Adding balancer member '{}' to balancer '{}'" , member . getName ( ) , name ) ; members . add ( member ) ; } }
Adds a new member .
2,121
public synchronized void removeMember ( BalancerMember member ) { if ( members . remove ( member ) ) { logger . info ( "Removing balancer member '{}' from balancer '{}'" , member . getName ( ) , name ) ; } }
Removes a member .
2,122
public Collection < ResourceBundle > bundles ( ) { Set < ResourceBundle > bundles = new LinkedHashSet < > ( ) ; for ( I18nExtension extension : extensions ) { bundles . add ( extension . bundle ( ) ) ; } return bundles ; }
Retrieves the set of resource bundles handled by the system .
2,123
public Collection < ResourceBundle > bundles ( Locale locale ) { Set < ResourceBundle > bundles = new LinkedHashSet < > ( ) ; for ( I18nExtension extension : extensions ) { if ( extension . locale ( ) . equals ( locale ) ) { bundles . add ( extension . bundle ( ) ) ; } } return bundles ; }
Retrieves the set of resource bundles handled by the system providing messages for the given locale .
2,124
public String etag ( Locale locale ) { String etag = etags . get ( locale ) ; if ( etag == null ) { return "0" ; } else { return etag ; } }
Retrieves the ETAG for the given locale .
2,125
@ Bind ( aggregate = true ) public void bindFactory ( Factory factory ) { if ( ! ( factory instanceof ComponentFactory ) ) { return ; } String cn = factory . getClassName ( ) ; if ( cn == null ) { return ; } try { Class clazz = ( ( ComponentFactory ) factory ) . loadClass ( cn ) ; InstantiatedBy annotation = ( InstantiatedBy ) clazz . getAnnotation ( InstantiatedBy . class ) ; if ( annotation != null ) { LOGGER . info ( "Factory annotated with `@InstantiatedBy` found : {}, configuration : {}" , factory . getName ( ) , annotation . value ( ) ) ; addInstanceDeclaration ( factory , annotation . value ( ) ) ; } } catch ( ClassNotFoundException e ) { LOGGER . error ( "Cannot load the component class {}" , cn , e ) ; } }
Bind a factory .
2,126
public void unbindFactory ( Factory factory ) { try { lock . lock ( ) ; InstanceDeclaration declaration = getDeclarationByFactory ( factory ) ; if ( declaration != null ) { LOGGER . info ( "Disposing instance created by" ) ; declaration . dispose ( ) ; declarations . remove ( declaration ) ; } } finally { lock . unlock ( ) ; } }
Unbinds a factory .
2,127
public void configurationEvent ( ConfigurationEvent event ) { LOGGER . debug ( "event received : " + event . getPid ( ) + " - " + event . getType ( ) ) ; try { lock . lock ( ) ; final List < InstanceDeclaration > impacted = getDeclarationsByConfiguration ( event . getPid ( ) , event . getFactoryPid ( ) ) ; if ( impacted . isEmpty ( ) ) { return ; } switch ( event . getType ( ) ) { case ConfigurationEvent . CM_DELETED : for ( InstanceDeclaration declaration : impacted ) { LOGGER . info ( "Configuration " + event . getPid ( ) + " deleted" ) ; declaration . dispose ( event . getPid ( ) ) ; } break ; case ConfigurationEvent . CM_UPDATED : for ( InstanceDeclaration declaration : impacted ) { final Configuration configuration = find ( event . getPid ( ) ) ; if ( configuration == null ) { LOGGER . error ( "Weird case, a matching declaration was found, but cannot be found a second " + "times, may be because of rapid changes in the config admin" ) ; } else { declaration . attachOrUpdate ( configuration ) ; } } break ; } } finally { lock . unlock ( ) ; } }
Receives a configuration event .
2,128
public static List < FactoryModel > factories ( BundleContext context ) { List < FactoryModel > factories = new ArrayList < FactoryModel > ( ) ; try { for ( ServiceReference ref : context . getServiceReferences ( Factory . class , null ) ) { factories . add ( new FactoryModel ( ( Factory ) context . getService ( ref ) ) ) ; } for ( ServiceReference ref : context . getServiceReferences ( HandlerFactory . class , null ) ) { factories . add ( new FactoryModel ( ( Factory ) context . getService ( ref ) ) ) ; } } catch ( InvalidSyntaxException e ) { } return factories ; }
Creates a list of factory model from the factory exposed . These factories are retrieved from the bundle context .
2,129
public static String getPrefixedUri ( String prefix , String uri ) { String localURI = uri ; if ( localURI . length ( ) > 0 ) { if ( ! localURI . startsWith ( "/" ) && ! prefix . endsWith ( "/" ) && Character . isLetterOrDigit ( localURI . indexOf ( 0 ) ) ) { localURI = prefix + "/" + localURI ; } else { localURI = prefix + localURI ; } } else { return prefix ; } return localURI ; }
Prepends the given prefix to the given uri .
2,130
public static List < ActionParameter > buildActionParameterList ( Method method ) { List < ActionParameter > arguments = new ArrayList < > ( ) ; Annotation [ ] [ ] annotations = method . getParameterAnnotations ( ) ; Class < ? > [ ] typesOfParameters = method . getParameterTypes ( ) ; Type [ ] genericTypeOfParameters = method . getGenericParameterTypes ( ) ; for ( int i = 0 ; i < annotations . length ; i ++ ) { arguments . add ( ActionParameter . from ( method , annotations [ i ] , typesOfParameters [ i ] , genericTypeOfParameters [ i ] ) ) ; } return arguments ; }
Gets the list of Argument i . e . formal parameter metadata for the given method .
2,131
public static ActionParameter from ( Member member , Annotation [ ] annotations , Class < ? > rawType , Type genericType ) { ActionParameter parameter = null ; String defaultValue = null ; for ( Annotation annotation : annotations ) { if ( annotation instanceof DefaultValue ) { defaultValue = ( ( DefaultValue ) annotation ) . value ( ) ; } else { ParameterFactory factory = BINDINGS . get ( annotation . annotationType ( ) ) ; if ( factory != null ) { parameter = factory . build ( annotation , rawType , genericType ) ; } } } if ( parameter == null ) { throw new IllegalArgumentException ( "The member (Constructor or method) of " + member . getDeclaringClass ( ) . getName ( ) + "." + member . getName ( ) + " has a parameter without annotations indicating the injected data" ) ; } parameter . setDefaultValue ( defaultValue ) ; return parameter ; }
Creates a new action parameter instance from the given parameter . Action Parameter contain the metadata of a specific method or constructor parameter to identify the injected data .
2,132
public static String toClause ( List < String > packages ) { return Joiner . on ( ", " ) . skipNulls ( ) . join ( packages ) ; }
Computes the BND clause from the given set of packages .
2,133
public static boolean shouldBeExported ( String packageName ) { boolean service = packageName . endsWith ( ".service" ) ; service = service || packageName . contains ( ".service." ) || packageName . endsWith ( ".services" ) || packageName . contains ( ".services." ) ; boolean api = packageName . endsWith ( ".api" ) ; api = api || packageName . contains ( ".api." ) || packageName . endsWith ( ".apis" ) || packageName . contains ( ".apis." ) ; boolean model = packageName . endsWith ( ".model" ) ; model = model || packageName . contains ( ".model." ) || packageName . endsWith ( ".models" ) || packageName . contains ( ".models." ) ; boolean entity = packageName . endsWith ( ".entity" ) ; entity = entity || packageName . contains ( ".entity." ) || packageName . endsWith ( ".entities" ) || packageName . contains ( ".entities." ) ; return ! packageName . isEmpty ( ) && ! packageName . equals ( "." ) && ( service || api || model || entity ) ; }
Checks whether the given package must be exported . The decision is made from heuristics .
2,134
public void tearDown ( ) { if ( registration != null ) { registration . unregister ( ) ; registration = null ; } if ( factoryRegistration != null ) { factoryRegistration . unregister ( ) ; factoryRegistration = null ; } }
Unregisters the validator service .
2,135
public static void addLastModified ( Result result , long lastModified ) { result . with ( HeaderNames . LAST_MODIFIED , DateUtil . formatForHttpHeader ( lastModified ) ) ; }
Add the last modified header to the given result . This method handle the HTTP Date format .
2,136
public static boolean isNotModified ( Context context , long lastModified , String etag ) { final String browserEtag = context . header ( HeaderNames . IF_NONE_MATCH ) ; if ( browserEtag != null ) { return browserEtag . equals ( etag ) ; } final String ifModifiedSince = context . header ( HeaderNames . IF_MODIFIED_SINCE ) ; if ( ifModifiedSince != null && lastModified > 0 && ! ifModifiedSince . isEmpty ( ) ) { try { return ifModifiedSince . equals ( DateUtil . formatForHttpHeader ( lastModified ) ) ; } catch ( IllegalArgumentException ex ) { LoggerFactory . getLogger ( CacheUtils . class ) . error ( "Cannot build the date string for {}" , lastModified , ex ) ; return true ; } } return false ; }
Check whether the request can send a NOT_MODIFIED response .
2,137
public static String computeEtag ( long lastModification , ApplicationConfiguration configuration , Crypto crypto ) { boolean useEtag = configuration . getBooleanWithDefault ( HTTP_USE_ETAG , HTTP_USE_ETAG_DEFAULT ) ; if ( ! useEtag ) { return null ; } String raw = Long . toString ( lastModification ) ; return crypto . hexSHA1 ( raw ) ; }
Computes the ETAG value based on the last modification date passed as parameter .
2,138
public static void addCacheControlAndEtagToResult ( Result result , String etag , ApplicationConfiguration configuration ) { String maxAge = configuration . getWithDefault ( HTTP_CACHE_CONTROL_MAX_AGE , HTTP_CACHE_CONTROL_DEFAULT ) ; if ( "0" . equals ( maxAge ) ) { result . with ( HeaderNames . CACHE_CONTROL , "no-cache" ) ; } else { result . with ( HeaderNames . CACHE_CONTROL , "max-age=" + maxAge ) ; } boolean useEtag = configuration . getBooleanWithDefault ( HTTP_USE_ETAG , HTTP_USE_ETAG_DEFAULT ) ; if ( useEtag ) { result . with ( HeaderNames . ETAG , etag ) ; } }
Adds cache control and etag to the given result .
2,139
public static Result fromFile ( File file , Context context , ApplicationConfiguration configuration , Crypto crypto ) { long lastModified = file . lastModified ( ) ; String etag = computeEtag ( lastModified , configuration , crypto ) ; if ( isNotModified ( context , lastModified , etag ) ) { return new Result ( Status . NOT_MODIFIED ) ; } else { Result result = Results . ok ( file ) ; addLastModified ( result , lastModified ) ; addCacheControlAndEtagToResult ( result , etag , configuration ) ; return result ; } }
Computes the result to sent the given file . Cache headers are automatically set by this method .
2,140
public static String convertToHocon ( File props ) throws IOException { StringBuilder output = new StringBuilder ( ) ; List < String > lines = FileUtils . readLines ( props ) ; boolean readingValue = false ; for ( String line : lines ) { if ( isComment ( line ) ) { output . append ( "#" ) . append ( line . trim ( ) . substring ( 1 ) ) . append ( "\n" ) ; continue ; } if ( line . trim ( ) . isEmpty ( ) ) { if ( ! readingValue ) { output . append ( "\n" ) ; } continue ; } if ( ! readingValue ) { int position = getKeyValueSeparatorPosition ( line ) ; if ( position != 0 ) { String key = line . substring ( 0 , position ) . trim ( ) ; int vPosition = getValueStartPosition ( line , position ) ; String value ; if ( vPosition == - 1 ) { value = "" ; } else { value = fixValue ( line . substring ( vPosition ) . trim ( ) ) ; } output . append ( fixKey ( key ) ) . append ( "=" ) ; if ( value . endsWith ( "\\" ) ) { readingValue = true ; output . append ( "\"" ) ; output . append ( value . substring ( 0 , value . length ( ) - 1 ) ) ; } else { if ( vPosition == - 1 ) { output . append ( "\"\"" ) ; } else { output . append ( fixSingleLineValue ( line . substring ( vPosition ) ) . trim ( ) ) . append ( "\n" ) ; } readingValue = false ; } } else { throw new IllegalStateException ( "No key-value separator found in " + line ) ; } } else { String value = line . trim ( ) ; if ( value . endsWith ( "\\" ) ) { readingValue = true ; output . append ( fixValue ( value . substring ( 0 , value . length ( ) - 1 ) ) ) ; } else { output . append ( fixValue ( value ) ) . append ( "\"\n" ) ; readingValue = false ; } } } return output . toString ( ) ; }
Generates the hocon string resulting from the conversion of the given properties file .
2,141
public void activate ( ) { active = configuration . getBooleanWithDefault ( CORS_FILTER_ENABLED , false ) ; extraHeaders = configuration . getList ( CORS_FILTER_ALLOW_HEADERS ) ; allowedHosts = configuration . getList ( CORS_FILTER_ALLOW_ORIGIN ) ; allowCredentials = configuration . getBooleanWithDefault ( CORS_FILTER_ALLOW_CREDENTIALS , false ) ; if ( configuration . has ( "cors.max-age" ) ) { preflightMaxAge = configuration . getIntegerWithDefault ( CORS_FILTER_MAX_AGE , 3600 ) ; } }
Initialisation method . It checks whether the CORS support needs to be enabled or not .
2,142
public static String cleanupVersion ( String version ) { StringBuilder result = new StringBuilder ( ) ; Matcher m = FUZZY_VERSION . matcher ( version ) ; if ( m . matches ( ) ) { String major = m . group ( 1 ) ; String minor = m . group ( 3 ) ; String micro = m . group ( 5 ) ; String qualifier = m . group ( 7 ) ; if ( major != null ) { result . append ( major ) ; if ( minor != null ) { result . append ( "." ) ; result . append ( minor ) ; if ( micro != null ) { result . append ( "." ) ; result . append ( micro ) ; if ( qualifier != null ) { result . append ( "." ) ; cleanupModifier ( result , qualifier ) ; } } else if ( qualifier != null ) { result . append ( ".0." ) ; cleanupModifier ( result , qualifier ) ; } else { result . append ( ".0" ) ; } } else if ( qualifier != null ) { result . append ( ".0.0." ) ; cleanupModifier ( result , qualifier ) ; } else { result . append ( ".0.0" ) ; } } } else { result . append ( "0.0.0." ) ; cleanupModifier ( result , version ) ; } return result . toString ( ) ; }
Cleans up the version to be OSGi compliant .
2,143
@ Route ( method = HttpMethod . POST , uri = "/session/clear" ) public Result clear ( ) { session ( ) . clear ( ) ; return redirect ( router . getReverseRouteFor ( this , "index" ) ) ; }
Action called to clear the session
2,144
@ Route ( method = HttpMethod . POST , uri = "/session/populate" ) public Result populate ( ) { session ( ) . put ( "createdBy" , "wisdom" ) ; session ( ) . put ( "at" , DateFormat . getDateTimeInstance ( ) . format ( new Date ( ) ) ) ; return redirect ( router . getReverseRouteFor ( this , "index" ) ) ; }
Action called to populate the session
2,145
public Result call ( Route route , RequestContext context ) throws Exception { String originHeader = context . request ( ) . getHeader ( ORIGIN ) ; if ( originHeader != null ) { originHeader = originHeader . toLowerCase ( ) ; } if ( route . getHttpMethod ( ) != HttpMethod . OPTIONS ) { return retrieveAndReturnResult ( context , originHeader ) ; } if ( ! route . isUnbound ( ) ) { return context . proceed ( ) ; } Collection < Route > routes = router . getRoutes ( ) ; List < String > methods = new ArrayList < > ( 4 ) ; for ( Route r : routes ) { if ( r . matches ( r . getHttpMethod ( ) , route . getUrl ( ) ) ) { methods . add ( r . getHttpMethod ( ) . name ( ) ) ; } } if ( methods . isEmpty ( ) ) { return context . proceed ( ) ; } String requestMethod = context . request ( ) . getHeader ( ACCESS_CONTROL_REQUEST_METHOD ) ; if ( originHeader == null || requestMethod == null ) { return context . proceed ( ) ; } Result res = Results . ok ( ) ; if ( ! methods . contains ( requestMethod . toUpperCase ( ) ) ) { res = Results . unauthorized ( "No such method for this route" ) ; } Integer maxAge = getMaxAge ( ) ; if ( maxAge != null ) { res = res . with ( ACCESS_CONTROL_MAX_AGE , String . valueOf ( maxAge ) ) ; } String exposedHeaders = getExposedHeadersHeader ( ) ; String allowedHosts = getAllowedHostsHeader ( originHeader ) ; String allowedMethods = Joiner . on ( ", " ) . join ( methods ) ; Result result = res . with ( ACCESS_CONTROL_ALLOW_ORIGIN , allowedHosts ) . with ( ACCESS_CONTROL_ALLOW_METHODS , allowedMethods ) . with ( ACCESS_CONTROL_ALLOW_HEADERS , exposedHeaders ) ; if ( getAllowCredentials ( ) ) { result = result . with ( ACCESS_CONTROL_ALLOW_CREDENTIALS , "true" ) ; } return result ; }
Interception method . It checks whether or not the request requires CORS support or not . It also checks whether the requests is allowed or not .
2,146
public boolean fileCreated ( File file ) throws WatchingException { if ( WatcherUtils . isInDirectory ( file , internalSources ) ) { processDirectory ( internalSources , destinationForInternals ) ; } else if ( WatcherUtils . isInDirectory ( file , externalSources ) ) { processDirectory ( externalSources , destinationForExternals ) ; } return true ; }
A file is created - process it .
2,147
protected void processDirectory ( File input , File destination ) throws WatchingException { if ( ! input . isDirectory ( ) ) { return ; } if ( ! destination . isDirectory ( ) ) { destination . mkdirs ( ) ; } try { Collection < File > files = FileUtils . listFiles ( input , new String [ ] { "ts" } , true ) ; if ( files . isEmpty ( ) ) { return ; } List < String > arguments = typescript . createTypeScriptCompilerArgumentList ( input , destination , files ) ; getLog ( ) . info ( "Invoking the TypeScript compiler with " + arguments ) ; npm . registerOutputStream ( true ) ; int exit = npm . execute ( TYPE_SCRIPT_COMMAND , arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; getLog ( ) . debug ( "TypeScript Compiler execution exiting with status: " + exit ) ; } catch ( MojoExecutionException e ) { if ( ! Strings . isNullOrEmpty ( npm . getLastOutputStream ( ) ) ) { throw build ( npm . getLastOutputStream ( ) ) ; } else { throw new WatchingException ( ERROR_TITLE , "Error while compiling " + input . getAbsolutePath ( ) , input , e ) ; } } }
Process all typescripts file from the given directory . Output files are generated in the given destination .
2,148
public File getOutputFile ( File input , String ext ) { File source ; File destination ; if ( input . getAbsolutePath ( ) . startsWith ( internalSources . getAbsolutePath ( ) ) ) { source = internalSources ; destination = destinationForInternals ; } else if ( input . getAbsolutePath ( ) . startsWith ( externalSources . getAbsolutePath ( ) ) ) { source = externalSources ; destination = destinationForExternals ; } else { return null ; } String jsFileName = input . getName ( ) . substring ( 0 , input . getName ( ) . length ( ) - ".ts" . length ( ) ) + "." + ext ; String path = input . getParentFile ( ) . getAbsolutePath ( ) . substring ( source . getAbsolutePath ( ) . length ( ) ) ; return new File ( destination , path + "/" + jsFileName ) ; }
Gets the output file for the given input and the given extension .
2,149
public void visit ( ClassOrInterfaceDeclaration declaration , ControllerModel controller ) { controller . setName ( declaration . getName ( ) ) ; LOGGER . info ( "[controller]Visit " + controller . getName ( ) ) ; super . visit ( declaration , controller ) ; }
Visit the class declaration this is the visitor entry point!
2,150
public void start ( ) { module = new SimpleModule ( MonitorExtension . class . getName ( ) ) ; module . addSerializer ( MonitorExtension . class , new JsonSerializer < MonitorExtension > ( ) { public void serialize ( MonitorExtension monitorExtension , JsonGenerator jsonGenerator , SerializerProvider serializerProvider ) throws IOException { jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeStringField ( "label" , monitorExtension . label ( ) ) ; jsonGenerator . writeStringField ( "url" , monitorExtension . url ( ) ) ; jsonGenerator . writeStringField ( "category" , monitorExtension . category ( ) ) ; jsonGenerator . writeEndObject ( ) ; } } ) ; repository . register ( module ) ; }
When the monitor starts we initializes and registers a JSON module handling the serialization of the monitor extension .
2,151
public synchronized < V > ManagedScheduledFutureTask < V > schedule ( Callable < V > callable , long delay , TimeUnit unit ) { ScheduledTask < V > task = getNewScheduledTaskFor ( callable , false ) ; ScheduledFuture < V > future = ( ( ScheduledExecutorService ) executor ) . schedule ( task . callable , delay , unit ) ; task . submittedScheduledTask ( future ) ; return task ; }
Creates and executes a ScheduledFuture that becomes enabled after the given delay .
2,152
private CompositeExecutionContext addAll ( List < ExecutionContext > contexts ) { this . elements = new ImmutableList . Builder ( ) . addAll ( contexts ) . build ( ) ; return this ; }
Sets the composing context .
2,153
public static List < BundleModel > bundles ( BundleContext context ) { List < BundleModel > bundles = new ArrayList < > ( ) ; for ( Bundle bundle : context . getBundles ( ) ) { bundles . add ( new BundleModel ( bundle ) ) ; } return bundles ; }
Creates the list of bundle models based on the bundle currently deployed .
2,154
private static void cleanup ( ContextFromVertx context ) { if ( context != null ) { context . cleanup ( ) ; } Context . CONTEXT . remove ( ) ; }
The request is now completed clean everything .
2,155
public String getHeader ( String headerName ) { List < String > headers = null ; for ( String h : headers ( ) . keySet ( ) ) { if ( headerName . equalsIgnoreCase ( h ) ) { headers = headers ( ) . get ( h ) ; break ; } } if ( headers == null || headers . isEmpty ( ) ) { return null ; } return headers . get ( 0 ) ; }
Retrieves a single header .
2,156
public static void bind ( Source source , RouteParameterHandler handler ) { if ( BINDINGS . containsKey ( source ) ) { LoggerFactory . getLogger ( Bindings . class ) . warn ( "Replacing a route parameter binding for {} by {}" , source . name ( ) , handler ) ; } BINDINGS . put ( source , handler ) ; }
Associates the given source to the given handler .
2,157
public static Object create ( ActionParameter argument , Context context , ParameterFactories engine ) { RouteParameterHandler handler = BINDINGS . get ( argument . getSource ( ) ) ; if ( handler != null ) { return handler . create ( argument , context , engine ) ; } else { LoggerFactory . getLogger ( Bindings . class ) . warn ( "Unsupported route parameter in method : {}" , argument . getSource ( ) . name ( ) ) ; return null ; } }
Creates the value to be injected .
2,158
public static InterestingLines extractInterestedLines ( String source , int line , int border , Logger logger ) { try { if ( source == null ) { return null ; } String [ ] lines = source . split ( "\n" ) ; int firstLine = Math . max ( 0 , line - border ) ; int lastLine = Math . min ( lines . length - 1 , line + border ) ; List < String > focusOn = new ArrayList < > ( ) ; focusOn . addAll ( Arrays . asList ( lines ) . subList ( firstLine , lastLine + 1 ) ) ; return new InterestingLines ( firstLine + 1 , focusOn . toArray ( new String [ focusOn . size ( ) ] ) , line - firstLine - 1 ) ; } catch ( Exception e ) { logger . error ( "Cannot extract the interesting lines" , e ) ; return null ; } }
Extracts interesting lines to be displayed to the user .
2,159
public boolean analyzeJar ( Analyzer analyzer ) throws Exception { loadInternalRangeFix ( ) ; loadExternalRangeFix ( ) ; if ( analyzer . getReferred ( ) == null ) { return false ; } for ( Map . Entry < Descriptors . PackageRef , Attrs > entry : analyzer . getReferred ( ) . entrySet ( ) ) { for ( Range range : ranges ) { if ( range . matches ( entry . getKey ( ) . getFQN ( ) ) ) { String value = range . getRange ( analyzer ) ; if ( value != null ) { reporter . warning ( "Updating import version of " + range . name + " to " + value ) ; entry . getValue ( ) . put ( "version" , value ) ; } } } } return false ; }
Analyzes the jar and update the version range .
2,160
public static Properties load ( URL url ) throws IOException { InputStream fis = null ; try { Properties props = new Properties ( ) ; fis = url . openStream ( ) ; props . load ( fis ) ; return props ; } finally { IOUtils . closeQuietly ( fis ) ; } }
Utility method to load a properties file pointed by the given url .
2,161
private String reloadConfiguration ( ) { String location = System . getProperty ( APPLICATION_CONFIGURATION ) ; if ( location == null ) { location = "conf/application.conf" ; } Config configuration = loadConfiguration ( location ) ; if ( configuration == null ) { throw new IllegalStateException ( "Cannot load the application configuration (" + location + ") - Wisdom cannot " + "work properly without such configuration" ) ; } setConfiguration ( configuration ) ; return location ; }
Reloads the configuration file .
2,162
public String path ( ) { try { return new URI ( request . uri ( ) ) . getRawPath ( ) ; } catch ( URISyntaxException e ) { return uri ( ) ; } }
The URI path without the query part .
2,163
public boolean accepts ( String mimeType ) { String contentType = request . headers ( ) . get ( HeaderNames . ACCEPT ) ; if ( contentType == null ) { contentType = MimeTypes . HTML ; } if ( contentType . contains ( mimeType ) ) { return true ; } MediaType input = MediaType . parse ( mimeType ) ; for ( MediaType type : mediaTypes ( ) ) { if ( input . is ( type ) ) { return true ; } } return false ; }
Check if this request accepts a given media type .
2,164
public Map < String , List < String > > headers ( ) { if ( headers != null ) { return headers ; } headers = new HashMap < > ( ) ; final MultiMap requestHeaders = request . headers ( ) ; Set < String > names = requestHeaders . names ( ) ; for ( String name : names ) { headers . put ( name , requestHeaders . getAll ( name ) ) ; } return headers ; }
Retrieves all headers .
2,165
public Map < String , List < String > > parameters ( ) { Map < String , List < String > > result = new HashMap < > ( ) ; for ( String key : request . params ( ) . names ( ) ) { result . put ( key , request . params ( ) . getAll ( key ) ) ; } return result ; }
Gets all the parameters from the request .
2,166
public String getRawBodyAsString ( ) { if ( raw == null ) { return null ; } return raw . toString ( Charsets . UTF_8 . displayName ( ) ) ; }
Gets the raw body .
2,167
public boolean ready ( ) { for ( VertxFileUpload file : files ) { if ( file . getErrorIfAny ( ) != null ) { return false ; } } String contentType = request . headers ( ) . get ( HeaderNames . CONTENT_TYPE ) ; if ( contentType != null ) { contentType = HttpUtils . getContentTypeFromContentTypeAndCharacterSetting ( contentType ) ; if ( ( HttpUtils . isPostOrPut ( request ) ) && ( contentType . equalsIgnoreCase ( MimeTypes . FORM ) || contentType . equalsIgnoreCase ( MimeTypes . MULTIPART ) ) ) { formData = new HashMap < > ( ) ; for ( String key : request . formAttributes ( ) . names ( ) ) { formData . put ( key , request . formAttributes ( ) . getAll ( key ) ) ; } return true ; } } formData = new HashMap < > ( ) ; return true ; }
Callbacks invokes when the request has been read completely .
2,168
public static File getArtifactFileFromProjectDependencies ( AbstractWisdomMojo mojo , String artifactId , String type ) { Preconditions . checkNotNull ( mojo ) ; Preconditions . checkNotNull ( artifactId ) ; Preconditions . checkNotNull ( type ) ; for ( Artifact artifact : mojo . project . getArtifacts ( ) ) { if ( artifact . getArtifactId ( ) . equals ( artifactId ) && artifact . getType ( ) . equals ( type ) ) { return artifact . getFile ( ) ; } } return null ; }
Gets the file of the dependency with the given artifact id from the project dependencies .
2,169
public static File getArtifactFile ( AbstractWisdomMojo mojo , String artifactId , String type ) { File file = getArtifactFileFromProjectDependencies ( mojo , artifactId , type ) ; if ( file == null ) { file = getArtifactFileFromPluginDependencies ( mojo , artifactId , type ) ; } return file ; }
Gets the file of the dependency with the given artifact id from the project dependencies and if not found from the plugin dependencies . This method also check the extension .
2,170
public static boolean expand ( AbstractWisdomMojo mojo , File destination , String profileOrGAV ) throws MojoExecutionException { if ( destination . exists ( ) && isWisdomAlreadyInstalled ( destination ) ) { return false ; } File archive = getArchive ( mojo , profileOrGAV ) ; if ( archive == null || ! archive . exists ( ) ) { throw new MojoExecutionException ( "Cannot retrieve the Wisdom-Runtime file" ) ; } unzip ( mojo , archive , destination ) ; ensure ( destination ) ; return true ; }
Downloads and expands the Wisdom distribution .
2,171
public String getUserName ( Context context ) { if ( ! enabled ) { return "admin" ; } String user = context . session ( ) . get ( "wisdom.monitor.username" ) ; if ( user != null && user . equals ( username ) ) { return user ; } return null ; }
Retrieves the username from the HTTP context . It reads the wisdom . monitor . username in the session and checks it is equal to the username set in the application configuration .
2,172
public void handle ( final ServerWebSocket socket ) { LOGGER . info ( "New web socket connection {}, {}" , socket , socket . uri ( ) ) ; if ( ! configuration . accept ( socket . uri ( ) ) ) { LOGGER . warn ( "Web Socket connection denied on {} by {}" , socket . uri ( ) , configuration . name ( ) ) ; return ; } final Socket sock = new Socket ( socket ) ; accessor . getDispatcher ( ) . addSocket ( socket . path ( ) , sock ) ; socket . closeHandler ( event -> { LOGGER . info ( "Web Socket closed {}, {}" , socket , socket . uri ( ) ) ; accessor . getDispatcher ( ) . removeSocket ( socket . path ( ) , sock ) ; } ) ; socket . handler ( event -> accessor . getDispatcher ( ) . received ( socket . path ( ) , event . getBytes ( ) , sock ) ) ; }
Handles a web socket connection .
2,173
@ Route ( method = HttpMethod . GET , uri = "/{id}" ) public Result toggleBundle ( @ Parameter ( "id" ) long id ) { Bundle bundle = context . getBundle ( id ) ; if ( bundle == null ) { return notFound ( "Bundle " + id + " not found" ) ; } else { if ( ! isFragment ( bundle ) ) { if ( bundle . getState ( ) == Bundle . ACTIVE ) { try { bundle . stop ( ) ; } catch ( BundleException e ) { logger ( ) . error ( "Cannot stop bundle {}" , bundle . getSymbolicName ( ) , e ) ; return badRequest ( e ) ; } } else if ( bundle . getState ( ) == Bundle . INSTALLED || bundle . getState ( ) == Bundle . RESOLVED ) { try { bundle . start ( ) ; } catch ( BundleException e ) { logger ( ) . error ( "Cannot start bundle {}" , bundle . getSymbolicName ( ) , e ) ; return badRequest ( e ) ; } } } else { if ( bundle . getState ( ) == Bundle . RESOLVED ) { try { bundle . stop ( ) ; } catch ( BundleException e ) { logger ( ) . error ( "Cannot stop bundle {}" , bundle . getSymbolicName ( ) , e ) ; return badRequest ( e ) ; } } } } return ok ( ) ; }
Toggles the states of the bundle . If the bundle is active the bundle is stopped . If the bundle is resolved or installed the bundle is started .
2,174
@ Route ( method = HttpMethod . POST , uri = "/{id}" ) public Result updateBundle ( @ Parameter ( "id" ) long id ) { final Bundle bundle = context . getBundle ( id ) ; if ( bundle == null ) { return notFound ( "Bundle " + id + " not found" ) ; } else { return async ( new Callable < Result > ( ) { public Result call ( ) throws Exception { try { logger ( ) . info ( "Updating bundle {} from {}" , bundle . getSymbolicName ( ) , bundle . getLocation ( ) ) ; bundle . update ( ) ; return ok ( ) ; } catch ( BundleException e ) { logger ( ) . error ( "Cannot update bundle {}" , bundle . getSymbolicName ( ) , e ) ; return badRequest ( e ) ; } } } ) ; } }
Updates the given bundle . The bundle is updated from the installation url .
2,175
@ Route ( method = HttpMethod . POST , uri = "" ) public Result installBundle ( @ FormParameter ( "bundle" ) final FileItem bundle , @ FormParameter ( "start" ) @ DefaultValue ( "false" ) final boolean startIfNeeded ) { if ( bundle != null ) { return async ( new Callable < Result > ( ) { public Result call ( ) throws Exception { Bundle b ; try { b = context . installBundle ( "file/temp/" + bundle . name ( ) , bundle . stream ( ) ) ; logger ( ) . info ( "Bundle {} installed" , b . getSymbolicName ( ) ) ; } catch ( BundleException e ) { flash ( "error" , "Cannot install bundle '" + bundle . name ( ) + "' : " + e . getMessage ( ) ) ; return bundle ( ) ; } if ( startIfNeeded && ! isFragment ( b ) ) { try { b . start ( ) ; flash ( "success" , "Bundle '" + b . getSymbolicName ( ) + "' installed and started" ) ; return bundle ( ) ; } catch ( BundleException e ) { flash ( "error" , "Bundle '" + b . getSymbolicName ( ) + "' installed but " + "failed to start: " + e . getMessage ( ) ) ; return bundle ( ) ; } } else { flash ( "success" , "Bundle '" + b . getSymbolicName ( ) + "' installed." ) ; return bundle ( ) ; } } } ) ; } else { logger ( ) . error ( "No bundle to install" ) ; flash ( "error" , "Unable to install the bundle - no uploaded file" ) ; return bundle ( ) ; } }
Installs a new bundle .
2,176
@ Route ( method = HttpMethod . DELETE , uri = "/{id}" ) public Result uninstallBundle ( @ Parameter ( "id" ) long id ) { final Bundle bundle = context . getBundle ( id ) ; if ( bundle == null ) { return notFound ( "Bundle " + id + " not found" ) ; } else { return async ( new Callable < Result > ( ) { public Result call ( ) throws Exception { try { logger ( ) . info ( "Uninstalling bundle {}" , bundle . getSymbolicName ( ) ) ; bundle . uninstall ( ) ; return ok ( ) ; } catch ( BundleException e ) { logger ( ) . error ( "Cannot uninstall bundle {}" , bundle . getSymbolicName ( ) , e ) ; return badRequest ( e ) ; } } } ) ; } }
Uninstalls the given bundle .
2,177
public static boolean isFragment ( Bundle bundle ) { Dictionary < String , String > headers = bundle . getHeaders ( ) ; return headers . get ( Constants . FRAGMENT_HOST ) != null ; }
Checks whether or not the given bundle is a fragment
2,178
public File findExecutable ( String binary ) throws IOException , ParseException { File npmDirectory = getNPMDirectory ( ) ; File packageFile = new File ( npmDirectory , PACKAGE_JSON ) ; if ( ! packageFile . isFile ( ) ) { throw new IllegalStateException ( "Invalid NPM " + npmName + " - " + packageFile . getAbsolutePath ( ) + " does not" + " exist" ) ; } FileReader reader = null ; try { reader = new FileReader ( packageFile ) ; JSONObject json = ( JSONObject ) JSONValue . parseWithException ( reader ) ; JSONObject bin = ( JSONObject ) json . get ( "bin" ) ; if ( bin == null ) { log . error ( "No `bin` object in " + packageFile . getAbsolutePath ( ) ) ; return null ; } else { String exec = ( String ) bin . get ( binary ) ; if ( exec == null ) { log . error ( "No `" + binary + "` object in the `bin` object from " + packageFile . getAbsolutePath ( ) ) ; return null ; } File file = new File ( npmDirectory , exec ) ; if ( ! file . isFile ( ) ) { log . error ( "To execute " + npmName + ", an entry was found for " + binary + " in 'package.json', " + "but the specified file does not exist - " + file . getAbsolutePath ( ) ) ; return null ; } return file ; } } finally { IOUtils . closeQuietly ( reader ) ; } }
Tries to find the main JS file . This search is based on the package . json file and it s bin entry . If there is an entry in the bin object matching binary it uses this javascript file . If the search failed null is returned
2,179
public static String getVersionFromNPM ( File npmDirectory , Log log ) { File packageFile = new File ( npmDirectory , PACKAGE_JSON ) ; if ( ! packageFile . isFile ( ) ) { return "0.0.0" ; } FileReader reader = null ; try { reader = new FileReader ( packageFile ) ; JSONObject json = ( JSONObject ) JSONValue . parseWithException ( reader ) ; return ( String ) json . get ( "version" ) ; } catch ( IOException | ParseException e ) { log . error ( "Cannot extract version from " + packageFile . getAbsolutePath ( ) , e ) ; } finally { IOUtils . closeQuietly ( reader ) ; } return null ; }
Utility method to extract the version from a NPM by reading its package . json file .
2,180
public static void configureRegistry ( NodeManager node , Log log , String npmRegistryUrl ) { try { node . factory ( ) . getNpmRunner ( node . proxy ( ) ) . execute ( "config set registry " + npmRegistryUrl ) ; } catch ( TaskRunnerException e ) { log . error ( "Error during the configuration of NPM registry with the url " + npmRegistryUrl + " - check log" , e ) ; } }
Configures the NPM registry location .
2,181
public int compareTo ( ControllerRouteModel rElem ) { if ( rElem == null ) { throw new NullPointerException ( "Cannot compare to null" ) ; } if ( rElem . equals ( this ) ) { return 0 ; } int compare = getPath ( ) . compareTo ( rElem . getPath ( ) ) ; if ( compare == 0 ) { compare = getHttpMethod ( ) . compareTo ( rElem . getHttpMethod ( ) ) ; if ( compare == 0 ) { compare = getMethodName ( ) . compareTo ( rElem . getMethodName ( ) ) ; } } return compare ; }
A bit dummy compareTo implementation use by the tree Map .
2,182
public void configure ( ) { bind ( Controller . class ) . to ( new AnnotationVisitorFactory ( ) { public AnnotationVisitor newAnnotationVisitor ( BindingContext context ) { return new WisdomControllerVisitor ( context . getWorkbench ( ) , context . getReporter ( ) ) ; } } ) ; bind ( Service . class ) . to ( new AnnotationVisitorFactory ( ) { public AnnotationVisitor newAnnotationVisitor ( BindingContext context ) { return new WisdomServiceVisitor ( context . getWorkbench ( ) , context . getReporter ( ) ) ; } } ) ; bind ( View . class ) . when ( on ( ElementType . FIELD ) ) . to ( new AnnotationVisitorFactory ( ) { public AnnotationVisitor newAnnotationVisitor ( BindingContext context ) { return new WisdomViewVisitor ( context . getWorkbench ( ) , context . getReporter ( ) , context . getFieldNode ( ) ) ; } } ) ; bind ( Model . class ) . when ( on ( ElementType . FIELD ) ) . to ( new AnnotationVisitorFactory ( ) { public AnnotationVisitor newAnnotationVisitor ( BindingContext context ) { return new WisdomModelVisitor ( context . getWorkbench ( ) , context . getReporter ( ) , context . getFieldNode ( ) ) ; } } ) ; }
Adds the Wisdom annotation to the iPOJO manipulator .
2,183
private SecretKey generateAESKey ( String privateKey , String salt ) { try { byte [ ] raw = decodeHex ( salt ) ; KeySpec spec = new PBEKeySpec ( privateKey . toCharArray ( ) , raw , iterationCount , keySize ) ; SecretKeyFactory factory = SecretKeyFactory . getInstance ( PBKDF_2_WITH_HMAC_SHA_1 ) ; return new SecretKeySpec ( factory . generateSecret ( spec ) . getEncoded ( ) , AES_ECB_ALGORITHM ) ; } catch ( NoSuchAlgorithmException | InvalidKeySpecException e ) { throw new IllegalStateException ( e ) ; } }
Generate the AES key from the salt and the private key .
2,184
public String sign ( String message , byte [ ] key ) { Preconditions . checkNotNull ( message ) ; Preconditions . checkNotNull ( key ) ; try { SecretKeySpec signingKey = new SecretKeySpec ( key , HMAC_SHA_1 ) ; Mac mac = Mac . getInstance ( HMAC_SHA_1 ) ; mac . init ( signingKey ) ; byte [ ] rawHmac = mac . doFinal ( message . getBytes ( Charsets . UTF_8 ) ) ; return hexToString ( rawHmac ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } }
Sign a message with a key .
2,185
public String hash ( String input , Hash hashType ) { Preconditions . checkNotNull ( input ) ; Preconditions . checkNotNull ( hashType ) ; try { MessageDigest m = MessageDigest . getInstance ( hashType . toString ( ) ) ; byte [ ] out = m . digest ( input . getBytes ( Charsets . UTF_8 ) ) ; return encodeBase64 ( out ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( e ) ; } }
Create a hash using specific hashing algorithm .
2,186
public String encodeBase64 ( byte [ ] value ) { return new String ( Base64 . encodeBase64 ( value ) , Charsets . UTF_8 ) ; }
Encode binary data to base64 .
2,187
public String hexMD5 ( String value ) { return String . valueOf ( Hex . encodeHex ( md5 ( value ) ) ) ; }
Build an hexadecimal MD5 hash for a String .
2,188
public String hexSHA1 ( String value ) { return String . valueOf ( Hex . encodeHex ( sha1 ( value ) ) ) ; }
Build an hexadecimal SHA1 hash for a String .
2,189
public boolean compareSignedTokens ( String tokenA , String tokenB ) { String a = extractSignedToken ( tokenA ) ; String b = extractSignedToken ( tokenB ) ; return a != null && b != null && constantTimeEquals ( a , b ) ; }
Compares two signed tokens .
2,190
public byte [ ] md5 ( String toHash ) { try { MessageDigest messageDigest = MessageDigest . getInstance ( Hash . MD5 . toString ( ) ) ; messageDigest . reset ( ) ; messageDigest . update ( toHash . getBytes ( UTF_8 ) ) ; return messageDigest . digest ( ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } }
Computes the MD5 hash of the given String .
2,191
public Runnable asRunnable ( ) { return new Runnable ( ) { public void run ( ) { try { callable . call ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } ; }
Wraps the enhanced callable as a runnable .
2,192
public static boolean safeEquals ( String a , String b ) { if ( a . length ( ) != b . length ( ) ) { return false ; } else { char equal = 0 ; for ( int i = 0 ; i < a . length ( ) ; i ++ ) { equal |= a . charAt ( i ) ^ b . charAt ( i ) ; } return equal == 0 ; } }
Constant time for same length String comparison to prevent timing attacks .
2,193
public static Server from ( ServiceAccessor accessor , Vertx vertx , String name , Configuration configuration ) { return new Server ( accessor , vertx , name , configuration . getIntegerOrDie ( "port" ) , configuration . getBooleanWithDefault ( "ssl" , false ) , configuration . getBooleanWithDefault ( "authentication" , false ) , configuration . get ( "host" ) , configuration . getList ( "allow" ) , configuration . getList ( "deny" ) , configuration . get ( "onDenied" ) ) ; }
Creates a new server from the given configuration object .
2,194
public boolean accept ( String path ) { if ( allow . isEmpty ( ) && deny . isEmpty ( ) ) { return true ; } for ( Pattern p : deny ) { if ( p . matcher ( path ) . matches ( ) ) { return false ; } } for ( Pattern p : allow ) { if ( p . matcher ( path ) . matches ( ) ) { return true ; } } return ! deny . isEmpty ( ) ; }
Checks whether the given path is accepted or rejected by the current server .
2,195
public static Element declareInstance ( ComponentWorkbench workbench ) { Element instance = new Element ( "instance" , "" ) ; instance . addAttribute ( new Attribute ( COMPONENT , workbench . getType ( ) . getClassName ( ) ) ) ; return instance ; }
Declares an instance .
2,196
public static Element getProvidesElement ( String specifications ) { Element provides = new Element ( "provides" , "" ) ; if ( specifications == null ) { return provides ; } else { Attribute attribute = new Attribute ( "specifications" , specifications ) ; provides . addAttribute ( attribute ) ; return provides ; } }
Gets the provides element .
2,197
public static JsonNode from ( InstanceDescription description , Json json ) { ObjectNode node = json . newObject ( ) ; node . put ( "classname" , description . getComponentDescription ( ) . getName ( ) ) . put ( "invalid" , description . getState ( ) == ComponentInstance . INVALID ) . put ( "reason" , extractInvalidityReason ( description ) ) ; return node ; }
Creates the Json representation for an invalid controller .
2,198
private static String extractTemplateName ( String filter ) { Matcher matcher = TEMPLATE_FILTER_PATTERN . matcher ( filter ) ; if ( matcher . matches ( ) ) { return matcher . group ( 1 ) ; } else { return "Unknown template" ; } }
Extracts the template name from the given LDAP filter . The LDAP filter is structure as established in the WisdomViewVisitor .
2,199
private static String extractModelName ( String filter ) { Matcher matcher = MODEL_FILTER_PATTERN . matcher ( filter ) ; if ( matcher . matches ( ) ) { return matcher . group ( 1 ) ; } else { return "Unknown model" ; } }
Extracts the model name from the given LDAP filter . The LDAP filter is structure as established in the WisdomModelVisitor .