idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
2,200
public void visitEnd ( ) { if ( name == null || name . length ( ) == 0 ) { reporter . error ( "The 'name' attribute of @Model from " + workbench . getType ( ) . getClassName ( ) + " must be " + "set" ) ; return ; } if ( ! Type . getDescriptor ( Crud . class ) . equals ( node . desc ) ) { reporter . warn ( "The type of the field " + field + " from " + workbench . getType ( ) . getClassName ( ) + " should" + " be " + Crud . class . getName ( ) + " because the field is annotated with @Model" ) ; } Element requires = new Element ( "requires" , "" ) ; requires . addAttribute ( new Attribute ( "field" , field ) ) ; requires . addAttribute ( new Attribute ( "filter" , getFilter ( name ) ) ) ; workbench . getElements ( ) . put ( requires , null ) ; }
Generates the element - attribute structure to be added .
2,201
< A > A getConfigurationForInterceptor ( Interceptor < A > interceptor ) { return ( A ) interceptors . get ( interceptor ) ; }
Retrieves the configuration annotation for the given interceptor .
2,202
public Result proceed ( ) throws Exception { if ( iterator == null ) { iterator = chain . listIterator ( ) ; } if ( ! iterator . hasNext ( ) ) { throw new IllegalStateException ( "Reached the end of the chain without result." ) ; } Filter filter = iterator . next ( ) ; return filter . call ( route , this ) ; }
Calls the next interceptors .
2,203
private Route _build ( ) { Preconditions . checkNotNull ( controller ) ; Preconditions . checkNotNull ( httpMethod ) ; Preconditions . checkNotNull ( uri ) ; Preconditions . checkNotNull ( httpMethod ) ; return new Route ( httpMethod , uri , controller , controllerMethod ) ; }
Internal method building the route .
2,204
private Method verifyThatControllerAndMethodExists ( Class < ? > controller , String controllerMethod ) throws NoSuchMethodException { Method methodFromQueryingClass = null ; for ( Method method : controller . getMethods ( ) ) { if ( method . getName ( ) . equals ( controllerMethod ) ) { if ( methodFromQueryingClass == null ) { methodFromQueryingClass = method ; } else { throw new NoSuchMethodException ( ) ; } } } if ( methodFromQueryingClass == null ) { throw new NoSuchMethodException ( "The method " + controllerMethod + " does not exist in " + controller . getName ( ) ) ; } if ( methodFromQueryingClass . getReturnType ( ) . isAssignableFrom ( Result . class ) ) { return methodFromQueryingClass ; } else { throw new NoSuchMethodException ( "The method " + controllerMethod + " is declared in " + controller . getName ( ) + " but does not return a " + Result . class . getName ( ) + " object." ) ; } }
Checks that the action method really exists .
2,205
public boolean accept ( File file ) { if ( ! WatcherUtils . isInDirectory ( file , javaSourceDir ) || ! WatcherUtils . hasExtension ( file , "java" ) ) { return false ; } if ( ! file . isFile ( ) ) { return true ; } try { final CompilationUnit parse = JavaParser . parse ( file ) ; final Boolean accept = parse . accept ( CLASS_VISITOR , null ) ; return accept != null && accept ; } catch ( Exception e ) { getLog ( ) . error ( "Cannot parse " + file . getAbsolutePath ( ) , e ) ; return false ; } }
Check if we can create a model from the given source .
2,206
public static ObjectNode from ( Route route , Json json ) { return json . newObject ( ) . put ( "url" , route . getUrl ( ) ) . put ( "controller" , route . getControllerClass ( ) . getName ( ) ) . put ( "method" , route . getControllerMethod ( ) . getName ( ) ) . put ( "http_method" , route . getHttpMethod ( ) . toString ( ) ) ; }
Creates the JSON representation of the given route .
2,207
public String toJsonP ( final String callback , final Object data ) { synchronized ( lock ) { try { return callback + "(" + stringify ( ( JsonNode ) mapper . valueToTree ( data ) ) + ");" ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }
Gets the JSONP response for the given callback and value .
2,208
public String stringify ( JsonNode json ) { try { return mapper ( ) . writerWithDefaultPrettyPrinter ( ) . writeValueAsString ( json ) ; } catch ( JsonProcessingException e ) { throw new RuntimeException ( "Cannot stringify the input json node" , e ) ; } }
Converts a JsonNode to its string representation . This implementation use a pretty printer .
2,209
public JsonNode parse ( String src ) { synchronized ( lock ) { try { return mapper . readValue ( src , JsonNode . class ) ; } catch ( Exception t ) { throw new RuntimeException ( t ) ; } } }
Parses a String representing a json and return it as a JsonNode .
2,210
private void setMappers ( ObjectMapper mapper , XmlMapper xml ) { synchronized ( lock ) { this . mapper = mapper ; this . xml = xml ; if ( mapper != null && xml != null ) { applyMapperConfiguration ( mapper , xml ) ; } } }
Sets the object mapper .
2,211
public void register ( Module module ) { if ( module == null ) { return ; } LOGGER . info ( "Adding JSON module {}" , module . getModuleName ( ) ) ; synchronized ( lock ) { modules . add ( module ) ; rebuildMappers ( ) ; } }
Registers a new Jackson Module .
2,212
public void unregister ( Module module ) { if ( module == null ) { return ; } LOGGER . info ( "Removing Jackson module {}" , module . getModuleName ( ) ) ; synchronized ( lock ) { if ( modules . remove ( module ) ) { rebuildMappers ( ) ; } } }
Un - registers a JSON Module .
2,213
public Document fromInputStream ( InputStream stream , Charset encoding ) throws IOException { try { DocumentBuilder builder = factory . newDocumentBuilder ( ) ; InputSource is = new InputSource ( stream ) ; if ( encoding == null ) { is . setEncoding ( Charsets . UTF_8 . name ( ) ) ; } else { is . setEncoding ( encoding . name ( ) ) ; } return builder . parse ( is ) ; } catch ( ParserConfigurationException | SAXException e ) { throw new IOException ( "Cannot parse the given XML document" , e ) ; } }
Builds a new XML Document from the given input stream . The stream is not closed by this method and so you must close it .
2,214
public String stringify ( Document document ) { try { StringWriter sw = new StringWriter ( ) ; TransformerFactory tf = TransformerFactory . newInstance ( ) ; Transformer transformer = tf . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "no" ) ; transformer . setOutputProperty ( OutputKeys . METHOD , "xml" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , "UTF-8" ) ; transformer . transform ( new DOMSource ( document ) , new StreamResult ( sw ) ) ; return sw . toString ( ) ; } catch ( TransformerException e ) { throw new RuntimeException ( e ) ; } }
Retrieves the string form of the given XML document .
2,215
@ Bind ( optional = true , aggregate = true ) public synchronized void bindModule ( Module module ) { register ( module ) ; }
Binds a module .
2,216
public static synchronized boolean remove ( MavenSession session , Watcher watcher ) { return ! ( session == null || watcher == null ) && get ( session ) . remove ( watcher ) ; }
Un - registers a watcher .
2,217
static synchronized List < Watcher > get ( MavenSession session ) { List < Watcher > watchers = ( List < Watcher > ) session . getExecutionProperties ( ) . get ( WATCHERS_KEY ) ; if ( watchers == null ) { watchers = new ArrayList < > ( ) ; session . getExecutionProperties ( ) . put ( WATCHERS_KEY , watchers ) ; } return watchers ; }
Gets the list of watchers from the given MavenSession .
2,218
static synchronized List < Watcher > get ( Context context ) { List < Watcher > watchers ; if ( context . contains ( WATCHERS_KEY ) ) { try { watchers = ( List < Watcher > ) context . get ( WATCHERS_KEY ) ; } catch ( ContextException e ) { throw new IllegalStateException ( "Cannot extract the watcher from the context" , e ) ; } } else { watchers = new ArrayList < > ( ) ; context . put ( WATCHERS_KEY , watchers ) ; } return watchers ; }
Gets the list of watchers from the given Plexus context .
2,219
public void serialize ( ConstraintViolationImpl constraintViolation , JsonGenerator jsonGenerator , SerializerProvider serializerProvider ) throws IOException { jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeStringField ( "message" , constraintViolation . getMessage ( ) ) ; Object invalidValue = constraintViolation . getInvalidValue ( ) ; if ( invalidValue != null ) { jsonGenerator . writeStringField ( "invalid" , invalidValue . toString ( ) ) ; } if ( constraintViolation . getPropertyPath ( ) != null ) { jsonGenerator . writeStringField ( "path" , constraintViolation . getPropertyPath ( ) . toString ( ) ) ; } jsonGenerator . writeEndObject ( ) ; }
Writes the JSON form of the Constraint Violation .
2,220
public static synchronized void set ( Chameleon chameleon ) { if ( INSTANCE != null && chameleon != null ) { throw new IllegalStateException ( "A Chameleon instance is already stored" ) ; } INSTANCE = chameleon ; if ( chameleon == null ) { HOST_NAME = null ; HTTP_PORT = - 1 ; HTTPS_PORT = - 1 ; } }
Stores a reference on a running chameleon .
2,221
private static void retrieveServerMetadata ( ) throws Exception { if ( get ( ) == null ) { throw new IllegalStateException ( "Cannot retrieve the server metadata - no reference to Chameleon stored " + "in the holder" ) ; } int factor = Integer . getInteger ( "time.factor" , 1 ) ; if ( factor != 1 ) { TimeUtils . TIME_FACTOR = factor ; } ServiceReference [ ] references = get ( ) . waitForStability ( ) . context ( ) . getAllServiceReferences ( WisdomEngine . class . getName ( ) , null ) ; if ( references == null || references . length == 0 ) { references = get ( ) . waitForStability ( ) . context ( ) . getAllServiceReferences ( WisdomEngine . class . getName ( ) , null ) ; } if ( references == null || references . length == 0 ) { throw new IllegalStateException ( "Cannot retrieve the Wisdom Engine service" ) ; } Object engine = get ( ) . context ( ) . getService ( references [ 0 ] ) ; HOST_NAME = ( String ) engine . getClass ( ) . getMethod ( "hostname" ) . invoke ( engine ) ; HTTP_PORT = ( int ) engine . getClass ( ) . getMethod ( "httpPort" ) . invoke ( engine ) ; HTTPS_PORT = ( int ) engine . getClass ( ) . getMethod ( "httpsPort" ) . invoke ( engine ) ; }
Methods call by the test framework to discover the server name and port .
2,222
public static boolean isLinux ( String os ) { if ( os == null ) { return false ; } String operating = os . toLowerCase ( ) ; return operating . contains ( "nix" ) || operating . contains ( "nux" ) || operating . contains ( "aix" ) ; }
Checks whether the given operating system name is Linux Unix or AIX .
2,223
public static boolean is64bits ( ) { String arch = System . getProperty ( "sun.arch.data.model" ) ; if ( Strings . isNullOrEmpty ( arch ) ) { arch = System . getProperty ( "os.arch" ) ; } return is64bits ( arch ) ; }
Checks if the CPU architecture of the current computer is 64 bits .
2,224
public String getReverseRouteFor ( Controller controller , String method ) { return getReverseRouteFor ( controller . getClass ( ) , method , null ) ; }
Gets the url of the route handled by the specified action method . The action does not takes parameters .
2,225
public String getReverseRouteFor ( Controller controller , String method , String var1 , Object val1 ) { return getReverseRouteFor ( controller , method , ImmutableMap . of ( var1 , val1 ) ) ; }
Gets the url of the route handled by the specified action method .
2,226
public boolean isNotMinified ( File file ) { return ! file . getName ( ) . endsWith ( "min.js" ) && ! file . getName ( ) . endsWith ( googleClosureMinifierSuffix + ".js" ) ; }
Checks whether or not the file is minified .
2,227
public File getMinifiedFile ( File file ) { File output = getOutputFile ( file ) ; return new File ( output . getParentFile ( ) . getAbsoluteFile ( ) , output . getName ( ) . replace ( ".js" , googleClosureMinifierSuffix + ".js" ) ) ; }
Computes the file object for the minified version of the given file . The given file must be a . js file .
2,228
private void createSourceMapFile ( File output , SourceMap sourceMap ) throws WatchingException { if ( googleClosureMap ) { PrintWriter mapWriter = null ; File mapFile = new File ( output . getPath ( ) + ".map" ) ; FileUtils . deleteQuietly ( mapFile ) ; try { mapWriter = new PrintWriter ( mapFile , Charset . defaultCharset ( ) . name ( ) ) ; sourceMap . appendTo ( mapWriter , output . getName ( ) ) ; FileUtils . write ( output , "\n//# sourceMappingURL=" + mapFile . getName ( ) , true ) ; } catch ( IOException e ) { throw new WatchingException ( "Cannot create source map file for JavaScript file '" + output . getAbsolutePath ( ) + "'" , e ) ; } finally { IOUtils . closeQuietly ( mapWriter ) ; } } }
Create a source map file corresponding to the given compiled js file .
2,229
private void listErrors ( final Result result ) { for ( JSError warning : result . warnings ) { getLog ( ) . warn ( warning . toString ( ) ) ; } for ( JSError error : result . errors ) { getLog ( ) . error ( error . toString ( ) ) ; } }
List the errors that google is providing from the compiler output .
2,230
public boolean fileCreated ( File file ) throws WatchingException { try { createApplicationBundle ( ) ; } catch ( Exception e ) { throw new WatchingException ( e . getMessage ( ) , file , e ) ; } return true ; }
On any change we just repackage the bundle .
2,231
public void execute ( ) throws MojoExecutionException { try { ensureNotExisting ( ) ; createDirectories ( ) ; if ( "blank" . equalsIgnoreCase ( skel ) ) { createApplicationConfiguration ( ) ; createBlankPomFile ( ) ; createPackageStructure ( ) ; copyDefaultErrorTemplates ( ) ; } else { createApplicationConfiguration ( ) ; createPomFile ( ) ; createPackageStructure ( ) ; createDefaultController ( ) ; createTests ( ) ; copyAssets ( ) ; createWelcomeTemplate ( ) ; copyDefaultErrorTemplates ( ) ; } printStartGuide ( ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Error during project generation" , e ) ; } }
Generates the project structure . If a directory with the artifactId \ name already exist nothing is generated as we don t want to overridde anything .
2,232
public static boolean isExcluded ( Artifact artifact ) { Set < String > excluded = EXCLUSIONS . get ( artifact . getGroupId ( ) ) ; return excluded != null && excluded . contains ( artifact . getArtifactId ( ) ) ; }
Checks whether the given artifact is on the excluded list .
2,233
public void stop ( AbstractWisdomMojo mojo ) throws MojoExecutionException { File script = new File ( mojo . getWisdomRootDirectory ( ) , "chameleon.sh" ) ; if ( ! script . isFile ( ) ) { throw new MojoExecutionException ( "The 'chameleon.sh' file does not exist in " + mojo . getWisdomRootDirectory ( ) . getAbsolutePath ( ) + " - cannot stop the Wisdom instance" ) ; } File pid = new File ( mojo . getWisdomRootDirectory ( ) , "RUNNING_PID" ) ; if ( ! pid . isFile ( ) ) { mojo . getLog ( ) . info ( "The RUNNING_PID file does not exist, are you sure Wisdom is running ?" ) ; return ; } CommandLine cmdLine = new CommandLine ( script ) ; cmdLine . addArgument ( "stop" ) ; try { mojo . getLog ( ) . info ( "Stopping Wisdom Server using '" + cmdLine . toString ( ) + "'." ) ; Runtime . getRuntime ( ) . exec ( cmdLine . toStrings ( ) , null , mojo . getWisdomRootDirectory ( ) ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Cannot stop Wisdom" , e ) ; } }
Stops a running instance of wisdom using chameleon stop .
2,234
public static boolean waitForFile ( File file ) { if ( file . isFile ( ) ) { return true ; } else { long timeout = System . currentTimeMillis ( ) + FILE_WAIT_TIMEOUT ; while ( System . currentTimeMillis ( ) <= timeout ) { sleepQuietly ( 10 ) ; if ( file . isFile ( ) ) { return true ; } } } return false ; }
Waits for a file to be created .
2,235
public String get ( final String key ) { return retrieve ( new Callable < String > ( ) { public String call ( ) throws Exception { return configuration . getString ( key ) ; } } , null ) ; }
Get a String property or null if it is not there ...
2,236
public String getWithDefault ( final String key , String defaultValue ) { return retrieve ( new Callable < String > ( ) { public String call ( ) throws Exception { return configuration . getString ( key ) ; } } , defaultValue ) ; }
Get a String property or a default value when property cannot be found in any configuration file .
2,237
public Integer getIntegerWithDefault ( final String key , Integer defaultValue ) { return retrieve ( new Callable < Integer > ( ) { public Integer call ( ) throws Exception { return configuration . getInt ( key ) ; } } , defaultValue ) ; }
Get a Integer property or a default value when property cannot be found in any configuration file .
2,238
public Double getDoubleWithDefault ( final String key , Double defaultValue ) { return retrieve ( new Callable < Double > ( ) { public Double call ( ) throws Exception { return configuration . getDouble ( key ) ; } } , defaultValue ) ; }
Get a Double property or a default value when property cannot be found in any configuration file .
2,239
public Boolean getBooleanWithDefault ( final String key , Boolean defaultValue ) { return retrieve ( new Callable < Boolean > ( ) { public Boolean call ( ) throws Exception { return configuration . getBoolean ( key ) ; } } , defaultValue ) ; }
Get a Boolean property or a default value when property cannot be found in any configuration file .
2,240
public Configuration getConfiguration ( String prefix ) { try { Config value = configuration . getConfig ( prefix ) ; return new ConfigurationImpl ( converters , value ) ; } catch ( ConfigException . Missing e ) { return null ; } }
Gets a configuration object with all the properties starting with the given prefix .
2,241
@ Route ( method = HttpMethod . GET , uri = "/async/hello/{name}" ) public Result heavyComputation ( @ Parameter ( "name" ) final String name ) { return async ( new Callable < Result > ( ) { public Result call ( ) throws Exception { System . out . println ( System . currentTimeMillis ( ) + " - Heavy computation executed from " + Thread . currentThread ( ) . getName ( ) ) ; Thread . sleep ( 10000 ) ; System . out . println ( System . currentTimeMillis ( ) + " - Heavy computation done " + Thread . currentThread ( ) . getName ( ) ) ; return ok ( "Hello " + name ) ; } } ) ; }
Waits ten second before sending the hello message .
2,242
protected HttpClient newHttpClient ( ) { return HttpClients . custom ( ) . setRedirectStrategy ( new DefaultRedirectStrategy ( ) { protected boolean isRedirectable ( String method ) { return followRedirect ( method ) ; } } ) . setDefaultCookieStore ( new BasicCookieStore ( ) { public synchronized List < Cookie > getCookies ( ) { return Collections . emptyList ( ) ; } } ) . build ( ) ; }
Allows you do override the HTTP Client used to execute the requests . By default it used a custom client without cookies .
2,243
private Result renderInternalError ( Context context , Route route , Throwable e ) { Throwable localException ; if ( internalerror == null ) { return internalServerError ( e ) ; } if ( e instanceof InvocationTargetException ) { localException = ( ( InvocationTargetException ) e ) . getTargetException ( ) ; } else { localException = e ; } String cause ; StackTraceElement [ ] stack ; if ( localException . getCause ( ) != null ) { cause = localException . getCause ( ) . getMessage ( ) ; stack = localException . getCause ( ) . getStackTrace ( ) ; } else { cause = localException . getMessage ( ) ; stack = localException . getStackTrace ( ) ; } String fileName = null ; int line = - 1 ; if ( stack != null && stack . length != 0 ) { fileName = stack [ 0 ] . getFileName ( ) ; line = stack [ 0 ] . getLineNumber ( ) ; } List < StackTraceElement > cleaned = StackTraceUtils . cleanup ( stack ) ; return internalServerError ( render ( internalerror , "route" , route , "context" , context , "exception" , localException , "message" , localException . getMessage ( ) , "cause" , cause , "file" , fileName , "line" , line , "stack" , cleaned ) ) ; }
Generates the error page .
2,244
public Result call ( Route route , RequestContext context ) throws Exception { if ( configuration . isDev ( ) && context . request ( ) . accepts ( MimeTypes . HTML ) && pipeline != null ) { File error = getFirstErrorFile ( ) ; if ( error != null ) { logger ( ) . debug ( "Error file detected, preparing rendering" ) ; try { return renderPipelineError ( error ) ; } catch ( IOException e ) { LOGGER . error ( "An exception occurred while generating the error page for {} {}" , route . getHttpMethod ( ) , route . getUrl ( ) , e ) ; return renderInternalError ( context . context ( ) , route , e ) ; } } } try { Result result = context . proceed ( ) ; if ( result . getStatusCode ( ) == NOT_FOUND && result . getRenderable ( ) instanceof NoHttpBody ) { if ( route . getHttpMethod ( ) == HttpMethod . HEAD ) { return switchToGet ( route , context ) ; } return renderNotFound ( route , result ) ; } return result ; } catch ( InvocationTargetException e ) { Throwable cause = e . getCause ( ) ; LOGGER . error ( "An exception occurred while processing request {} {}" , route . getHttpMethod ( ) , route . getUrl ( ) , cause ) ; if ( cause instanceof HttpException ) { LOGGER . error ( "A HTTP exception occurred while processing request {} {}" , route . getHttpMethod ( ) , route . getUrl ( ) , e ) ; return ( ( HttpException ) cause ) . toResult ( ) ; } for ( ExceptionMapper mapper : mappers ) { if ( mapper . getExceptionClass ( ) . equals ( cause . getClass ( ) ) ) { return mapper . toResult ( ( Exception ) cause ) ; } } return renderInternalError ( context . context ( ) , route , e ) ; } catch ( Exception e ) { LOGGER . error ( "An exception occurred while processing request {} {}" , route . getHttpMethod ( ) , route . getUrl ( ) , e ) ; Throwable cause = e . getCause ( ) ; for ( ExceptionMapper mapper : mappers ) { if ( mapper . getExceptionClass ( ) . equals ( cause . getClass ( ) ) ) { return mapper . toResult ( ( Exception ) cause ) ; } } return renderInternalError ( context . context ( ) , route , e ) ; } }
The interception method . When the request is unbound generate a 404 page . When the controller throws an exception generates a 500 page .
2,245
public Route accepts ( String ... types ) { Preconditions . checkNotNull ( types ) ; final ImmutableSet . Builder < MediaType > builder = new ImmutableSet . Builder < > ( ) ; builder . addAll ( this . acceptedMediaTypes ) ; for ( String s : types ) { builder . add ( MediaType . parse ( s ) ) ; } this . acceptedMediaTypes = builder . build ( ) ; return this ; }
Sets the set of media types accepted by the route .
2,246
public Route produces ( String ... types ) { Preconditions . checkNotNull ( types ) ; final ImmutableSet . Builder < MediaType > builder = new ImmutableSet . Builder < > ( ) ; builder . addAll ( this . producedMediaTypes ) ; for ( String s : types ) { final MediaType mt = MediaType . parse ( s ) ; if ( mt . hasWildcard ( ) ) { throw new RoutingException ( "A route cannot `produce` a mime type with a wildcard: " + mt ) ; } builder . add ( mt ) ; } this . producedMediaTypes = builder . build ( ) ; return this ; }
Sets the set of media types produced by the route .
2,247
public boolean isCompliantWithRequestAccept ( Request request ) { if ( producedMediaTypes == null || producedMediaTypes . isEmpty ( ) || request == null || request . getHeader ( HeaderNames . ACCEPT ) == null ) { return true ; } else { for ( MediaType mt : producedMediaTypes ) { if ( request . accepts ( mt . toString ( ) ) ) { return true ; } } return false ; } }
Checks whether the given request is compliant with the media type accepted by the current route .
2,248
@ Route ( method = HttpMethod . GET , uri = "" ) public Result index ( @ PathParameter ( "name" ) String name ) { if ( names . contains ( name ) ) { return ok ( render ( template , "source" , RAML_ASSET_DIR + name + RAML_EXT ) ) ; } return notFound ( ) ; }
Return the raml console api corresponding to the raml of given name .
2,249
public void start ( ) { for ( Asset asset : assets . assets ( ) ) { if ( asset . getPath ( ) . matches ( "^" + RAML_ASSET_DIR + "[A-Za-z0-9_-]+\\" + RAML_EXT + "$" ) ) { String name = asset . getPath ( ) . substring ( RAML_ASSET_DIR . length ( ) , asset . getPath ( ) . length ( ) - RAML_EXT . length ( ) ) ; if ( ! names . add ( name ) ) { continue ; } registrations . add ( context . registerService ( MonitorExtension . class , new RamlMonitorConsole ( name ) , null ) ) ; } } }
Looks for the raml file available in the assets and publish a RamlMonitorConsole for each of them .
2,250
public void stop ( ) { for ( ServiceRegistration registration : registrations ) { registration . unregister ( ) ; } registrations . clear ( ) ; names . clear ( ) ; }
Unregister all RamlMonitorConsole services created by this instance .
2,251
public BodyParser getBodyParserEngineForContentType ( String contentType ) { for ( BodyParser parser : parsers ) { if ( parser . getContentTypes ( ) . contains ( contentType ) ) { return parser ; } } LoggerFactory . getLogger ( this . getClass ( ) ) . info ( "Cannot find a body parser for " + contentType ) ; return null ; }
Gets the body parser that can be used to parse a body with the given content type .
2,252
public ContentSerializer getContentSerializerForContentType ( String contentType ) { for ( ContentSerializer renderer : serializers ) { if ( renderer . getContentType ( ) . equals ( contentType ) ) { return renderer ; } } LoggerFactory . getLogger ( this . getClass ( ) ) . info ( "Cannot find a content renderer handling " + contentType ) ; return null ; }
Gets the content serializer that can be used to serialize a result to the given content type . This method uses an exact match .
2,253
public ContentSerializer getBestSerializer ( Collection < MediaType > mediaTypes ) { if ( mediaTypes == null || mediaTypes . isEmpty ( ) ) { mediaTypes = ImmutableList . of ( MediaType . HTML_UTF_8 ) ; } for ( MediaType type : mediaTypes ) { for ( ContentSerializer ser : serializers ) { MediaType mt = MediaType . parse ( ser . getContentType ( ) ) ; if ( mt . is ( type . withoutParameters ( ) ) ) { return ser ; } } } return null ; }
Finds the best content serializer for the given accept headers .
2,254
public void execute ( ) throws MojoExecutionException { if ( skipCleanCSS ) { getLog ( ) . debug ( "Skipping CSS minification" ) ; removeFromWatching ( ) ; return ; } cleancss = NPM . npm ( this , CLEANCSS_NPM_NAME , cleanCssVersion ) ; getLog ( ) . info ( "Clean CSS version: " + cleanCssVersion ) ; if ( stylesheets == null ) { getLog ( ) . info ( "No 'stylesheets' processing configuration, minifying all '.css' files individually" ) ; for ( File file : getResources ( getExtensions ( ) ) ) { try { process ( file ) ; } catch ( WatchingException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } } } else { process ( stylesheets ) ; } }
Checks if the skipCleanCSS flag has been set if so we stop watching css files . If not we continue by setting our Clean CSS NPM object and calling the minify method for all css files found .
2,255
public boolean isNotMinified ( File file ) { return ! file . getName ( ) . endsWith ( "min.css" ) && ! file . getName ( ) . endsWith ( cssMinifierSuffix + ".css" ) ; }
Checks to see if the file is already minified .
2,256
public boolean fileCreated ( File file ) throws WatchingException { if ( stylesheets != null ) { try { process ( stylesheets ) ; } catch ( MojoExecutionException e ) { throw new WatchingException ( "Error while aggregating or minifying CSS resources" , file , e ) ; } } else { process ( file ) ; } return true ; }
Minifies the created files .
2,257
public boolean fileDeleted ( File file ) throws WatchingException { if ( isNotMinified ( file ) ) { File minified = getMinifiedFile ( file ) ; FileUtils . deleteQuietly ( minified ) ; File map = new File ( minified . getParentFile ( ) , minified . getName ( ) + ".map" ) ; FileUtils . deleteQuietly ( map ) ; } return true ; }
Cleans the output file if any .
2,258
public File getFilteredVersion ( File input ) { File out ; if ( ! input . getName ( ) . endsWith ( ".css" ) ) { out = getOutputFile ( input , "css" ) ; } else { out = getOutputFile ( input ) ; } if ( ! out . isFile ( ) ) { return null ; } return out ; }
Overrides the parent method to manage the case where the given file is not a . css . In that case it should strips the extension and find a . css file .
2,259
private void process ( File file ) throws WatchingException { getLog ( ) . info ( "Minifying CSS files from " + file . getName ( ) + " using Clean CSS" ) ; File filtered = getFilteredVersion ( file ) ; if ( filtered == null ) { filtered = file ; } File output = getMinifiedFile ( file ) ; if ( output . exists ( ) ) { FileUtils . deleteQuietly ( output ) ; } if ( ! output . getParentFile ( ) . isDirectory ( ) ) { getLog ( ) . debug ( "Creating output directory for " + output . getAbsolutePath ( ) + " : " + output . getParentFile ( ) . mkdirs ( ) ) ; } getLog ( ) . info ( "Minifying " + filtered . getAbsolutePath ( ) + " to " + output . getAbsolutePath ( ) ) ; try { List < String > arguments = new ArrayList < > ( ) ; arguments . add ( "--output" ) ; arguments . add ( output . getAbsolutePath ( ) ) ; arguments . add ( "--source-map" ) ; if ( cleanCssArguments != null ) { arguments . addAll ( Splitter . on ( ' ' ) . splitToList ( cleanCssArguments ) ) ; } arguments . add ( filtered . getAbsolutePath ( ) ) ; int exit = cleancss . execute ( "cleancss" , arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; getLog ( ) . debug ( "CSS minification execution exiting with " + exit + " status" ) ; } catch ( MojoExecutionException e ) { throw new WatchingException ( "Error during the minification of " + filtered . getName ( ) , e ) ; } }
Minifies the CSS file using Clean CSS .
2,260
protected File getMinifiedFile ( File input ) { File output = getOutputFile ( input ) ; String ext = FilenameUtils . getExtension ( output . getName ( ) ) ; return new File ( output . getParentFile ( ) . getAbsoluteFile ( ) , output . getName ( ) . replace ( "." + ext , cssMinifierSuffix + ".css" ) ) ; }
Creates out minified output file replacing the current extension with the minified one .
2,261
protected static String getArray ( List < String > paths ) { StringBuilder builder = new StringBuilder ( ) ; for ( String s : paths ) { if ( builder . length ( ) == 0 ) { builder . append ( s ) ; } else { builder . append ( "," ) . append ( s ) ; } } return builder . toString ( ) ; }
Compute a String form the given list of paths . The list uses comma as separator .
2,262
private void initView ( ) { setMinValue ( MIN_VALUE ) ; setMaxValue ( MAX_VALUE ) ; setValue ( DEFAULT_VALUE ) ; setBackgroundColor ( BACKGROUND_COLOR ) ; setSeparatorColor ( SEPARATOR_COLOR ) ; setTextColor ( TEXT_COLOR ) ; setTextSize ( TEXT_SIZE ) ; setWrapSelectorWheel ( false ) ; setFocusability ( false ) ; try { Field f = NumberPicker . class . getDeclaredField ( "mInputText" ) ; f . setAccessible ( true ) ; EditText inputText = ( EditText ) f . get ( this ) ; inputText . setFilters ( new InputFilter [ 0 ] ) ; } catch ( NoSuchFieldException | IllegalAccessException | IllegalArgumentException e ) { e . printStackTrace ( ) ; } }
Init number picker by disabling focusability of edit text embedded inside the number picker We also override the edit text filter private attribute by using reflection as the formatter is still buggy while attempting to display the default value This is still an open Google
2,263
public void setSeparatorColor ( int separatorColor ) { mSeparatorColor = separatorColor ; Field [ ] pickerFields = NumberPicker . class . getDeclaredFields ( ) ; for ( Field pf : pickerFields ) { if ( pf . getName ( ) . equals ( "mSelectionDivider" ) ) { pf . setAccessible ( true ) ; try { pf . set ( this , new ColorDrawable ( separatorColor ) ) ; } catch ( IllegalAccessException | IllegalArgumentException e ) { e . printStackTrace ( ) ; } break ; } } }
Uses reflection to access divider private attribute and override its color Use Color . Transparent if you wish to hide them
2,264
public Action rebootDroplet ( Integer dropletId ) throws DigitalOceanException , RequestUnsuccessfulException { validateDropletId ( dropletId ) ; Object [ ] params = { dropletId } ; return ( Action ) perform ( new ApiRequest ( ApiAction . REBOOT_DROPLET , new DropletAction ( ActionType . REBOOT ) , params ) ) . getData ( ) ; }
Droplet action methods
2,265
private String getSimpleHeaderValue ( String header , HttpResponse httpResponse ) { return getSimpleHeaderValue ( header , httpResponse , true ) ; }
Easy method for HTTP header values . defaults to first one .
2,266
private void checkBlankAndThrowError ( String str , String msg ) { if ( StringUtils . isBlank ( str ) ) { log . error ( msg ) ; throw new IllegalArgumentException ( msg ) ; } }
It checks for null whitespace and length
2,267
protected ArchiveOutputStream createArchiveOutputStream ( File archiveFile ) throws IOException { try { return CommonsStreamFactory . createArchiveOutputStream ( this , archiveFile ) ; } catch ( ArchiveException e ) { throw new IOException ( e ) ; } }
Returns a new ArchiveOutputStream for creating archives . Subclasses can override this to return their own custom implementation .
2,268
protected void assertExtractSource ( File archive ) throws FileNotFoundException , IllegalArgumentException { if ( archive . isDirectory ( ) ) { throw new IllegalArgumentException ( "Can not extract " + archive + ". Source is a directory." ) ; } else if ( ! archive . exists ( ) ) { throw new FileNotFoundException ( archive . getPath ( ) ) ; } else if ( ! archive . canRead ( ) ) { throw new IllegalArgumentException ( "Can not extract " + archive + ". Can not read from source." ) ; } }
Asserts that the given File object is a readable file that can be used to extract from .
2,269
protected File createNewArchiveFile ( String archive , String extension , File destination ) throws IOException { if ( ! archive . endsWith ( extension ) ) { archive += extension ; } File file = new File ( destination , archive ) ; file . createNewFile ( ) ; return file ; }
Creates a new File in the given destination . The resulting name will always be archive . fileExtension . If the archive name parameter already ends with the given file name extension it is not additionally appended .
2,270
public static AttributeAccessor < ? > create ( ArchiveEntry entry ) { if ( entry instanceof TarArchiveEntry ) { return new TarAttributeAccessor ( ( TarArchiveEntry ) entry ) ; } else if ( entry instanceof ZipArchiveEntry ) { return new ZipAttributeAccessor ( ( ZipArchiveEntry ) entry ) ; } else if ( entry instanceof CpioArchiveEntry ) { return new CpioAttributeAccessor ( ( CpioArchiveEntry ) entry ) ; } else if ( entry instanceof ArjArchiveEntry ) { return new ArjAttributeAccessor ( ( ArjArchiveEntry ) entry ) ; } else if ( entry instanceof ArArchiveEntry ) { return new ArAttributeAccessor ( ( ArArchiveEntry ) entry ) ; } return new FallbackAttributeAccessor ( entry ) ; }
Detects the type of the given ArchiveEntry and returns an appropriate AttributeAccessor for it .
2,271
public static Compressor createCompressor ( String compression ) throws IllegalArgumentException { if ( ! CompressionType . isValidCompressionType ( compression ) ) { throw new IllegalArgumentException ( "Unkonwn compression type " + compression ) ; } return createCompressor ( CompressionType . fromString ( compression ) ) ; }
Creates a compressor from the given compression type .
2,272
public static void copy ( InputStream source , File destination ) throws IOException { OutputStream output = null ; try { output = new FileOutputStream ( destination ) ; copy ( source , output ) ; } finally { closeQuietly ( output ) ; } }
Copies the content of an InputStream into a destination File .
2,273
public static File [ ] filesContainedIn ( File source ) { if ( source . isDirectory ( ) ) { return source . listFiles ( ) ; } else { return new File [ ] { source } ; } }
Given a source File return its direct descendants if the File is a directory . Otherwise return the File itself .
2,274
public static void map ( ArchiveEntry entry , File file ) throws IOException { create ( entry ) . map ( file ) ; }
Utility method to create a FileModeMapper for the given entry and use it to map the file mode onto the given file .
2,275
public CurrencyDateCalculatorBuilder < E > ccy1Calendar ( final HolidayCalendar < E > ccy1Calendar ) { if ( ccy1Calendar != null ) { this . ccy1Calendar = ccy1Calendar ; } return this ; }
The holiday calendar for ccy1 if null or not set then a default calendar will be used with NO holidays .
2,276
public CurrencyDateCalculatorBuilder < E > ccy2Calendar ( final HolidayCalendar < E > ccy2Calendar ) { if ( ccy2Calendar != null ) { this . ccy2Calendar = ccy2Calendar ; } return this ; }
The holiday calendar for ccy2 if null or not set then a default calendar will be used with NO holidays .
2,277
public CurrencyDateCalculatorBuilder < E > crossCcyCalendar ( final HolidayCalendar < E > crossCcyCalendar ) { if ( crossCcyCalendar != null ) { this . crossCcyCalendar = crossCcyCalendar ; } return this ; }
If brokenDate is not allowed we do require to check the WorkingWeek and Holiday for the crossCcy when validating the SpotDate or a Tenor date .
2,278
public CalendarDateCalculator getDateCalculator ( final String name , final String holidayHandlerType ) { final CalendarDateCalculator cal = new CalendarDateCalculator ( ) ; cal . setName ( name ) ; setHolidays ( name , cal ) ; if ( holidayHandlerType != null ) { cal . setHolidayHandler ( getHolidayHandler ( holidayHandlerType ) ) ; } return cal ; }
Create a new DateCalculator for a given name and type of handling .
2,279
private static void moveToIMMDay ( final Calendar cal ) { cal . set ( DAY_OF_MONTH , 1 ) ; final int dayOfWeek = cal . get ( Calendar . DAY_OF_WEEK ) ; if ( dayOfWeek < WEDNESDAY ) { cal . add ( DAY_OF_MONTH , WEDNESDAY - dayOfWeek ) ; } else if ( dayOfWeek > WEDNESDAY ) { cal . add ( DAY_OF_MONTH , WEDNESDAY + NUMBER_DAYS_IN_WEEK - dayOfWeek ) ; } cal . add ( DAY_OF_MONTH , NUMBER_DAYS_IN_WEEK * 2 ) ; }
Assumes that the month is correct get the day for the 3rd wednesday .
2,280
public static Calendar blastTime ( final Calendar cal ) { cal . set ( Calendar . HOUR_OF_DAY , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; return cal ; }
Removes set s all time fields to zero leaving only the date portion of the Calendar . The Calendar passe
2,281
public static Date createDate ( final String dateStr ) { if ( dateStr == null ) { return createCalendar ( null ) . getTime ( ) ; } final Calendar cal = getCal ( dateStr ) ; return cal != null ? cal . getTime ( ) : null ; }
Creates a Date object given a string representation of it
2,282
public static Calendar createCalendar ( final String dateStr ) { if ( dateStr == null ) { return blastTime ( Calendar . getInstance ( ) ) ; } return getCal ( dateStr ) ; }
get a new Calendar based on the string date .
2,283
public static Calendar getCal ( final Date date ) { if ( date == null ) { return null ; } final Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; return blastTime ( cal ) ; }
Get a Calendar object for a given Date representation .
2,284
public static Set < Date > toDateSet ( final Set < Calendar > calendars ) { return calendars . stream ( ) . map ( Calendar :: getTime ) . collect ( Collectors . toSet ( ) ) ; }
Converts a Set of Calendar objects to a Set of Date objects
2,285
public DateCalculator < E > setStartDate ( final E startDate ) { this . startDate = startDate ; setCurrentBusinessDate ( startDate ) ; return this ; }
Set both start date and current date
2,286
public DateCalculator < E > moveByTenor ( final Tenor tenor , final int spotLag ) { if ( tenor == null ) { throw new IllegalArgumentException ( "Tenor cannot be null" ) ; } TenorCode tenorCode = tenor . getCode ( ) ; if ( tenorCode != TenorCode . OVERNIGHT && tenorCode != TenorCode . TOM_NEXT ) { moveToSpotDate ( spotLag ) ; } int unit = tenor . getUnits ( ) ; if ( tenorCode == TenorCode . WEEK ) { tenorCode = TenorCode . DAY ; unit *= DAYS_IN_WEEK ; } if ( tenorCode == TenorCode . YEAR ) { tenorCode = TenorCode . MONTH ; unit *= MONTHS_IN_YEAR ; } return applyTenor ( tenorCode , unit ) ; }
move the current date by a given tenor this means that if a date is either a weekend or holiday it will be skipped acording to the holiday handler and not count towards the number of days to move .
2,287
public boolean isNonWorkingDay ( final E date ) { if ( date != null && ( holidayCalendar . getEarlyBoundary ( ) != null || holidayCalendar . getLateBoundary ( ) != null ) ) { checkBoundary ( date ) ; } return isWeekend ( date ) || holidayCalendar . isHoliday ( date ) ; }
is the given date a non working day?
2,288
public ExcelCell newCell ( String url , String label ) { return row . newCell ( ) . link ( url , label ) ; }
Add a hyperlink
2,289
public CurrencyAmount add ( final CurrencyAmount money ) { if ( ! money . getCurrency ( ) . equals ( currency ) ) { throw new IllegalArgumentException ( "You cannot add " + money . getCurrency ( ) + " with " + currency ) ; } return new Cash ( currency , BigDecimalUtil . add ( amount , money . getAmount ( ) ) ) ; }
Add the amount with the existing one and return a new immutable Money .
2,290
public boolean isWeekend ( final Date date ) { if ( date != null && delegate != null ) { return delegate . isWeekend ( Utils . getCal ( date ) ) ; } return false ; }
is the date a non - working day according to the WorkingWeek?
2,291
public static BigDecimal bd ( final String val ) { return val != null && val . length ( ) > 0 ? new BigDecimal ( val ) : null ; }
Convenience method to create a BigDecimal with a String can be statically imported .
2,292
public static BigDecimal inverse ( final BigDecimal value ) { if ( isNotZero ( value ) ) { return BigDecimal . ONE . setScale ( MAX_SCALE_FOR_INVERSE ) . divide ( value , BigDecimal . ROUND_HALF_UP ) ; } return null ; }
Return the inverse of value if no tnull of zero
2,293
public static boolean isSameAbsValue ( final BigDecimal v1 , final BigDecimal v2 ) { return isSameValue ( abs ( v1 ) , abs ( v2 ) ) ; }
Check ABS values of v1 and v2 .
2,294
public static BigDecimal roundTo ( final BigDecimal bd , final int numberOfDecPlaces , final int finalScale ) { return setScale ( setScale ( bd , numberOfDecPlaces , BigDecimal . ROUND_HALF_UP ) , finalScale ) ; }
returns a new BigDecimal with correct scale after being round to n dec places .
2,295
public static BigDecimal setScale ( final BigDecimal bd , final int scale ) { return setScale ( bd , scale , BigDecimal . ROUND_HALF_UP ) ; }
returns a new BigDecimal with correct scale .
2,296
public static BigDecimal setScale ( final BigDecimal bd , final Integer scale , final int rounding ) { if ( bd != null && scale != null ) { return bd . setScale ( scale , rounding ) ; } return null ; }
returns a new BigDecimal with correct Scales . PERCENT_SCALE . This is used by the table renderer .
2,297
public static String percentFormat ( final BigDecimal bd ) { return bd != null ? NUMBER_FORMAT . format ( bd . movePointRight ( 2 ) ) : "" ; }
return a Number formatted or empty string if null .
2,298
public static BigDecimal ensureMin ( final BigDecimal minimum , final BigDecimal value ) { return BigDecimalUtil . compareTo ( minimum , value ) == 1 ? minimum : value ; }
Return minimum if the value is &lt ; minimum .
2,299
public static BigDecimal forceNegativeIfTrue ( final boolean condition , final BigDecimal amount ) { return condition ? BigDecimalUtil . negate ( BigDecimalUtil . abs ( amount ) ) : BigDecimalUtil . abs ( amount ) ; }
Return a negative amount based on amount if true otherwise return the ABS .