idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
10,900
public static String escapeInstancePath ( String instancePath ) { String result ; if ( Utils . isEmptyOrWhitespaces ( instancePath ) ) result = "" ; else result = instancePath . replaceFirst ( "^/*" , "" ) . replaceFirst ( "/*$" , "" ) . replaceAll ( "/+" , "." ) ; return result ; }
Removes unnecessary slashes and transforms the others into dots .
10,901
public static String buildId ( RecipientKind ownerKind , String domain , String applicationName , String scopedInstancePath ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "[ " ) ; sb . append ( domain ) ; sb . append ( " ] " ) ; if ( ownerKind == RecipientKind . DM ) { sb . append ( "DM" ) ; } else { sb . append ( scopedInstancePath ) ; sb . append ( " @ " ) ; sb . append ( applicationName ) ; } return sb . toString ( ) ; }
Builds a string identifying a messaging client .
10,902
private boolean checkVmIsOnline ( ) { String zoneName = OpenstackIaasHandler . findZoneName ( this . novaApi , this . targetProperties ) ; Server server = this . novaApi . getServerApiForZone ( zoneName ) . get ( this . machineId ) ; return Status . ACTIVE . equals ( server . getStatus ( ) ) ; }
Checks whether a VM is created .
10,903
public boolean prepareObjectStorage ( ) throws TargetException { String domains = this . targetProperties . get ( OBJ_STORAGE_DOMAINS ) ; if ( ! Utils . isEmptyOrWhitespaces ( domains ) ) { String zoneName = OpenstackIaasHandler . findZoneName ( this . novaApi , this . targetProperties ) ; SwiftApi swiftApi = OpenstackIaasHandler . swiftApi ( this . targetProperties ) ; try { List < String > existingDomainNames = new ArrayList < > ( ) ; for ( Container container : swiftApi . getContainerApi ( zoneName ) . list ( ) ) { existingDomainNames . add ( container . getName ( ) ) ; } List < String > domainsToCreate = Utils . splitNicely ( domains , "," ) ; domainsToCreate . removeAll ( existingDomainNames ) ; for ( String domainName : domainsToCreate ) { this . logger . info ( "Creating container " + domainName + " (object storage)..." ) ; swiftApi . getContainerApi ( zoneName ) . create ( domainName ) ; } } catch ( Exception e ) { throw new TargetException ( e ) ; } finally { try { swiftApi . close ( ) ; } catch ( IOException e ) { throw new TargetException ( e ) ; } } } return true ; }
Configures the object storage .
10,904
String [ ] splitFromInlineComment ( String line ) { String [ ] result = new String [ ] { line , "" } ; int index = line . indexOf ( ParsingConstants . COMMENT_DELIMITER ) ; if ( index >= 0 ) { result [ 0 ] = line . substring ( 0 , index ) ; if ( ! this . ignoreComments ) { Matcher m = Pattern . compile ( "(\\s+)$" ) . matcher ( result [ 0 ] ) ; String prefix = "" ; if ( m . find ( ) ) prefix = m . group ( 1 ) ; result [ 1 ] = prefix + line . substring ( index ) ; } result [ 0 ] = result [ 0 ] . trim ( ) ; } return result ; }
Splits the line from the comment delimiter .
10,905
private void fillIn ( ) throws IOException { BufferedReader br = null ; InputStream in = null ; try { in = new FileInputStream ( this . definitionFile . getEditedFile ( ) ) ; br = new BufferedReader ( new InputStreamReader ( in , StandardCharsets . UTF_8 ) ) ; String line ; while ( ( line = nextLine ( br ) ) != null ) { int code = recognizeBlankLine ( line , this . definitionFile . getBlocks ( ) ) ; if ( code == P_CODE_YES ) continue ; code = recognizeComment ( line , this . definitionFile . getBlocks ( ) ) ; if ( code == P_CODE_YES ) continue ; code = recognizeImport ( line ) ; if ( code == P_CODE_CANCEL ) break ; else if ( code == P_CODE_YES ) continue ; code = recognizeFacet ( line , br ) ; if ( code == P_CODE_CANCEL ) break ; else if ( code == P_CODE_YES ) continue ; code = recognizeInstanceOf ( line , br , null ) ; if ( code == P_CODE_CANCEL ) break ; else if ( code == P_CODE_YES ) continue ; code = recognizeComponent ( line , br ) ; if ( code != P_CODE_YES ) this . definitionFile . getBlocks ( ) . add ( new BlockUnknown ( this . definitionFile , line ) ) ; if ( code == P_CODE_CANCEL ) break ; if ( code == P_CODE_NO ) addModelError ( ErrorCode . P_UNRECOGNIZED_BLOCK ) ; } if ( line == null && this . lastLineEndedWithLineBreak ) this . definitionFile . getBlocks ( ) . add ( new BlockBlank ( this . definitionFile , "" ) ) ; } finally { Utils . closeQuietly ( br ) ; Utils . closeQuietly ( in ) ; } }
Parses the file and fills - in the resulting structure .
10,906
public static String commentLine ( String line ) { String result = line ; if ( ! Utils . isEmptyOrWhitespaces ( line ) && ! line . trim ( ) . startsWith ( ParsingConstants . COMMENT_DELIMITER ) ) result = ParsingConstants . COMMENT_DELIMITER + line ; return result ; }
Comments a line .
10,907
static String cleanPath ( String path ) { return path . replaceFirst ( "^" + ServletRegistrationComponent . REST_CONTEXT + "/" , "/" ) . replaceFirst ( "^" + ServletRegistrationComponent . WEBSOCKET_CONTEXT + "/" , "/" ) . replaceFirst ( "\\?.*" , "" ) ; }
Cleans the path by removing the servlet paths and URL parameters .
10,908
public static synchronized void resetAllCounters ( ) { initializeCount . set ( 0 ) ; deployCount . set ( 0 ) ; undeployCount . set ( 0 ) ; startCount . set ( 0 ) ; stopCount . set ( 0 ) ; updateCount . set ( 0 ) ; errorCount . set ( 0 ) ; }
Resets all counters .
10,909
public String queryLivestatus ( String nagiosQuery ) throws UnknownHostException , IOException { Socket liveStatusSocket = null ; try { this . logger . fine ( "About to open a connection through Live Status..." ) ; liveStatusSocket = new Socket ( this . host , this . port ) ; this . logger . fine ( "A connection was established through Live Status." ) ; Writer osw = new OutputStreamWriter ( liveStatusSocket . getOutputStream ( ) , StandardCharsets . UTF_8 ) ; PrintWriter printer = new PrintWriter ( osw , false ) ; printer . print ( nagiosQuery ) ; printer . flush ( ) ; liveStatusSocket . shutdownOutput ( ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; Utils . copyStreamSafely ( liveStatusSocket . getInputStream ( ) , os ) ; String result = os . toString ( "UTF-8" ) ; result = format ( nagiosQuery , result ) ; return result ; } finally { if ( liveStatusSocket != null ) liveStatusSocket . close ( ) ; this . logger . fine ( "The Live Status connection was closed." ) ; } }
Queries a live status server .
10,910
Diagnostic createDiagnostic ( Instance instance ) { Diagnostic result = new Diagnostic ( InstanceHelpers . computeInstancePath ( instance ) ) ; for ( Map . Entry < String , Boolean > entry : ComponentHelpers . findComponentDependenciesFor ( instance . getComponent ( ) ) . entrySet ( ) ) { String facetOrComponentName = entry . getKey ( ) ; Collection < Import > imports = instance . getImports ( ) . get ( facetOrComponentName ) ; boolean resolved = imports != null && ! imports . isEmpty ( ) ; boolean optional = entry . getValue ( ) ; result . getDependenciesInformation ( ) . add ( new DependencyInformation ( facetOrComponentName , optional , resolved ) ) ; } return result ; }
Creates a diagnostic for an instance .
10,911
public static Map < String , ExportedVariable > parseExportedVariables ( String line ) { Pattern randomPattern = Pattern . compile ( ParsingConstants . PROPERTY_GRAPH_RANDOM_PATTERN , Pattern . CASE_INSENSITIVE ) ; Pattern varPattern = Pattern . compile ( "([^,=]+)(\\s*=\\s*(\"([^\",]+)\"|([^,]+)))?" ) ; Map < String , ExportedVariable > result = new LinkedHashMap < > ( ) ; Matcher varMatcher = varPattern . matcher ( line ) ; while ( varMatcher . find ( ) ) { String key = varMatcher . group ( 1 ) . trim ( ) ; if ( Utils . isEmptyOrWhitespaces ( key ) ) continue ; String value = null ; if ( varMatcher . group ( 3 ) != null ) { if ( varMatcher . group ( 5 ) != null ) value = varMatcher . group ( 5 ) . trim ( ) ; else value = varMatcher . group ( 4 ) ; } ExportedVariable var = new ExportedVariable ( ) ; Matcher m = randomPattern . matcher ( key ) ; if ( m . matches ( ) ) { var . setRandom ( true ) ; var . setRawKind ( m . group ( 1 ) ) ; key = m . group ( 2 ) . trim ( ) ; } var . setName ( key . trim ( ) ) ; if ( value != null ) var . setValue ( value ) ; result . put ( var . getName ( ) , var ) ; } return result ; }
Parse a list of exported variables .
10,912
public static Set < String > findPrefixesForExportedVariables ( Instance instance ) { Set < String > result = new HashSet < > ( ) ; for ( String exportedVariableName : InstanceHelpers . findAllExportedVariables ( instance ) . keySet ( ) ) result . add ( VariableHelpers . parseVariableName ( exportedVariableName ) . getKey ( ) ) ; return result ; }
Finds the component and facet names that prefix the variables an instance exports .
10,913
public static Set < String > findPrefixesForImportedVariables ( Instance instance ) { Set < String > result = new HashSet < > ( ) ; for ( ImportedVariable var : ComponentHelpers . findAllImportedVariables ( instance . getComponent ( ) ) . values ( ) ) result . add ( VariableHelpers . parseVariableName ( var . getName ( ) ) . getKey ( ) ) ; return result ; }
Finds the component and facet names that prefix the variables an instance imports .
10,914
public void setDescription ( String applicationName , String newDesc ) throws ApplicationWsException { this . logger . finer ( "Updating the description of application " + applicationName + "." ) ; WebResource path = this . resource . path ( UrlConstants . APP ) . path ( applicationName ) . path ( "description" ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . TEXT_PLAIN ) . post ( ClientResponse . class , newDesc ) ; handleResponse ( response ) ; this . logger . finer ( String . valueOf ( response . getStatusInfo ( ) ) ) ; }
Changes the description of an application .
10,915
public void undeployAll ( String applicationName , String instancePath ) throws ApplicationWsException { this . logger . finer ( "Undeploying instances in " + applicationName + " from instance = " + instancePath ) ; WebResource path = this . resource . path ( UrlConstants . APP ) . path ( applicationName ) . path ( "undeploy-all" ) ; if ( instancePath != null ) path = path . queryParam ( "instance-path" , instancePath ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . post ( ClientResponse . class ) ; handleResponse ( response ) ; this . logger . finer ( String . valueOf ( response . getStatusInfo ( ) ) ) ; }
Undeploys several instances at once .
10,916
public List < Instance > listChildrenInstances ( String applicationName , String instancePath , boolean all ) { this . logger . finer ( "Listing children instances for " + instancePath + " in " + applicationName + "." ) ; WebResource path = this . resource . path ( UrlConstants . APP ) . path ( applicationName ) . path ( "instances" ) . queryParam ( "all-children" , String . valueOf ( all ) ) ; if ( instancePath != null ) path = path . queryParam ( "instance-path" , instancePath ) ; List < Instance > result = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . type ( MediaType . APPLICATION_JSON ) . get ( new GenericType < List < Instance > > ( ) { } ) ; if ( result != null ) { this . logger . finer ( result . size ( ) + " children instances were found for " + instancePath + " in " + applicationName + "." ) ; } else { this . logger . finer ( "No child instance was found for " + instancePath + " in " + applicationName + "." ) ; result = new ArrayList < > ( 0 ) ; } return result ; }
Lists all the children of an instance .
10,917
public void addInstance ( String applicationName , String parentInstancePath , Instance instance ) throws ApplicationWsException { this . logger . finer ( "Adding an instance to the application " + applicationName + "..." ) ; WebResource path = this . resource . path ( UrlConstants . APP ) . path ( applicationName ) . path ( "instances" ) ; if ( parentInstancePath != null ) path = path . queryParam ( "instance-path" , parentInstancePath ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . type ( MediaType . APPLICATION_JSON ) . post ( ClientResponse . class , instance ) ; handleResponse ( response ) ; this . logger . finer ( String . valueOf ( response . getStatusInfo ( ) ) ) ; }
Adds an instance into an application .
10,918
public void removeInstance ( String applicationName , String instancePath ) { this . logger . finer ( String . format ( "Removing instance \"%s\" from application \"%s\"..." , instancePath , applicationName ) ) ; WebResource path = this . resource . path ( UrlConstants . APP ) . path ( applicationName ) . path ( "instances" ) . queryParam ( "instance-path" , instancePath ) ; this . wsClient . createBuilder ( path ) . delete ( ) ; this . logger . finer ( String . format ( "Instance \"%s\" has been removed from application \"%s\"" , instancePath , applicationName ) ) ; }
Removes an instance .
10,919
public void bindApplication ( String applicationName , String boundTplName , String boundApp ) throws ApplicationWsException { this . logger . finer ( "Creating a binding for external exports in " + applicationName + "..." ) ; WebResource path = this . resource . path ( UrlConstants . APP ) . path ( applicationName ) . path ( "bind" ) . queryParam ( "bound-tpl" , boundTplName ) . queryParam ( "bound-app" , boundApp ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . post ( ClientResponse . class ) ; handleResponse ( response ) ; }
Binds an application for external exports .
10,920
public List < String > listAllCommands ( String applicationName ) { this . logger . finer ( "Listing commands in " + applicationName + "..." ) ; WebResource path = this . resource . path ( UrlConstants . APP ) . path ( applicationName ) . path ( "commands" ) ; List < String > result = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . get ( new GenericType < List < String > > ( ) { } ) ; if ( result != null ) { this . logger . finer ( result . size ( ) + " command(s) were found for " + applicationName + "." ) ; } else { this . logger . finer ( "No command was found for " + applicationName + "." ) ; result = new ArrayList < > ( 0 ) ; } return result ; }
Lists application commands .
10,921
public PluginInterface findPlugin ( Instance instance ) { PluginInterface result = null ; if ( this . simulatePlugins ) { this . logger . finer ( "Simulating plugins..." ) ; result = new PluginMock ( ) ; } else { String installerName = null ; if ( instance . getComponent ( ) != null ) installerName = ComponentHelpers . findComponentInstaller ( instance . getComponent ( ) ) ; for ( PluginInterface pi : this . plugins ) { if ( pi . getPluginName ( ) . equalsIgnoreCase ( installerName ) ) { result = pi ; break ; } } if ( result == null ) this . logger . severe ( "No plugin was found for instance '" + instance . getName ( ) + "' with installer '" + installerName + "'." ) ; } if ( result != null ) result . setNames ( this . applicationName , this . scopedInstancePath ) ; return result == null ? null : new PluginProxy ( result ) ; }
Finds the right plug - in for an instance .
10,922
public void listPlugins ( ) { if ( this . plugins . isEmpty ( ) ) { this . logger . info ( "No plug-in was found for Roboconf's agent." ) ; } else { StringBuilder sb = new StringBuilder ( "Available plug-ins in Roboconf's agent: " ) ; for ( Iterator < PluginInterface > it = this . plugins . iterator ( ) ; it . hasNext ( ) ; ) { sb . append ( it . next ( ) . getPluginName ( ) ) ; if ( it . hasNext ( ) ) sb . append ( ", " ) ; } sb . append ( "." ) ; this . logger . info ( sb . toString ( ) ) ; } }
This method lists the available plug - ins and logs it .
10,923
public void pluginAppears ( PluginInterface pi ) { if ( pi != null ) { this . logger . info ( "Plugin '" + pi . getPluginName ( ) + "' is now available in Roboconf's agent." ) ; this . plugins . add ( pi ) ; listPlugins ( ) ; } }
This method is invoked by iPojo every time a new plug - in appears .
10,924
public void pluginDisappears ( PluginInterface pi ) { if ( pi == null ) { this . logger . info ( "An invalid plugin is removed." ) ; } else { this . plugins . remove ( pi ) ; this . logger . info ( "Plugin '" + pi . getPluginName ( ) + "' is not available anymore in Roboconf's agent." ) ; } listPlugins ( ) ; }
This method is invoked by iPojo every time a plug - in disappears .
10,925
void reloadUserData ( ) { if ( Utils . isEmptyOrWhitespaces ( this . parameters ) ) { this . logger . warning ( "No parameters were specified in the agent configuration. No user data will be retrieved." ) ; } else if ( ! this . overrideProperties ) { this . logger . fine ( "User data are NOT supposed to be used." ) ; } else if ( Constants . AGENT_RESET . equalsIgnoreCase ( this . parameters ) ) { if ( getMessagingClient ( ) != null && getMessagingClient ( ) . getMessageProcessor ( ) != null ) ( ( AgentMessageProcessor ) getMessagingClient ( ) . getMessageProcessor ( ) ) . resetRequest ( ) ; } else { AgentProperties props = null ; this . logger . fine ( "User data are supposed to be used. Retrieving in progress..." ) ; if ( AgentConstants . PLATFORM_EC2 . equalsIgnoreCase ( this . parameters ) || AgentConstants . PLATFORM_OPENSTACK . equalsIgnoreCase ( this . parameters ) ) props = this . userDataHelper . findParametersForAmazonOrOpenStack ( this . logger ) ; else if ( AgentConstants . PLATFORM_AZURE . equalsIgnoreCase ( this . parameters ) ) props = this . userDataHelper . findParametersForAzure ( this . logger ) ; else if ( AgentConstants . PLATFORM_VMWARE . equalsIgnoreCase ( this . parameters ) ) props = this . userDataHelper . findParametersForVmware ( this . logger ) ; else if ( Constants . AGENT_RESET . equalsIgnoreCase ( this . parameters ) ) props = new AgentProperties ( ) ; else props = this . userDataHelper . findParametersFromUrl ( this . parameters , this . logger ) ; if ( props != null ) { String errorMessage = null ; if ( ! Constants . AGENT_RESET . equalsIgnoreCase ( this . parameters ) && ( errorMessage = props . validate ( ) ) != null ) { this . logger . severe ( "An error was found in user data. " + errorMessage ) ; } this . applicationName = props . getApplicationName ( ) ; this . domain = props . getDomain ( ) ; this . scopedInstancePath = props . getScopedInstancePath ( ) ; if ( ! Utils . isEmptyOrWhitespaces ( props . getIpAddress ( ) ) ) { this . ipAddress = props . getIpAddress ( ) ; this . logger . info ( "The agent's address was overwritten from user data and set to " + this . ipAddress ) ; } try { this . logger . info ( "Reconfiguring the agent with user data." ) ; this . userDataHelper . reconfigureMessaging ( this . karafEtc , props . getMessagingConfiguration ( ) ) ; } catch ( Exception e ) { this . logger . severe ( "Error in messaging reconfiguration from user data: " + e ) ; } } } }
Reloads user data .
10,926
public boolean checkParameter ( String key , String value ) { if ( null == value ) { return true ; } value = value . toLowerCase ( ) ; if ( value . contains ( "'" ) ) { return false ; } if ( value . contains ( "--" ) ) { return false ; } if ( value . contains ( "drop " ) ) { return false ; } if ( value . contains ( "insert " ) ) { return false ; } if ( value . contains ( "select " ) ) { return false ; } if ( value . contains ( "delete " ) ) { return false ; } if ( value . contains ( "<" ) ) { return false ; } if ( value . contains ( ">" ) ) { return false ; } return true ; }
returns true if the parameter seems to be ok .
10,927
public String createOrUpdateJob ( String jobId , String jobName , String appName , String cmdName , String cron ) throws SchedulerWsException { if ( jobId == null ) this . logger . finer ( "Creating a new scheduled job." ) ; else this . logger . finer ( "Updating the following scheduled job: " + jobId ) ; WebResource path = this . resource . path ( UrlConstants . SCHEDULER ) ; if ( jobId != null ) path = path . queryParam ( "job-id" , jobId ) ; path = path . queryParam ( "job-name" , jobName ) ; path = path . queryParam ( "app-name" , appName ) ; path = path . queryParam ( "cmd-name" , cmdName ) ; path = path . queryParam ( "cron" , cron ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . post ( ClientResponse . class ) ; handleResponse ( response ) ; StringWrapper wrapper = response . getEntity ( StringWrapper . class ) ; return wrapper . toString ( ) ; }
Creates or updates a scheduled job .
10,928
public void deleteJob ( String jobId ) throws SchedulerWsException { this . logger . finer ( "Deleting scheduled job: " + jobId ) ; WebResource path = this . resource . path ( UrlConstants . SCHEDULER ) . path ( jobId ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . delete ( ClientResponse . class ) ; handleResponse ( response ) ; }
Deletes a scheduled job .
10,929
public ScheduledJob getJobProperties ( String jobId ) throws SchedulerWsException { this . logger . finer ( "Getting the properties of a scheduled job: " + jobId ) ; WebResource path = this . resource . path ( UrlConstants . SCHEDULER ) . path ( jobId ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . get ( ClientResponse . class ) ; handleResponse ( response ) ; return response . getEntity ( ScheduledJob . class ) ; }
Gets the properties of a scheduled job .
10,930
public static synchronized Process getProcess ( String applicationName , String scopedInstancePath ) { return PROCESS_MAP . get ( toAgentId ( applicationName , scopedInstancePath ) ) ; }
Retrieves a stored process when found .
10,931
public static synchronized Process clearProcess ( String applicationName , String scopedInstancePath ) { return PROCESS_MAP . remove ( toAgentId ( applicationName , scopedInstancePath ) ) ; }
Removes a stored process if found .
10,932
public static Object getAttribute ( UIComponent component , String attributeName ) { Object value = component . getPassThroughAttributes ( ) . get ( attributeName ) ; if ( null == value ) { value = component . getAttributes ( ) . get ( attributeName ) ; } if ( null == value ) { if ( ! attributeName . equals ( attributeName . toLowerCase ( ) ) ) { return getAttribute ( component , attributeName . toLowerCase ( ) ) ; } } if ( value instanceof ValueExpression ) { value = ( ( ValueExpression ) value ) . getValue ( FacesContext . getCurrentInstance ( ) . getELContext ( ) ) ; } return value ; }
Apache MyFaces make HMTL attributes of HTML elements pass - through - attributes . This method finds the attribute no matter whether it is stored as an ordinary or as an pass - through - attribute .
10,933
public static String getAttributeAsString ( UIComponent component , String attributeName ) { try { Object attribute = getAttribute ( component , attributeName ) ; if ( null != attribute ) { if ( attribute instanceof ValueExpression ) { return ( String ) ( ( ValueExpression ) attribute ) . getValue ( FacesContext . getCurrentInstance ( ) . getELContext ( ) ) ; } else if ( attribute instanceof String ) { return ( String ) attribute ; } else { LOGGER . severe ( "unexpected data type of label: " + attributeName + " type:" + attribute . getClass ( ) . getName ( ) ) ; return "unexpected data type of label: " + attributeName + " type:" + attribute . getClass ( ) . getName ( ) ; } } if ( null == attribute ) { ValueExpression vex = component . getValueExpression ( attributeName ) ; if ( null != vex ) { return ( String ) vex . getValue ( FacesContext . getCurrentInstance ( ) . getELContext ( ) ) ; } } } catch ( ClassCastException error ) { LOGGER . fine ( "Attribute is not a String: " + attributeName ) ; } return null ; }
Apache MyFaces sometimes returns a ValueExpression when you read an attribute . Mojarra does not but requires a second call . The method treats both frameworks in a uniform way and evaluates the expression if needed returning a String value .
10,934
protected File generateTemplate ( File template , Instance instance ) throws IOException { String scriptName = instance . getName ( ) . replace ( "\\s+" , "_" ) ; File generated = File . createTempFile ( scriptName , ".script" ) ; InstanceTemplateHelper . injectInstanceImports ( instance , template , generated ) ; return generated ; }
Generates a file from the template and the instance .
10,935
public static StringBuilder formatErrors ( Collection < ? extends RoboconfError > errors , Log log ) { StringBuilder result = new StringBuilder ( ) ; for ( Map . Entry < RoboconfError , String > entry : RoboconfErrorHelpers . formatErrors ( errors , null , true ) . entrySet ( ) ) { if ( entry . getKey ( ) . getErrorCode ( ) . getLevel ( ) == ErrorLevel . WARNING ) log . warn ( entry . getValue ( ) ) ; else log . error ( entry . getValue ( ) ) ; result . append ( entry . getValue ( ) ) ; result . append ( "\n" ) ; } return result ; }
Formats a Roboconf errors and outputs it in the logs .
10,936
public void encodeBegin ( FacesContext context , UIComponent component ) throws IOException { long timer = System . nanoTime ( ) ; long random = ( long ) ( Math . random ( ) * Integer . MAX_VALUE ) ; long token = timer ^ random ; NGSecureUtilities . setSecurityToken ( String . valueOf ( token ) , component . getClientId ( ) ) ; super . encodeBegin ( context , component ) ; NGSecurityFilter filter = findAndVerifySecurityFilter ( context , component ) ; showLegalDisclaimer ( context , filter ) ; }
Stores a unique token in the session to prevent repeated submission of the same form .
10,937
public static DockerClient createDockerClient ( Map < String , String > targetProperties ) throws TargetException { Logger logger = Logger . getLogger ( DockerHandler . class . getName ( ) ) ; logger . fine ( "Setting the target properties." ) ; String edpt = targetProperties . get ( DockerHandler . ENDPOINT ) ; if ( Utils . isEmptyOrWhitespaces ( edpt ) ) edpt = DockerHandler . DEFAULT_ENDPOINT ; Builder config = DefaultDockerClientConfig . createDefaultConfigBuilder ( ) . withDockerHost ( edpt ) . withRegistryUsername ( targetProperties . get ( DockerHandler . USER ) ) . withRegistryPassword ( targetProperties . get ( DockerHandler . PASSWORD ) ) . withRegistryEmail ( targetProperties . get ( DockerHandler . EMAIL ) ) . withApiVersion ( targetProperties . get ( DockerHandler . VERSION ) ) ; DockerClientBuilder clientBuilder = DockerClientBuilder . getInstance ( config . build ( ) ) ; return clientBuilder . build ( ) ; }
Creates a Docker client from target properties .
10,938
public static void deleteImageIfItExists ( String imageId , DockerClient dockerClient ) { if ( imageId != null ) { List < Image > images = dockerClient . listImagesCmd ( ) . exec ( ) ; if ( findImageById ( imageId , images ) != null ) dockerClient . removeImageCmd ( imageId ) . withForce ( true ) . exec ( ) ; } }
Deletes a Docker image if it exists .
10,939
public static Image findImageByIdOrByTag ( String name , DockerClient dockerClient ) { Image image = null ; if ( ! Utils . isEmptyOrWhitespaces ( name ) ) { Logger logger = Logger . getLogger ( DockerUtils . class . getName ( ) ) ; List < Image > images = dockerClient . listImagesCmd ( ) . exec ( ) ; if ( ( image = DockerUtils . findImageById ( name , images ) ) != null ) logger . fine ( "Found a Docker image with ID " + name ) ; else if ( ( image = DockerUtils . findImageByTag ( name , images ) ) != null ) logger . fine ( "Found a Docker image with tag " + name ) ; } return image ; }
Finds an image by ID or by tag .
10,940
public static Image findImageById ( String imageId , List < Image > images ) { Image result = null ; for ( Image img : images ) { if ( img . getId ( ) . equals ( imageId ) ) { result = img ; break ; } } return result ; }
Finds an image by ID .
10,941
public static Image findImageByTag ( String imageTag , List < Image > images ) { Image result = null ; for ( Image img : images ) { String [ ] tags = img . getRepoTags ( ) ; if ( tags == null ) continue ; for ( String s : tags ) { if ( s . contains ( imageTag ) ) { result = img ; break ; } } } return result ; }
Finds an image by tag .
10,942
public static Container findContainerByIdOrByName ( String name , DockerClient dockerClient ) { Container result = null ; List < Container > containers = dockerClient . listContainersCmd ( ) . withShowAll ( true ) . exec ( ) ; for ( Container container : containers ) { List < String > names = Arrays . asList ( container . getNames ( ) ) ; if ( container . getId ( ) . equals ( name ) || names . contains ( "/" + name ) ) { result = container ; break ; } } return result ; }
Finds a container by ID or by name .
10,943
public static ContainerState getContainerState ( String containerId , DockerClient dockerClient ) { ContainerState result = null ; try { InspectContainerResponse resp = dockerClient . inspectContainerCmd ( containerId ) . exec ( ) ; if ( resp != null ) result = resp . getState ( ) ; } catch ( Exception e ) { } return result ; }
Gets the state of a container .
10,944
public static void configureOptions ( Map < String , String > options , CreateContainerCmd cmd ) throws TargetException { Logger logger = Logger . getLogger ( DockerUtils . class . getName ( ) ) ; Map < String , List < String > > hackedSetterNames = new HashMap < > ( ) ; List < Class < ? > > types = new ArrayList < > ( ) ; types . add ( String . class ) ; types . add ( String [ ] . class ) ; types . add ( long . class ) ; types . add ( Long . class ) ; types . add ( int . class ) ; types . add ( Integer . class ) ; types . add ( boolean . class ) ; types . add ( Boolean . class ) ; types . add ( Capability [ ] . class ) ; for ( Map . Entry < String , String > entry : options . entrySet ( ) ) { String optionValue = entry . getValue ( ) ; String methodName = entry . getKey ( ) . replace ( "-" , " " ) . trim ( ) ; methodName = WordUtils . capitalize ( methodName ) ; methodName = methodName . replace ( " " , "" ) ; methodName = "with" + methodName ; Method _m = null ; for ( Method m : cmd . getClass ( ) . getMethods ( ) ) { boolean sameMethod = methodName . equalsIgnoreCase ( m . getName ( ) ) ; boolean methodWithAlias = hackedSetterNames . containsKey ( methodName ) && hackedSetterNames . get ( methodName ) . contains ( m . getName ( ) ) ; if ( sameMethod || methodWithAlias ) { if ( m . getParameterTypes ( ) . length != 1 ) { logger . warning ( "A method was found for " + entry . getKey ( ) + " but it does not have the right number of parameters." ) ; continue ; } if ( ! types . contains ( m . getParameterTypes ( ) [ 0 ] ) ) { logger . warning ( "A method was found for " + entry . getKey ( ) + " but it does not have the right parameter type. " + "Skipping it. You may want to add a feature request." ) ; continue ; } _m = m ; break ; } } if ( _m == null ) throw new TargetException ( "Nothing matched the " + entry . getKey ( ) + " option in the REST API. Please, report it." ) ; try { Object o = prepareParameter ( optionValue , _m . getParameterTypes ( ) [ 0 ] ) ; _m . invoke ( cmd , o ) ; } catch ( ReflectiveOperationException | IllegalArgumentException e ) { throw new TargetException ( "Option " + entry . getKey ( ) + " could not be set." ) ; } } }
Finds the options and tries to configure them on the creation command .
10,945
public static Object prepareParameter ( String rawValue , Class < ? > clazz ) throws TargetException { Object result ; if ( clazz == int . class || clazz == Integer . class ) result = Integer . parseInt ( rawValue ) ; else if ( clazz == long . class || clazz == Long . class ) result = Long . parseLong ( rawValue ) ; else if ( clazz == boolean . class || clazz == Boolean . class ) result = Boolean . parseBoolean ( rawValue ) ; else if ( clazz == String [ ] . class ) { List < String > parts = Utils . splitNicely ( rawValue , "," ) ; result = parts . toArray ( new String [ parts . size ( ) ] ) ; } else if ( clazz == Capability [ ] . class ) { List < Capability > caps = new ArrayList < > ( ) ; for ( String s : Utils . splitNicely ( rawValue , "," ) ) { try { caps . add ( Capability . valueOf ( s ) ) ; } catch ( Exception e ) { throw new TargetException ( "Unknown capability: " + s ) ; } } result = caps . toArray ( new Capability [ caps . size ( ) ] ) ; } else result = rawValue ; return result ; }
Prepares the parameter to pass it to the REST API .
10,946
public static String findDefaultImageVersion ( String rawVersion ) { String rbcfVersion = rawVersion ; if ( rbcfVersion == null || rbcfVersion . toLowerCase ( ) . endsWith ( "snapshot" ) ) rbcfVersion = LATEST ; return rbcfVersion ; }
Finds the version of the default Docker image .
10,947
public static String buildContainerNameFrom ( String scopedInstancePath , String applicationName ) { String containerName = scopedInstancePath + "_from_" + applicationName ; containerName = containerName . replaceFirst ( "^/" , "" ) . replace ( "/" , "-" ) . replaceAll ( "\\s+" , "_" ) ; if ( containerName . length ( ) > 61 ) containerName = containerName . substring ( 0 , 61 ) ; return containerName ; }
Builds a container name .
10,948
public FileDefinition buildFileDefinition ( Collection < Instance > rootInstances , File targetFile , boolean addComment , boolean saveRuntimeInformation ) { FileDefinition result = new FileDefinition ( targetFile ) ; result . setFileType ( FileDefinition . INSTANCE ) ; if ( addComment ) { String s = "# File created from an in-memory model,\n# without a binding to existing files." ; BlockComment initialComment = new BlockComment ( result , s ) ; result . getBlocks ( ) . add ( initialComment ) ; result . getBlocks ( ) . add ( new BlockBlank ( result , "\n" ) ) ; } for ( Instance rootInstance : rootInstances ) result . getBlocks ( ) . addAll ( buildInstanceOf ( result , rootInstance , addComment , saveRuntimeInformation ) ) ; return result ; }
Builds a file definition from a collection of instances .
10,949
Properties readProperties ( Instance instance ) throws PluginException { Properties result = null ; File instanceDirectory = InstanceHelpers . findInstanceDirectoryOnAgent ( instance ) ; File file = new File ( instanceDirectory , FILE_NAME ) ; try { if ( file . exists ( ) ) { result = Utils . readPropertiesFile ( file ) ; } else { this . logger . warning ( file + " does not exist or is invalid. There is no instruction for the plugin." ) ; result = new Properties ( ) ; } } catch ( IOException e ) { throw new PluginException ( e ) ; } return result ; }
Reads the instructions . properties file .
10,950
SortedSet < Action > findActions ( String actionName , Properties properties ) { Pattern pattern = Pattern . compile ( actionName + "\\.(\\d)+\\.(.*)" , Pattern . CASE_INSENSITIVE ) ; SortedSet < Action > result = new TreeSet < Action > ( new ActionComparator ( ) ) ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { String key = String . valueOf ( entry . getKey ( ) ) . toLowerCase ( ) ; Matcher m = pattern . matcher ( key ) ; if ( ! m . matches ( ) ) continue ; int position = Integer . parseInt ( m . group ( 1 ) ) ; ActionType actionType = ActionType . which ( m . group ( 2 ) ) ; String parameter = String . valueOf ( entry . getValue ( ) ) ; result . add ( new Action ( position , actionType , parameter ) ) ; } return result ; }
Finds the actions to execute for a given step .
10,951
void executeAction ( Action action ) throws PluginException { try { switch ( action . actionType ) { case DELETE : this . logger . fine ( "Deleting " + action . parameter + "..." ) ; File f = new File ( action . parameter ) ; Utils . deleteFilesRecursively ( f ) ; break ; case DOWNLOAD : this . logger . fine ( "Downloading " + action . parameter + "..." ) ; URI uri = UriUtils . urlToUri ( action . parameter ) ; File targetFile = new File ( System . getProperty ( "java.io.tmpdir" ) , TMP_FILE ) ; InputStream in = null ; try { in = uri . toURL ( ) . openStream ( ) ; Utils . copyStream ( in , targetFile ) ; } finally { Utils . closeQuietly ( in ) ; } break ; case MOVE : List < String > parts = Utils . splitNicely ( action . parameter , "->" ) ; if ( parts . size ( ) != 2 ) { this . logger . warning ( "Invalid syntax for 'move' action. " + action . parameter ) ; } else { File source = new File ( parts . get ( 0 ) ) ; File target = new File ( parts . get ( 1 ) ) ; this . logger . fine ( "Moving " + source + " to " + target + "..." ) ; if ( ! source . renameTo ( target ) ) throw new IOException ( source + " could not be moved to " + target ) ; } break ; case COPY : parts = Utils . splitNicely ( action . parameter , "->" ) ; if ( parts . size ( ) != 2 ) { this . logger . warning ( "Invalid syntax for 'copy' action. " + action . parameter ) ; } else { File source = new File ( parts . get ( 0 ) ) ; File target = new File ( parts . get ( 1 ) ) ; this . logger . fine ( "Copying " + source + " to " + target + "..." ) ; Utils . copyStream ( source , target ) ; } break ; default : this . logger . fine ( "Ignoring the action..." ) ; break ; } } catch ( Exception e ) { throw new PluginException ( e ) ; } }
Executes an action .
10,952
private void send ( String message ) { if ( ! this . enabled . get ( ) ) { this . logger . finest ( "Notifications were disabled by the DM." ) ; } else if ( message == null ) { this . logger . finest ( "No message to send to web socket clients." ) ; } else synchronized ( SESSIONS ) { for ( Session session : SESSIONS ) { try { this . logger . finest ( "Sending a message to a web socket client..." ) ; session . getRemote ( ) . sendString ( message ) ; } catch ( IOException e ) { StringBuilder sb = new StringBuilder ( "A notification could not be propagated for session " ) ; sb . append ( session . getRemoteAddress ( ) ) ; sb . append ( "." ) ; if ( ! Utils . isEmptyOrWhitespaces ( e . getMessage ( ) ) ) sb . append ( " " + e . getMessage ( ) ) ; this . logger . severe ( sb . toString ( ) ) ; Utils . logException ( this . logger , e ) ; } } } }
Sends a message to all the connected sessions .
10,953
public String login ( String username , String password ) throws DebugWsException { this . logger . finer ( "Logging in as " + username ) ; WebResource path = this . resource . path ( UrlConstants . AUTHENTICATION ) . path ( "e" ) ; ClientResponse response = path . header ( "u" , username ) . header ( "p" , password ) . post ( ClientResponse . class ) ; if ( Family . SUCCESSFUL != response . getStatusInfo ( ) . getFamily ( ) ) { String value = response . getEntity ( String . class ) ; this . logger . finer ( response . getStatusInfo ( ) + ": " + value ) ; throw new DebugWsException ( response . getStatusInfo ( ) . getStatusCode ( ) , value ) ; } String sessionId = null ; List < NewCookie > cookies = response . getCookies ( ) ; if ( cookies != null ) { for ( NewCookie cookie : cookies ) { if ( UrlConstants . SESSION_ID . equals ( cookie . getName ( ) ) ) { sessionId = cookie . getValue ( ) ; break ; } } } this . wsClient . setSessionId ( sessionId ) ; this . logger . finer ( "Session ID: " + sessionId ) ; return sessionId ; }
Logs in with a user name and a password .
10,954
public void logout ( String sessionId ) throws DebugWsException { this . logger . finer ( "Logging out... Session ID = " + sessionId ) ; WebResource path = this . resource . path ( UrlConstants . AUTHENTICATION ) . path ( "s" ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . get ( ClientResponse . class ) ; this . logger . finer ( String . valueOf ( response . getStatusInfo ( ) ) ) ; this . wsClient . setSessionId ( null ) ; }
Terminates a session .
10,955
private void cancelRecipe ( String applicationName , String scopedInstancePath ) { if ( Utils . isEmptyOrWhitespaces ( applicationName ) ) applicationName = "" ; if ( Utils . isEmptyOrWhitespaces ( scopedInstancePath ) ) scopedInstancePath = "" ; this . out . println ( "looking up [" + applicationName + "] [" + scopedInstancePath + "]" ) ; Process p = ProcessStore . getProcess ( applicationName , scopedInstancePath ) ; if ( p != null ) { p . destroy ( ) ; ProcessStore . clearProcess ( applicationName , scopedInstancePath ) ; this . out . println ( "Recipe cancelled !" ) ; } else { this . out . println ( "No running recipe to cancel." ) ; } }
Cancels running recipe if any .
10,956
private String httpsQuery ( ) { String response = null ; try { TrustManager [ ] trustAllCerts = new TrustManager [ ] { new LocalX509TrustManager ( ) } ; final SSLContext sc = SSLContext . getInstance ( "SSL" ) ; sc . init ( null , trustAllCerts , new java . security . SecureRandom ( ) ) ; HttpsURLConnection . setDefaultSSLSocketFactory ( sc . getSocketFactory ( ) ) ; HostnameVerifier allHostsValid = new LocalHostnameVerifier ( ) ; HttpsURLConnection . setDefaultHostnameVerifier ( allHostsValid ) ; URL restUrl = new URL ( this . url ) ; HttpsURLConnection conn = ( HttpsURLConnection ) restUrl . openConnection ( ) ; response = query ( conn ) ; } catch ( Exception e ) { this . logger . severe ( "Cannot issue GET on URL " + this . url + ". Monitoring notification is discarded." ) ; Utils . logException ( this . logger , e ) ; } return response ; }
Query a https URL ignoring certificates .
10,957
private String httpQuery ( ) { String response = null ; try { URL restUrl = new URL ( this . url ) ; HttpURLConnection conn = ( HttpURLConnection ) restUrl . openConnection ( ) ; response = query ( conn ) ; } catch ( Exception e ) { this . logger . severe ( "Cannot issue GET on URL " + this . url + ". Monitoring notification is discarded." ) ; Utils . logException ( this . logger , e ) ; } return response ; }
Query a http URL .
10,958
public static Set < String > findGraphFilesToImport ( File appDirectory , File editedFile , String fileContent ) { File graphDir = new File ( appDirectory , Constants . PROJECT_DIR_GRAPH ) ; return findFilesToImport ( graphDir , Constants . FILE_EXT_GRAPH , editedFile , fileContent ) ; }
Finds all the graph files that can be imported .
10,959
public static Set < String > findInstancesFilesToImport ( File appDirectory , File editedFile , String fileContent ) { File instancesDir = new File ( appDirectory , Constants . PROJECT_DIR_INSTANCES ) ; return findFilesToImport ( instancesDir , Constants . FILE_EXT_INSTANCES , editedFile , fileContent ) ; }
Finds all the instances files that can be imported .
10,960
static Set < String > findFilesToImport ( File searchDirectory , String fileExtension , File editedFile , String fileContent ) { Set < String > result = new TreeSet < > ( ) ; if ( searchDirectory . exists ( ) ) { for ( File f : Utils . listAllFiles ( searchDirectory , fileExtension ) ) { if ( f . equals ( editedFile ) ) continue ; String path = Utils . computeFileRelativeLocation ( searchDirectory , f ) ; result . add ( path ) ; } } Pattern importPattern = Pattern . compile ( "\\b" + ParsingConstants . KEYWORD_IMPORT + "\\s+(.*)" , Pattern . CASE_INSENSITIVE ) ; Matcher m = importPattern . matcher ( fileContent ) ; while ( m . find ( ) ) { String imp = m . group ( 1 ) . trim ( ) ; if ( imp . endsWith ( ";" ) ) imp = imp . substring ( 0 , imp . length ( ) - 1 ) ; result . remove ( imp . trim ( ) ) ; } return result ; }
Finds all the files that can be imported .
10,961
public static RoboconfCompletionProposal basicProposal ( String s , String lastWord , boolean trim ) { return new RoboconfCompletionProposal ( s , trim ? s . trim ( ) : s , null , lastWord . length ( ) ) ; }
A convenience method to shorten the creation of a basic proposal .
10,962
public static Map < String , RoboconfTypeBean > findAllTypes ( File appDirectory ) { List < File > graphFiles = new ArrayList < > ( ) ; File graphDirectory = appDirectory ; if ( graphDirectory != null && graphDirectory . exists ( ) ) graphFiles = Utils . listAllFiles ( graphDirectory , Constants . FILE_EXT_GRAPH ) ; Map < String , RoboconfTypeBean > result = new HashMap < > ( ) ; for ( File f : graphFiles ) { try { FromGraphDefinition converter = new FromGraphDefinition ( appDirectory , true ) ; Graphs g = converter . buildGraphs ( f ) ; Collection < AbstractType > types = new ArrayList < > ( ) ; types . addAll ( ComponentHelpers . findAllComponents ( g ) ) ; types . addAll ( g . getFacetNameToFacet ( ) . values ( ) ) ; for ( AbstractType type : types ) { RoboconfTypeBean bean = new RoboconfTypeBean ( type . getName ( ) , converter . getTypeAnnotations ( ) . get ( type . getName ( ) ) , type instanceof Facet ) ; result . put ( type . getName ( ) , bean ) ; for ( Map . Entry < String , String > entry : ComponentHelpers . findAllExportedVariables ( type ) . entrySet ( ) ) { bean . exportedVariables . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } } catch ( Exception e ) { Logger logger = Logger . getLogger ( CompletionUtils . class . getName ( ) ) ; Utils . logException ( logger , e ) ; } } return result ; }
Finds all the Roboconf types .
10,963
public static String resolveStringDescription ( String variableName , String defaultValue ) { String result = null ; if ( Constants . SPECIFIC_VARIABLE_IP . equalsIgnoreCase ( variableName ) || variableName . toLowerCase ( ) . endsWith ( "." + Constants . SPECIFIC_VARIABLE_IP ) ) result = SET_BY_ROBOCONF ; else if ( ! Utils . isEmptyOrWhitespaces ( defaultValue ) ) result = DEFAULT_VALUE + defaultValue ; return result ; }
Resolves the description to show for an exported variable .
10,964
public Object getValue ( ) { final List < String > tokens = NGSecureUtilities . getSecurityToken ( ) ; return tokens . get ( tokens . size ( ) - 1 ) ; }
This components value is the security token .
10,965
public String checkMessagingConnectionForTheDm ( String message ) throws DebugWsException { this . logger . finer ( "Checking messaging connection with the DM: message=" + message ) ; WebResource path = this . resource . path ( UrlConstants . DEBUG ) . path ( "check-dm" ) ; if ( message != null ) path = path . queryParam ( "message" , message ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . get ( ClientResponse . class ) ; if ( Family . SUCCESSFUL != response . getStatusInfo ( ) . getFamily ( ) ) { String value = response . getEntity ( String . class ) ; this . logger . finer ( response . getStatusInfo ( ) + ": " + value ) ; throw new DebugWsException ( response . getStatusInfo ( ) . getStatusCode ( ) , value ) ; } this . logger . finer ( String . valueOf ( response . getStatusInfo ( ) ) ) ; return response . getEntity ( String . class ) ; }
Checks the DM is correctly connected with the messaging server .
10,966
public Diagnostic diagnoseInstance ( String applicationName , String instancePath ) throws DebugWsException { this . logger . finer ( "Diagnosing instance " + instancePath + " in application " + applicationName ) ; WebResource path = this . resource . path ( UrlConstants . DEBUG ) . path ( "diagnose-instance" ) ; path = path . queryParam ( "application-name" , applicationName ) ; path = path . queryParam ( "instance-path" , instancePath ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . get ( ClientResponse . class ) ; if ( Family . SUCCESSFUL != response . getStatusInfo ( ) . getFamily ( ) ) { String value = response . getEntity ( String . class ) ; this . logger . finer ( response . getStatusInfo ( ) + ": " + value ) ; throw new DebugWsException ( response . getStatusInfo ( ) . getStatusCode ( ) , value ) ; } this . logger . finer ( String . valueOf ( response . getStatusInfo ( ) ) ) ; return response . getEntity ( Diagnostic . class ) ; }
Runs a diagnostic for a given instance .
10,967
public List < Diagnostic > diagnoseApplication ( String applicationName ) { this . logger . finer ( "Diagnosing application " + applicationName ) ; WebResource path = this . resource . path ( UrlConstants . DEBUG ) . path ( "diagnose-application" ) ; path = path . queryParam ( "application-name" , applicationName ) ; List < Diagnostic > result = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . get ( new GenericType < List < Diagnostic > > ( ) { } ) ; if ( result == null ) this . logger . finer ( "No diagnostic was returned for application " + applicationName ) ; return result ; }
Runs a diagnostic for a given application .
10,968
public void addTargetHandler ( TargetHandler targetItf ) { if ( targetItf != null ) { this . logger . info ( "Target handler '" + targetItf . getTargetId ( ) + "' is now available in Roboconf's DM." ) ; synchronized ( this . targetHandlers ) { this . targetHandlers . add ( targetItf ) ; } listTargets ( this . targetHandlers , this . logger ) ; } }
Adds a new target handler .
10,969
public void removeTargetHandler ( TargetHandler targetItf ) { if ( targetItf == null ) { this . logger . info ( "An invalid target handler is removed." ) ; } else { synchronized ( this . targetHandlers ) { this . targetHandlers . remove ( targetItf ) ; } this . logger . info ( "Target handler '" + targetItf . getTargetId ( ) + "' is not available anymore in Roboconf's DM." ) ; } listTargets ( this . targetHandlers , this . logger ) ; }
Removes a target handler .
10,970
public static void listTargets ( List < TargetHandler > targetHandlers , Logger logger ) { if ( targetHandlers . isEmpty ( ) ) { logger . info ( "No target was found for Roboconf's DM." ) ; } else { StringBuilder sb = new StringBuilder ( "Available target in Roboconf's DM: " ) ; for ( Iterator < TargetHandler > it = targetHandlers . iterator ( ) ; it . hasNext ( ) ; ) { sb . append ( it . next ( ) . getTargetId ( ) ) ; if ( it . hasNext ( ) ) sb . append ( ", " ) ; } sb . append ( "." ) ; logger . info ( sb . toString ( ) ) ; } }
This method lists the available target and logs them .
10,971
public static String capitalize ( String s ) { String result = s ; if ( ! Utils . isEmptyOrWhitespaces ( s ) ) result = Character . toUpperCase ( s . charAt ( 0 ) ) + s . substring ( 1 ) . toLowerCase ( ) ; return result ; }
Capitalizes a string .
10,972
public static String removeFileExtension ( String filename ) { String result = filename ; int index = filename . lastIndexOf ( '.' ) ; if ( index != - 1 ) result = filename . substring ( 0 , index ) ; return result ; }
Removes the extension from a file name .
10,973
public static List < String > filterEmptyValues ( List < String > values ) { List < String > result = new ArrayList < > ( ) ; for ( String s : values ) { if ( ! Utils . isEmptyOrWhitespaces ( s ) ) result . add ( s ) ; } return result ; }
Creates a new list and only keeps values that are not null or made up of white characters .
10,974
public static String format ( Collection < String > items , String separator ) { StringBuilder sb = new StringBuilder ( ) ; for ( Iterator < String > it = items . iterator ( ) ; it . hasNext ( ) ; ) { sb . append ( it . next ( ) ) ; if ( it . hasNext ( ) ) sb . append ( separator ) ; } return sb . toString ( ) ; }
Formats a collection of elements as a string .
10,975
public static void copyStream ( File inputFile , File outputFile ) throws IOException { InputStream is = new FileInputStream ( inputFile ) ; try { copyStream ( is , outputFile ) ; } finally { is . close ( ) ; } }
Copies the content from inputFile into outputFile .
10,976
public static void copyStream ( File inputFile , OutputStream os ) throws IOException { InputStream is = new FileInputStream ( inputFile ) ; try { copyStreamUnsafelyUseWithCaution ( is , os ) ; } finally { is . close ( ) ; } }
Copies the content from inputFile into an output stream .
10,977
public static void appendStringInto ( String s , File outputFile ) throws IOException { OutputStreamWriter fw = null ; try { fw = new OutputStreamWriter ( new FileOutputStream ( outputFile , true ) , StandardCharsets . UTF_8 ) ; fw . append ( s ) ; } finally { Utils . closeQuietly ( fw ) ; } }
Appends a string into a file .
10,978
public static Properties readPropertiesFile ( File file ) throws IOException { Properties result = new Properties ( ) ; InputStream in = null ; try { in = new FileInputStream ( file ) ; result . load ( in ) ; } finally { closeQuietly ( in ) ; } return result ; }
Reads properties from a file .
10,979
public static Properties readPropertiesFileQuietly ( File file , Logger logger ) { Properties result = new Properties ( ) ; try { if ( file != null && file . exists ( ) ) result = readPropertiesFile ( file ) ; } catch ( Exception e ) { logger . severe ( "Properties file " + file + " could not be read." ) ; logException ( logger , e ) ; } return result ; }
Reads properties from a file but does not throw any error in case of problem .
10,980
public static Properties readPropertiesQuietly ( String fileContent , Logger logger ) { Properties result = new Properties ( ) ; try { if ( fileContent != null ) { InputStream in = new ByteArrayInputStream ( fileContent . getBytes ( StandardCharsets . UTF_8 ) ) ; result . load ( in ) ; } } catch ( Exception e ) { logger . severe ( "Properties could not be read from a string." ) ; logException ( logger , e ) ; } return result ; }
Reads properties from a string .
10,981
public static void writePropertiesFile ( Properties properties , File file ) throws IOException { OutputStream out = null ; try { out = new FileOutputStream ( file ) ; properties . store ( out , "" ) ; } finally { closeQuietly ( out ) ; } }
Writes Java properties into a file .
10,982
public static String cleanNameWithAccents ( String name ) { String temp = Normalizer . normalize ( name , Normalizer . Form . NFD ) ; Pattern pattern = Pattern . compile ( "\\p{InCombiningDiacriticalMarks}+" ) ; return pattern . matcher ( temp ) . replaceAll ( "" ) . trim ( ) ; }
Replaces all the accents in a string .
10,983
public static String updateProperties ( String propertiesContent , Map < String , String > keyToNewValue ) { for ( Map . Entry < String , String > entry : keyToNewValue . entrySet ( ) ) { propertiesContent = propertiesContent . replaceFirst ( "(?mi)^\\s*" + entry . getKey ( ) + "\\s*[:=][^\n]*$" , entry . getKey ( ) + " = " + entry . getValue ( ) ) ; } return propertiesContent ; }
Updates string properties .
10,984
public static List < File > listDirectories ( File root ) { List < File > result = new ArrayList < > ( ) ; File [ ] files = root . listFiles ( new DirectoryFileFilter ( ) ) ; if ( files != null ) result . addAll ( Arrays . asList ( files ) ) ; Collections . sort ( result , new FileNameComparator ( ) ) ; return result ; }
Lists directories located under a given file .
10,985
public static String computeFileRelativeLocation ( File rootDirectory , File subFile ) { String rootPath = rootDirectory . getAbsolutePath ( ) ; String subPath = subFile . getAbsolutePath ( ) ; if ( ! subPath . startsWith ( rootPath ) ) throw new IllegalArgumentException ( "The sub-file must be contained in the directory." ) ; if ( rootDirectory . equals ( subFile ) ) throw new IllegalArgumentException ( "The sub-file must be different than the directory." ) ; return subPath . substring ( rootPath . length ( ) + 1 ) . replace ( '\\' , '/' ) ; }
Computes the relative location of a file with respect to a root directory .
10,986
public static void extractZipArchive ( File zipFile , File targetDirectory ) throws IOException { extractZipArchive ( zipFile , targetDirectory , null , null ) ; }
Extracts a ZIP archive in a directory .
10,987
public static boolean isAncestor ( File ancestorCandidate , File file ) { String path = ancestorCandidate . getAbsolutePath ( ) ; if ( ! path . endsWith ( "/" ) ) path += "/" ; return file . getAbsolutePath ( ) . startsWith ( path ) ; }
Determines whether a directory contains a given file .
10,988
public static void deleteFilesRecursively ( File ... files ) throws IOException { if ( files == null ) return ; List < File > filesToDelete = new ArrayList < > ( ) ; filesToDelete . addAll ( Arrays . asList ( files ) ) ; while ( ! filesToDelete . isEmpty ( ) ) { File currentFile = filesToDelete . remove ( 0 ) ; if ( currentFile == null || ! currentFile . exists ( ) ) continue ; File [ ] subFiles = currentFile . listFiles ( ) ; if ( subFiles != null && subFiles . length > 0 ) { filesToDelete . add ( 0 , currentFile ) ; filesToDelete . addAll ( 0 , Arrays . asList ( subFiles ) ) ; } else if ( ! currentFile . delete ( ) ) throw new IOException ( currentFile . getAbsolutePath ( ) + " could not be deleted." ) ; } }
Deletes files recursively .
10,989
public static void deleteFilesRecursivelyAndQuietly ( File ... files ) { try { deleteFilesRecursively ( files ) ; } catch ( IOException e ) { Logger logger = Logger . getLogger ( Utils . class . getName ( ) ) ; logException ( logger , e ) ; } }
Deletes files recursively and remains quiet even if an exception is thrown .
10,990
public static void logException ( Logger logger , Throwable t ) { logException ( logger , Level . FINEST , t ) ; }
Logs an exception with the given logger and the FINEST level .
10,991
public static void closeStatement ( PreparedStatement ps , Logger logger ) { try { if ( ps != null ) ps . close ( ) ; } catch ( SQLException e ) { Utils . logException ( logger , e ) ; } }
Closes a prepared statement .
10,992
public static void closeStatement ( Statement st , Logger logger ) { try { if ( st != null ) st . close ( ) ; } catch ( SQLException e ) { Utils . logException ( logger , e ) ; } }
Closes a statement .
10,993
public static void closeResultSet ( ResultSet resultSet , Logger logger ) { try { if ( resultSet != null ) resultSet . close ( ) ; } catch ( SQLException e ) { Utils . logException ( logger , e ) ; } }
Closes a result set .
10,994
public static void closeConnection ( Connection conn , Logger logger ) { try { if ( conn != null ) conn . close ( ) ; } catch ( SQLException e ) { Utils . logException ( logger , e ) ; } }
Closes a connection to a database .
10,995
public static Map . Entry < String , Integer > findUrlAndPort ( String url ) { Matcher m = Pattern . compile ( ".*(:\\d+).*" ) . matcher ( url ) ; String portAsString = m . find ( ) ? m . group ( 1 ) . substring ( 1 ) : null ; Integer port = portAsString == null ? - 1 : Integer . parseInt ( portAsString ) ; String address = portAsString == null ? url : url . replace ( m . group ( 1 ) , "" ) ; return new AbstractMap . SimpleEntry < > ( address , port ) ; }
Parses a raw URL and extracts the host and port .
10,996
public static String getValue ( Map < String , String > map , String key , String defaultValue ) { return map . containsKey ( key ) ? map . get ( key ) : defaultValue ; }
Returns the value contained in a map of string if it exists using the key .
10,997
public static String findApplicationName ( final File templateDir , final File templateFile ) { final File parentDir = templateFile . getParentFile ( ) ; final String appName ; if ( templateDir . equals ( parentDir ) ) appName = null ; else if ( templateDir . equals ( parentDir . getParentFile ( ) ) ) appName = parentDir . getName ( ) ; else throw new IllegalArgumentException ( "Not a template file: " + templateFile ) ; return appName ; }
Finds an application name from a template file .
10,998
public static void deleteGeneratedFiles ( Application app , File outputDirectory ) { File target = new File ( outputDirectory , app . getName ( ) ) ; Utils . deleteFilesRecursivelyAndQuietly ( target ) ; }
Deletes the generated files for a given application .
10,999
public static Collection < TemplateEntry > findTemplatesForApplication ( String appName , Collection < TemplateEntry > templates ) { final Collection < TemplateEntry > result = new ArrayList < > ( ) ; for ( TemplateEntry te : templates ) { if ( te . getAppName ( ) == null || te . getAppName ( ) . equals ( appName ) ) result . add ( te ) ; } return result ; }
Finds the templates that can apply to a given application .