idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
10,800
static SwiftApi swiftApi ( Map < String , String > targetProperties ) throws TargetException { validate ( targetProperties ) ; return ContextBuilder . newBuilder ( PROVIDER_SWIFT ) . endpoint ( targetProperties . get ( API_URL ) ) . credentials ( identity ( targetProperties ) , targetProperties . get ( PASSWORD ) ) . buildApi ( SwiftApi . class ) ; }
Creates a JCloud context for Swift .
10,801
static void validate ( Map < String , String > targetProperties ) throws TargetException { checkProperty ( API_URL , targetProperties ) ; checkProperty ( IMAGE_NAME , targetProperties ) ; checkProperty ( TENANT_NAME , targetProperties ) ; checkProperty ( FLAVOR_NAME , targetProperties ) ; checkProperty ( SECURITY_GROUP , targetProperties ) ; checkProperty ( KEY_PAIR , targetProperties ) ; checkProperty ( USER , targetProperties ) ; checkProperty ( PASSWORD , targetProperties ) ; }
Validates the basic target properties .
10,802
static void validateAll ( Map < String , String > targetProperties , String appName , String instanceName ) throws TargetException { validate ( targetProperties ) ; Set < String > mountPoints = new HashSet < > ( ) ; Set < String > volumeNames = new HashSet < > ( ) ; for ( String s : findStorageIds ( targetProperties ) ) { String mountPoint = findStorageProperty ( targetProperties , s , VOLUME_MOUNT_POINT_PREFIX ) ; if ( mountPoints . contains ( mountPoint ) ) throw new TargetException ( "Mount point '" + mountPoint + "' is already used by another volume for this VM." ) ; mountPoints . add ( mountPoint ) ; String volumeName = findStorageProperty ( targetProperties , s , VOLUME_NAME_PREFIX ) ; volumeName = expandVolumeName ( volumeName , appName , instanceName ) ; if ( volumeNames . contains ( volumeName ) ) throw new TargetException ( "Volume name '" + volumeName + "' is already used by another volume for this VM." ) ; volumeNames . add ( volumeName ) ; String volumesize = findStorageProperty ( targetProperties , s , VOLUME_SIZE_GB_PREFIX ) ; try { Integer . valueOf ( volumesize ) ; } catch ( NumberFormatException e ) { throw new TargetException ( "The volume size must be a valid integer." , e ) ; } } }
Validates the target properties including storage ones .
10,803
static String findStorageProperty ( Map < String , String > targetProperties , String storageId , String propertyPrefix ) { String property = propertyPrefix + storageId ; String value = targetProperties . get ( property ) ; return Utils . isEmptyOrWhitespaces ( value ) ? DEFAULTS . get ( propertyPrefix ) : value . trim ( ) ; }
Finds a storage property for a given storage ID .
10,804
static String expandVolumeName ( String nameTemplate , String appName , String instanceName ) { String name = nameTemplate . replace ( TPL_VOLUME_NAME , instanceName ) ; name = name . replace ( TPL_VOLUME_APP , appName ) ; name = name . replaceAll ( "[\\W_-]" , "-" ) ; return name ; }
Updates a volume name by replacing template variables .
10,805
public BlockProperty findPropertyBlockByName ( String propertyName ) { BlockProperty result = null ; for ( AbstractBlock region : this . innerBlocks ) { if ( region . getInstructionType ( ) == PROPERTY && propertyName . equals ( ( ( BlockProperty ) region ) . getName ( ) ) ) { result = ( BlockProperty ) region ; break ; } } return result ; }
Finds a property by its name among the ones this instance owns .
10,806
public List < BlockProperty > findPropertiesBlockByName ( String propertyName ) { List < BlockProperty > result = new ArrayList < > ( ) ; for ( AbstractBlock region : this . innerBlocks ) { if ( region . getInstructionType ( ) == PROPERTY && propertyName . equals ( ( ( BlockProperty ) region ) . getName ( ) ) ) { result . add ( ( BlockProperty ) region ) ; } } return result ; }
Finds properties by name among the ones this instance owns .
10,807
public static Map . Entry < String , String > decodeIconUrl ( String path ) { if ( path . startsWith ( "/" ) ) path = path . substring ( 1 ) ; String name = null , version = null ; String [ ] parts = path . split ( "/" ) ; switch ( parts . length ) { case 2 : name = parts [ 0 ] ; break ; case 3 : name = parts [ 0 ] ; version = parts [ 1 ] ; break ; default : break ; } return new AbstractMap . SimpleEntry < > ( name , version ) ; }
Decodes an URL path to extract a name and a potential version .
10,808
public static String findIconUrl ( AbstractApplication app ) { StringBuilder sb = new StringBuilder ( ) ; File iconFile = findIcon ( app ) ; if ( iconFile != null ) { sb . append ( "/" ) ; sb . append ( app . getName ( ) ) ; if ( app instanceof ApplicationTemplate ) { sb . append ( "/" ) ; sb . append ( ( ( ApplicationTemplate ) app ) . getVersion ( ) ) ; } sb . append ( "/" ) ; sb . append ( iconFile . getName ( ) ) ; } return sb . toString ( ) ; }
Finds the URL to access the icon of an application or templates .
10,809
public static String writeConfigurationFile ( FileDefinition relationsFile , boolean writeComments , String lineSeparator ) { return new FileDefinitionSerializer ( lineSeparator ) . write ( relationsFile , writeComments ) ; }
Writes a model into a string .
10,810
public static void saveRelationsFile ( FileDefinition relationsFile , boolean writeComments , String lineSeparator ) throws IOException { if ( relationsFile . getEditedFile ( ) == null ) throw new IOException ( "Save operation could not be performed. The model was not loaded from a local file." ) ; saveRelationsFileInto ( relationsFile . getEditedFile ( ) , relationsFile , writeComments , lineSeparator ) ; }
Saves the model into the original file .
10,811
public static void saveRelationsFileInto ( File targetFile , FileDefinition relationsFile , boolean writeComments , String lineSeparator ) throws IOException { String s = writeConfigurationFile ( relationsFile , writeComments , lineSeparator ) ; Utils . copyStream ( new ByteArrayInputStream ( s . getBytes ( StandardCharsets . UTF_8 ) ) , targetFile ) ; }
Saves the model into another file .
10,812
public static String labelFromCamelCase ( String camel ) { StringBuilder label = new StringBuilder ( ) ; for ( int i = 0 ; i < camel . length ( ) ; i ++ ) { char c = camel . charAt ( i ) ; if ( Character . isDigit ( c ) ) { if ( i > 0 && Character . isAlphabetic ( camel . charAt ( i - 1 ) ) ) label . append ( " " ) ; } if ( c == '_' ) { label . append ( " " ) ; } else if ( Character . isUpperCase ( c ) ) { label . append ( ' ' ) ; label . append ( Character . toLowerCase ( c ) ) ; } else { label . append ( c ) ; } } return label . toString ( ) ; }
Converts a camelcase variable name to a human readable text .
10,813
AbstractCommandExecution findExecutor ( AbstractCommandInstruction instr ) { AbstractCommandExecution result = null ; if ( RenameCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new RenameCommandExecution ( ( RenameCommandInstruction ) instr ) ; else if ( ReplicateCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new ReplicateCommandExecution ( ( ReplicateCommandInstruction ) instr , this . manager ) ; else if ( AssociateTargetCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new AssociateTargetCommandExecution ( ( AssociateTargetCommandInstruction ) instr , this . manager ) ; else if ( BulkCommandInstructions . class . equals ( instr . getClass ( ) ) ) result = new BulkCommandExecution ( ( BulkCommandInstructions ) instr , this . manager ) ; else if ( ChangeStateCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new ChangeStateCommandExecution ( ( ChangeStateCommandInstruction ) instr , this . manager ) ; else if ( CreateInstanceCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new CreateInstanceCommandExecution ( ( CreateInstanceCommandInstruction ) instr , this . manager ) ; else if ( EmailCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new EmailCommandExecution ( ( EmailCommandInstruction ) instr , this . manager ) ; else if ( WriteCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new WriteCommandExecution ( ( WriteCommandInstruction ) instr ) ; else if ( AppendCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new AppendCommandExecution ( ( AppendCommandInstruction ) instr ) ; else if ( ExecuteCommandInstruction . class . equals ( instr . getClass ( ) ) ) result = new ExecuteCommandExecution ( ( ExecuteCommandInstruction ) instr , this . manager ) ; return result ; }
Finds the right executor for an instruction .
10,814
private String convertPropertyFileLineToJSon ( String line , String json ) { if ( line == null ) return json ; String l = line . trim ( ) ; if ( l . length ( ) == 0 || l . startsWith ( "//" ) ) return json ; boolean inString = l . startsWith ( "\"" ) ; String english ; String rest ; if ( inString ) { boolean esc = false ; int i = 1 ; for ( ; i < l . length ( ) ; i ++ ) { if ( esc ) esc = false ; else if ( l . charAt ( i ) == '\\' ) esc = true ; else if ( l . charAt ( i ) == '\"' ) { i ++ ; break ; } } english = l . substring ( 1 , i - 1 ) . replace ( "\\\"" , "\"" ) ; rest = l . substring ( i ) . trim ( ) ; } else { int pos = l . indexOf ( '=' ) ; if ( pos < 0 ) { LOGGER . severe ( "Illegal entry in language file: \"" + line + "\"" ) ; return json ; } else { english = l . substring ( 0 , pos ) . trim ( ) ; rest = l . substring ( pos ) ; } } if ( ! rest . startsWith ( "=" ) ) { LOGGER . severe ( "Illegal entry in language file: \"" + line + "\"" ) ; } else { String translation ; rest = rest . substring ( 1 ) . trim ( ) ; if ( rest . startsWith ( "\"" ) ) { int pos = rest . lastIndexOf ( "\"" ) ; if ( pos > 1 ) translation = rest . substring ( 1 , pos ) . replace ( "\\\"" , "\"" ) . trim ( ) ; else translation = rest . replace ( "\\\"" , "\"" ) ; } else translation = rest ; this . translations . put ( english , translation ) ; json += ", \"" + english + "\"" + "," + "\"" + translation + "\"" ; } return json ; }
Note this method has a side effect - it also fills the HashMap of translations .
10,815
public void targetAppears ( TargetHandler targetItf ) { this . defaultTargetHandlerResolver . addTargetHandler ( targetItf ) ; if ( this . timer != null ) restoreInstancesFrom ( targetItf ) ; }
This method is invoked by iPojo every time a new target handler appears .
10,816
public void setTargetResolver ( ITargetHandlerResolver targetHandlerResolver ) { if ( targetHandlerResolver == null ) { this . targetConfigurator . setTargetHandlerResolver ( this . defaultTargetHandlerResolver ) ; this . instancesMngr . setTargetHandlerResolver ( this . defaultTargetHandlerResolver ) ; } else { this . targetConfigurator . setTargetHandlerResolver ( targetHandlerResolver ) ; this . instancesMngr . setTargetHandlerResolver ( targetHandlerResolver ) ; } }
Sets the target resolver .
10,817
void restoreAllInstances ( ) { this . logger . fine ( "Restoring all the instance states from the current target handlers." ) ; for ( ManagedApplication ma : this . applicationMngr . getManagedApplications ( ) ) { List < TargetHandler > snapshot = this . defaultTargetHandlerResolver . getTargetHandlersSnapshot ( ) ; for ( TargetHandler targetHandler : snapshot ) instancesMngr ( ) . restoreInstanceStates ( ma , targetHandler ) ; } }
Restores the states of all the instances from the current target handlers .
10,818
void restoreInstancesFrom ( TargetHandler targetHandler ) { this . logger . fine ( "Restoring the instance states with the '" + targetHandler . getTargetId ( ) + "' target handler." ) ; for ( ManagedApplication ma : this . applicationMngr . getManagedApplications ( ) ) instancesMngr ( ) . restoreInstanceStates ( ma , targetHandler ) ; }
Restores the states of all the instances from a given target handler .
10,819
public boolean addMessagingClientFactory ( IMessagingClientFactory factory ) { final String type = factory . getType ( ) ; this . logger . fine ( "Adding messaging client factory: " + type ) ; final boolean result = this . factories . putIfAbsent ( type , factory ) == null ; if ( result ) notifyListeners ( factory , true ) ; return result ; }
Adds a messaging client factory to this registry unless a similar one was already registered .
10,820
public boolean removeMessagingClientFactory ( IMessagingClientFactory factory ) { final String type = factory . getType ( ) ; this . logger . fine ( "Removing messaging client factory: " + type ) ; final boolean result = this . factories . remove ( type , factory ) ; if ( result ) notifyListeners ( factory , false ) ; return result ; }
Removes a messaging client factory from this registry .
10,821
public static Object getValueToRender ( FacesContext context , UIComponent component ) { if ( component instanceof ValueHolder ) { if ( component instanceof EditableValueHolder ) { EditableValueHolder input = ( EditableValueHolder ) component ; Object submittedValue = input . getSubmittedValue ( ) ; ConfigContainer config = RequestContext . getCurrentInstance ( ) . getApplicationContext ( ) . getConfig ( ) ; if ( config . isInterpretEmptyStringAsNull ( ) && submittedValue == null && context . isValidationFailed ( ) && ! input . isValid ( ) ) { return null ; } else if ( submittedValue != null ) { return submittedValue ; } } ValueHolder valueHolder = ( ValueHolder ) component ; Object value = valueHolder . getValue ( ) ; return value ; } return null ; }
This method has been copied from the PrimeFaces 5 project .
10,822
public void acknowledgeHeartBeat ( Instance scopedInstance ) { String count = scopedInstance . data . get ( MISSED_HEARTBEATS ) ; if ( count != null && Integer . parseInt ( count ) > THRESHOLD ) this . logger . info ( "Agent " + InstanceHelpers . computeInstancePath ( scopedInstance ) + " is alive and reachable again." ) ; if ( scopedInstance . getStatus ( ) != InstanceStatus . DEPLOYED_STARTED || ! scopedInstance . data . containsKey ( Instance . RUNNING_FROM ) ) scopedInstance . data . put ( Instance . RUNNING_FROM , String . valueOf ( new Date ( ) . getTime ( ) ) ) ; scopedInstance . setStatus ( InstanceStatus . DEPLOYED_STARTED ) ; scopedInstance . data . remove ( MISSED_HEARTBEATS ) ; }
Acknowledges a heart beat .
10,823
public void checkStates ( INotificationMngr notificationMngr ) { Collection < Instance > scopedInstances = InstanceHelpers . findAllScopedInstances ( this . application ) ; for ( Instance scopedInstance : scopedInstances ) { if ( scopedInstance . getStatus ( ) == InstanceStatus . NOT_DEPLOYED || scopedInstance . getStatus ( ) == InstanceStatus . DEPLOYING || scopedInstance . getStatus ( ) == InstanceStatus . UNDEPLOYING ) { scopedInstance . data . remove ( MISSED_HEARTBEATS ) ; continue ; } String countAs = scopedInstance . data . get ( MISSED_HEARTBEATS ) ; int count = countAs == null ? 0 : Integer . parseInt ( countAs ) ; if ( ++ count > THRESHOLD ) { scopedInstance . setStatus ( InstanceStatus . PROBLEM ) ; notificationMngr . instance ( scopedInstance , this . application , EventType . CHANGED ) ; this . logger . severe ( "Agent " + InstanceHelpers . computeInstancePath ( scopedInstance ) + " has not sent heart beats for quite a long time. Status changed to PROBLEM." ) ; } scopedInstance . data . put ( MISSED_HEARTBEATS , String . valueOf ( count ) ) ; } }
Check the scoped instances states with respect to missed heart beats .
10,824
public static void markScopedInstanceAsNotDeployed ( Instance scopedInstance , ManagedApplication ma , INotificationMngr notificationMngr , IInstancesMngr instanceMngr ) { scopedInstance . data . remove ( Instance . IP_ADDRESS ) ; scopedInstance . data . remove ( Instance . MACHINE_ID ) ; scopedInstance . data . remove ( Instance . TARGET_ACQUIRED ) ; scopedInstance . data . remove ( Instance . RUNNING_FROM ) ; scopedInstance . data . remove ( Instance . READY_FOR_CFG_MARKER ) ; List < Instance > instancesToDelete = new ArrayList < > ( ) ; for ( Instance i : InstanceHelpers . buildHierarchicalList ( scopedInstance ) ) { InstanceStatus oldstatus = i . getStatus ( ) ; i . setStatus ( InstanceStatus . NOT_DEPLOYED ) ; if ( oldstatus != InstanceStatus . NOT_DEPLOYED ) notificationMngr . instance ( i , ma . getApplication ( ) , EventType . CHANGED ) ; i . getImports ( ) . clear ( ) ; if ( i . data . containsKey ( Instance . DELETE_WHEN_NOT_DEPLOYED ) ) instancesToDelete . add ( i ) ; } Collections . reverse ( instancesToDelete ) ; for ( Instance i : instancesToDelete ) { try { instanceMngr . removeInstance ( ma , i , true ) ; } catch ( Exception e ) { Logger logger = Logger . getLogger ( DmUtils . class . getName ( ) ) ; logger . severe ( "An error occurred while deleting an instance marked with DELETE_WHEN_NOT_DEPLOYED. Instance = " + InstanceHelpers . computeInstancePath ( i ) + " App = " + ma . getName ( ) ) ; Utils . logException ( logger , e ) ; } } }
Updates a scoped instance and its children to be marked as not deployed .
10,825
private void dealWithMainComponent ( ) { this . typeToLocation . put ( this . component , new Point2D . Double ( this . hMargin , this . currentHeigth ) ) ; int width = H_PADDING + GraphUtils . computeShapeWidth ( this . component ) ; this . maxRowWidth = Math . max ( this . maxRowWidth , width ) ; this . aloneOnRow . add ( this . component ) ; }
Finds the position for the main component .
10,826
private void dealWithOthers ( Collection < AbstractType > others ) { int col = 1 ; this . currentWidth = this . hMargin ; for ( AbstractType t : others ) { if ( col > this . maxPerLine ) { col = 1 ; this . currentHeigth += V_PADDING + GraphUtils . SHAPE_HEIGHT ; this . currentWidth = this . hMargin ; } this . typeToLocation . put ( t , new Point2D . Double ( this . currentWidth , this . currentHeigth ) ) ; this . currentWidth += H_PADDING + GraphUtils . computeShapeWidth ( t ) ; col ++ ; this . maxRowWidth = Math . max ( this . maxRowWidth , this . currentWidth ) ; } if ( others . size ( ) == 1 ) this . aloneOnRow . add ( others . iterator ( ) . next ( ) ) ; }
Finds the position of other components .
10,827
public static URI buildNewURI ( URI referenceUri , String uriSuffix ) throws URISyntaxException { if ( uriSuffix == null ) throw new IllegalArgumentException ( "The URI suffix cannot be null." ) ; uriSuffix = uriSuffix . replaceAll ( "\\\\" , "/" ) ; URI importUri = null ; try { importUri = urlToUri ( new URL ( uriSuffix ) ) ; } catch ( Exception e ) { try { if ( ! referenceUri . toString ( ) . endsWith ( "/" ) && ! uriSuffix . startsWith ( "/" ) ) referenceUri = new URI ( referenceUri . toString ( ) + "/" ) ; importUri = referenceUri . resolve ( new URI ( null , uriSuffix , null ) ) ; } catch ( Exception e2 ) { String msg = "An URI could not be built from the URI " + referenceUri . toString ( ) + " and the suffix " + uriSuffix + "." ; throw new URISyntaxException ( msg , e2 . getMessage ( ) ) ; } } return importUri . normalize ( ) ; }
Builds an URI from an URI and a suffix .
10,828
public static int executeCommand ( final Logger logger , final String [ ] command , final File workingDir , final Map < String , String > environmentVars , final String applicationName , final String scopedInstancePath ) throws IOException , InterruptedException { ExecutionResult result = executeCommandWithResult ( logger , command , workingDir , environmentVars , applicationName , scopedInstancePath ) ; if ( ! Utils . isEmptyOrWhitespaces ( result . getNormalOutput ( ) ) ) logger . fine ( result . getNormalOutput ( ) ) ; if ( ! Utils . isEmptyOrWhitespaces ( result . getErrorOutput ( ) ) ) logger . warning ( result . getErrorOutput ( ) ) ; return result . getExitValue ( ) ; }
Executes a command on the VM and logs the output .
10,829
public static int executeCommand ( final Logger logger , final List < String > command , final File workingDir , final Map < String , String > environmentVars , final String applicationName , final String scopedInstanceName ) throws IOException , InterruptedException { return executeCommand ( logger , command . toArray ( new String [ 0 ] ) , workingDir , environmentVars , applicationName , scopedInstanceName ) ; }
Executes a command on the VM and prints on the console its output .
10,830
public static List < DockerCommand > dockerfileToCommandList ( File dockerfile ) throws IOException { List < DockerCommand > result = new ArrayList < > ( ) ; FileInputStream in = new FileInputStream ( dockerfile ) ; Logger logger = Logger . getLogger ( DockerfileParser . class . getName ( ) ) ; BufferedReader br = null ; try { br = new BufferedReader ( new InputStreamReader ( in , StandardCharsets . UTF_8 ) ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { DockerCommand cmd = DockerCommand . guess ( line ) ; if ( cmd != null ) result . add ( cmd ) ; else logger . fine ( "Ignoring unsupported Docker instruction: " + line ) ; } } finally { Utils . closeQuietly ( br ) ; Utils . closeQuietly ( in ) ; } return result ; }
Parses a dockerfile to a list of commands .
10,831
public void enableCors ( boolean enableCors ) { if ( enableCors ) getProperties ( ) . put ( ResourceConfig . PROPERTY_CONTAINER_RESPONSE_FILTERS , ResponseCorsFilter . class . getName ( ) ) ; else getProperties ( ) . remove ( ResourceConfig . PROPERTY_CONTAINER_RESPONSE_FILTERS ) ; }
Enables or disables CORS .
10,832
public static String getVMIP ( String hostIpPort , String id ) throws TargetException { if ( ! hostIpPort . endsWith ( "/compute" ) && id . startsWith ( "urn:uuid:" ) ) id = id . substring ( 9 ) ; String vmIp = null ; URL url = null ; try { CookieHandler . setDefault ( new CookieManager ( null , CookiePolicy . ACCEPT_ALL ) ) ; url = new URL ( "http://" + hostIpPort + "/" + id ) ; } catch ( MalformedURLException e ) { throw new TargetException ( e ) ; } HttpURLConnection httpURLConnection = null ; DataInputStream in = null ; try { httpURLConnection = ( HttpURLConnection ) url . openConnection ( ) ; httpURLConnection . setRequestMethod ( "GET" ) ; httpURLConnection . setRequestProperty ( "Accept" , "application/json" ) ; in = new DataInputStream ( httpURLConnection . getInputStream ( ) ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Utils . copyStreamSafely ( in , out ) ; ObjectMapper objectMapper = new ObjectMapper ( ) ; JsonResponse rsp = objectMapper . readValue ( out . toString ( "UTF-8" ) , JsonResponse . class ) ; vmIp = rsp . getHostsystemname ( ) ; if ( Utils . isEmptyOrWhitespaces ( vmIp ) ) vmIp = rsp . getHostname ( ) ; if ( Utils . isEmptyOrWhitespaces ( vmIp ) && rsp . getAttributes ( ) != null ) vmIp = rsp . getAttributes ( ) . getHostname ( ) ; } catch ( IOException e ) { throw new TargetException ( e ) ; } finally { Utils . closeQuietly ( in ) ; if ( httpURLConnection != null ) { httpURLConnection . disconnect ( ) ; } } return vmIp ; }
Retrieves VM IP .
10,833
public static boolean isVMRunning ( String hostIpPort , String id ) throws TargetException { boolean result = false ; String ip = OcciVMUtils . getVMIP ( hostIpPort , id ) ; try { InetAddress inet = InetAddress . getByName ( ip ) ; result = inet . isReachable ( 5000 ) ; } catch ( Exception e ) { result = false ; final Logger logger = Logger . getLogger ( OcciVMUtils . class . getName ( ) ) ; logger . info ( e . getMessage ( ) ) ; } return result ; }
Checks if VM is running .
10,834
public String createTarget ( String targetContent ) throws IOException { TargetValidator tv = new TargetValidator ( targetContent ) ; tv . validate ( ) ; if ( RoboconfErrorHelpers . containsCriticalErrors ( tv . getErrors ( ) ) ) throw new IOException ( "There are errors in the target definition." ) ; String targetId = tv . getProperties ( ) . getProperty ( Constants . TARGET_PROPERTY_ID ) ; String creator = tv . getProperties ( ) . getProperty ( CREATED_BY ) ; if ( this . targetIds . putIfAbsent ( targetId , Boolean . TRUE ) != null ) { if ( creator == null ) throw new IOException ( "ID " + targetId + " is already used." ) ; File createdByFile = new File ( findTargetDirectory ( targetId ) , CREATED_BY ) ; String storedCreator = null ; if ( createdByFile . exists ( ) ) storedCreator = Utils . readFileContent ( createdByFile ) ; if ( ! Objects . equals ( creator , storedCreator ) ) throw new IOException ( "ID " + targetId + " is already used." ) ; } targetContent = targetContent . replaceAll ( Constants . TARGET_PROPERTY_ID + "\\s*(:|=)[^\n]*(\n|$)" , "" ) ; targetContent = targetContent . replaceAll ( "\n\n" + Pattern . quote ( CREATED_BY ) + "\\s*(:|=)[^\n]*(\n|$)" , "" ) ; File targetFile = new File ( findTargetDirectory ( targetId ) , Constants . TARGET_PROPERTIES_FILE_NAME ) ; Utils . createDirectory ( targetFile . getParentFile ( ) ) ; Utils . writeStringInto ( targetContent , targetFile ) ; if ( creator != null ) { File createdByFile = new File ( findTargetDirectory ( targetId ) , CREATED_BY ) ; Utils . writeStringInto ( creator , createdByFile ) ; } return targetId ; }
CRUD operations on targets
10,835
public Map < String , byte [ ] > findScriptResourcesForAgent ( String targetId ) throws IOException { Map < String , byte [ ] > result = new HashMap < > ( 0 ) ; File targetDir = new File ( findTargetDirectory ( targetId ) , Constants . PROJECT_SUB_DIR_SCRIPTS ) ; if ( targetDir . isDirectory ( ) ) { List < String > exclusionPatterns = Arrays . asList ( "(?i).*" + Pattern . quote ( Constants . LOCAL_RESOURCE_PREFIX ) + ".*" ) ; result . putAll ( Utils . storeDirectoryResourcesAsBytes ( targetDir , exclusionPatterns ) ) ; } return result ; }
Finding script resources
10,836
public List < TargetWrapperDescriptor > listPossibleTargets ( AbstractApplication app ) { String key = new InstanceContext ( app ) . toString ( ) ; String tplKey = null ; if ( app instanceof Application ) tplKey = new InstanceContext ( ( ( Application ) app ) . getTemplate ( ) ) . toString ( ) ; List < File > targetDirectories = new ArrayList < > ( ) ; File dir = new File ( this . configurationMngr . getWorkingDirectory ( ) , ConfigurationUtils . TARGETS ) ; for ( File f : Utils . listDirectories ( dir ) ) { File hintsFile = new File ( f , TARGETS_HINTS_FILE ) ; if ( ! hintsFile . exists ( ) ) { targetDirectories . add ( f ) ; continue ; } Properties props = Utils . readPropertiesFileQuietly ( hintsFile , this . logger ) ; if ( props . containsKey ( key ) ) targetDirectories . add ( f ) ; else if ( tplKey != null && props . containsKey ( tplKey ) ) targetDirectories . add ( f ) ; } return buildList ( targetDirectories , app ) ; }
In relation with hints
10,837
public TargetProperties lockAndGetTarget ( Application app , Instance scopedInstance ) throws IOException { String instancePath = InstanceHelpers . computeInstancePath ( scopedInstance ) ; String targetId = findTargetId ( app , instancePath ) ; if ( targetId == null ) throw new IOException ( "No target was found for " + app + " :: " + instancePath ) ; InstanceContext mappingKey = new InstanceContext ( app , instancePath ) ; synchronized ( LOCK ) { saveUsage ( mappingKey , targetId , true ) ; } this . logger . fine ( "Target " + targetId + "'s lock was acquired for " + instancePath ) ; TargetProperties result = findTargetProperties ( app , instancePath ) ; Map < String , String > newTargetProperties = TargetHelpers . expandProperties ( scopedInstance , result . asMap ( ) ) ; result . asMap ( ) . clear ( ) ; result . asMap ( ) . putAll ( newTargetProperties ) ; return result ; }
Atomic operations ...
10,838
public static void verify ( CommandExecutionContext executionContext , Component component ) throws CommandException { if ( executionContext != null && Constants . TARGET_INSTALLER . equalsIgnoreCase ( component . getInstallerName ( ) ) && executionContext . getMaxVm ( ) > 0 && executionContext . getMaxVm ( ) <= executionContext . getGlobalVmNumber ( ) . get ( ) && executionContext . isStrictMaxVm ( ) ) throw new CommandException ( "The maximum number of VM created by the autonomic has been reached." ) ; }
Verifies a new VM model can be created according to a given context .
10,839
public static void update ( CommandExecutionContext executionContext , Instance createdInstance ) { if ( executionContext != null ) { createdInstance . data . put ( executionContext . getNewVmMarkerKey ( ) , executionContext . getNewVmMarkerValue ( ) ) ; executionContext . getGlobalVmNumber ( ) . incrementAndGet ( ) ; executionContext . getAppVmNumber ( ) . incrementAndGet ( ) ; } }
Updates an instance with context information .
10,840
public static List < ModelError > validateComponentRecipes ( File applicationFilesDirectory , Component component ) { List < ModelError > result ; if ( "puppet" . equalsIgnoreCase ( component . getInstallerName ( ) ) ) result = validatePuppetComponent ( applicationFilesDirectory , component ) ; else if ( "script" . equalsIgnoreCase ( component . getInstallerName ( ) ) ) result = validateScriptComponent ( applicationFilesDirectory , component ) ; else result = Collections . emptyList ( ) ; return result ; }
Validates the recipes of a component .
10,841
private static void checkPuppetFile ( File pp , boolean withUpdateParams , Component component , Collection < ModelError > errors ) throws IOException { String [ ] cmd = { "puppet" , "parser" , "validate" , pp . getAbsolutePath ( ) } ; Logger logger = Logger . getLogger ( RecipesValidator . class . getName ( ) ) ; try { int execCode = ProgramUtils . executeCommand ( logger , cmd , null , null , null , null ) ; if ( execCode != 0 ) errors . add ( new ModelError ( ErrorCode . REC_PUPPET_SYNTAX_ERROR , component , component ( component ) , file ( pp ) ) ) ; } catch ( Exception e ) { logger . info ( "Puppet parser is not available on the machine." ) ; } Pattern pattern = Pattern . compile ( "class [^(]+\\(([^)]+)\\)" , Pattern . CASE_INSENSITIVE | Pattern . MULTILINE | Pattern . DOTALL ) ; String content = Utils . readFileContent ( pp ) ; Matcher m = pattern . matcher ( content ) ; Set < String > params = new HashSet < > ( ) ; if ( ! m . find ( ) ) return ; for ( String s : m . group ( 1 ) . split ( "," ) ) { Entry < String , String > entry = VariableHelpers . parseExportedVariable ( s . trim ( ) ) ; params . add ( entry . getKey ( ) ) ; } if ( withUpdateParams ) { if ( ! params . remove ( "$importDiff" ) ) errors . add ( new ModelError ( ErrorCode . REC_PUPPET_MISSING_PARAM_IMPORT_DIFF , component , component ( component ) , file ( pp ) ) ) ; } params . remove ( "$importDiff" ) ; if ( ! params . remove ( "$runningState" ) ) errors . add ( new ModelError ( ErrorCode . REC_PUPPET_MISSING_PARAM_RUNNING_STATE , component , component ( component ) , file ( pp ) ) ) ; Instance fake = new Instance ( "fake" ) . component ( component ) ; for ( String facetOrComponentName : VariableHelpers . findPrefixesForImportedVariables ( fake ) ) { if ( ! params . remove ( "$" + facetOrComponentName . toLowerCase ( ) ) ) { ErrorDetails [ ] details = new ErrorDetails [ ] { name ( component . getName ( ) ) , file ( pp ) , expected ( facetOrComponentName . toLowerCase ( ) ) } ; errors . add ( new ModelError ( ErrorCode . REC_PUPPET_MISSING_PARAM_FROM_IMPORT , component , details ) ) ; } } }
Reads a Puppet script and validates it .
10,842
public static String findManifestProperty ( String propertyName ) { String result = null ; InputStream is = null ; try { is = ManifestUtils . class . getResourceAsStream ( "/META-INF/MANIFEST.MF" ) ; Properties props = new Properties ( ) ; props . load ( is ) ; result = findManifestProperty ( props , propertyName ) ; } catch ( IOException e ) { Logger logger = Logger . getLogger ( ManifestUtils . class . getName ( ) ) ; logger . warning ( "Could not read the bundle manifest. " + e . getMessage ( ) ) ; } finally { Utils . closeQuietly ( is ) ; } return result ; }
Finds a property in the MANIFEST file .
10,843
public static String findManifestProperty ( Properties props , String propertyName ) { String result = null ; for ( Map . Entry < Object , Object > entry : props . entrySet ( ) ) { if ( propertyName . equalsIgnoreCase ( String . valueOf ( entry . getKey ( ) ) ) ) { result = String . valueOf ( entry . getValue ( ) ) ; break ; } } return result ; }
Finds a property in the MANIFEST properties .
10,844
public static ErrorDetails applicationTpl ( String tplName , String tplVersion ) { return new ErrorDetails ( tplName + " (" + tplVersion + ")" , ErrorDetailsKind . APPLICATION_TEMPLATE ) ; }
Details for an application .
10,845
public static ErrorDetails exception ( Throwable t ) { return new ErrorDetails ( Utils . writeExceptionButDoNotUseItForLogging ( t ) , ErrorDetailsKind . EXCEPTION ) ; }
Details for an exception .
10,846
public static ErrorDetails exceptionName ( Throwable t ) { return new ErrorDetails ( t . getClass ( ) . getName ( ) , ErrorDetailsKind . EXCEPTION_NAME ) ; }
Details for an exception name .
10,847
static AzureProperties buildProperties ( Map < String , String > targetProperties ) throws TargetException { String [ ] properties = { AzureConstants . AZURE_SUBSCRIPTION_ID , AzureConstants . AZURE_KEY_STORE_FILE , AzureConstants . AZURE_KEY_STORE_PASSWORD , AzureConstants . AZURE_CREATE_CLOUD_SERVICE_TEMPLATE , AzureConstants . AZURE_CREATE_DEPLOYMENT_TEMPLATE , AzureConstants . AZURE_LOCATION , AzureConstants . AZURE_VM_SIZE , AzureConstants . AZURE_VM_TEMPLATE } ; for ( String property : properties ) { if ( Utils . isEmptyOrWhitespaces ( targetProperties . get ( property ) ) ) throw new TargetException ( "The value for " + property + " cannot be null or empty." ) ; } AzureProperties azureProperties = new AzureProperties ( ) ; String s = targetProperties . get ( AzureConstants . AZURE_SUBSCRIPTION_ID ) ; azureProperties . setSubscriptionId ( s . trim ( ) ) ; s = targetProperties . get ( AzureConstants . AZURE_KEY_STORE_FILE ) ; azureProperties . setKeyStoreFile ( s . trim ( ) ) ; s = targetProperties . get ( AzureConstants . AZURE_KEY_STORE_PASSWORD ) ; azureProperties . setKeyStoreFile ( s . trim ( ) ) ; s = targetProperties . get ( AzureConstants . AZURE_CREATE_CLOUD_SERVICE_TEMPLATE ) ; azureProperties . setKeyStoreFile ( s . trim ( ) ) ; s = targetProperties . get ( AzureConstants . AZURE_CREATE_DEPLOYMENT_TEMPLATE ) ; azureProperties . setKeyStoreFile ( s . trim ( ) ) ; s = targetProperties . get ( AzureConstants . AZURE_LOCATION ) ; azureProperties . setKeyStoreFile ( s . trim ( ) ) ; s = targetProperties . get ( AzureConstants . AZURE_VM_SIZE ) ; azureProperties . setKeyStoreFile ( s . trim ( ) ) ; s = targetProperties . get ( AzureConstants . AZURE_VM_TEMPLATE ) ; azureProperties . setKeyStoreFile ( s . trim ( ) ) ; return azureProperties ; }
Validates the received properties and builds a Java bean from them .
10,848
public static ApplicationTemplateDescriptor load ( File f ) throws IOException { String fileContent = Utils . readFileContent ( f ) ; Logger logger = Logger . getLogger ( ApplicationTemplateDescriptor . class . getName ( ) ) ; Properties properties = Utils . readPropertiesQuietly ( fileContent , logger ) ; if ( properties . get ( "fail.read" ) != null ) throw new IOException ( "This is for test purpose..." ) ; ApplicationTemplateDescriptor result = load ( properties ) ; int lineNumber = 1 ; for ( String line : fileContent . split ( "\n" ) ) { for ( String property : ALL_PROPERTIES ) { if ( line . trim ( ) . matches ( "(" + LEGACY_PREFIX + ")?" + property + "\\s*[:=].*" ) ) { result . propertyToLine . put ( property , lineNumber ) ; break ; } } lineNumber ++ ; } return result ; }
Loads an application template s descriptor .
10,849
public static void save ( File f , ApplicationTemplateDescriptor descriptor ) throws IOException { Properties properties = new Properties ( ) ; if ( descriptor . name != null ) properties . setProperty ( APPLICATION_NAME , descriptor . name ) ; if ( descriptor . version != null ) properties . setProperty ( APPLICATION_VERSION , descriptor . version ) ; if ( descriptor . dslId != null ) properties . setProperty ( APPLICATION_DSL_ID , descriptor . dslId ) ; if ( descriptor . description != null ) properties . setProperty ( APPLICATION_DESCRIPTION , descriptor . description ) ; if ( descriptor . graphEntryPoint != null ) properties . setProperty ( APPLICATION_GRAPH_EP , descriptor . graphEntryPoint ) ; if ( descriptor . instanceEntryPoint != null ) properties . setProperty ( APPLICATION_INSTANCES_EP , descriptor . instanceEntryPoint ) ; if ( descriptor . externalExportsPrefix != null ) properties . setProperty ( APPLICATION_EXTERNAL_EXPORTS_PREFIX , descriptor . externalExportsPrefix ) ; StringBuilder sb = new StringBuilder ( ) ; for ( Iterator < Map . Entry < String , String > > it = descriptor . externalExports . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < String , String > entry = it . next ( ) ; sb . append ( entry . getKey ( ) ) ; sb . append ( " " ) ; sb . append ( APPLICATION_EXTERNAL_EXPORTS_AS ) ; sb . append ( " " ) ; sb . append ( entry . getValue ( ) ) ; if ( it . hasNext ( ) ) sb . append ( ", " ) ; } if ( sb . length ( ) > 0 ) properties . setProperty ( APPLICATION_EXTERNAL_EXPORTS , sb . toString ( ) ) ; properties . setProperty ( APPLICATION_TAGS , Utils . format ( descriptor . tags , ", " ) ) ; Utils . writePropertiesFile ( properties , f ) ; }
Saves an application template s descriptor .
10,850
static String getLegacyProperty ( Properties props , String property , String defaultValue ) { String result = props . getProperty ( property , null ) ; if ( result == null ) result = props . getProperty ( LEGACY_PREFIX + property , defaultValue ) ; return result ; }
Gets a property value while supporting legacy ones .
10,851
public static void createProjectSkeleton ( File targetDirectory , CreationBean creationBean ) throws IOException { if ( creationBean . isMavenProject ( ) ) createMavenProject ( targetDirectory , creationBean ) ; else createSimpleProject ( targetDirectory , creationBean ) ; }
Creates a project for Roboconf .
10,852
public static List < File > createRecipeDirectories ( File applicationDirectory ) throws IOException { List < File > result = new ArrayList < > ( ) ; ApplicationLoadResult alr = RuntimeModelIo . loadApplicationFlexibly ( applicationDirectory ) ; if ( alr . getApplicationTemplate ( ) != null ) { for ( Component c : ComponentHelpers . findAllComponents ( alr . getApplicationTemplate ( ) ) ) { File directory = ResourceUtils . findInstanceResourcesDirectory ( applicationDirectory , c ) ; if ( ! directory . exists ( ) ) result . add ( directory ) ; Utils . createDirectory ( directory ) ; } } return result ; }
Creates the recipes directories for a Roboconf components .
10,853
private static void createSimpleProject ( File targetDirectory , CreationBean creationBean ) throws IOException { String [ ] directoriesToCreate = creationBean . isReusableRecipe ( ) ? RR_DIRECTORIES : ALL_DIRECTORIES ; for ( String s : directoriesToCreate ) { File dir = new File ( targetDirectory , s ) ; Utils . createDirectory ( dir ) ; } InputStream in = ProjectUtils . class . getResourceAsStream ( "/application-skeleton.props" ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Utils . copyStreamSafely ( in , out ) ; String tpl = out . toString ( "UTF-8" ) . replace ( TPL_NAME , creationBean . getProjectName ( ) ) . replace ( TPL_VERSION , creationBean . getProjectVersion ( ) ) . replace ( TPL_DESCRIPTION , creationBean . getProjectDescription ( ) ) ; completeProjectCreation ( targetDirectory , tpl , creationBean ) ; }
Creates a simple project for Roboconf .
10,854
private static void createMavenProject ( File targetDirectory , CreationBean creationBean ) throws IOException { File rootDir = new File ( targetDirectory , Constants . MAVEN_SRC_MAIN_MODEL ) ; String [ ] directoriesToCreate = creationBean . isReusableRecipe ( ) ? RR_DIRECTORIES : ALL_DIRECTORIES ; for ( String s : directoriesToCreate ) { File dir = new File ( rootDir , s ) ; Utils . createDirectory ( dir ) ; } InputStream in ; if ( Utils . isEmptyOrWhitespaces ( creationBean . getCustomPomLocation ( ) ) ) in = ProjectUtils . class . getResourceAsStream ( "/pom-skeleton.xml" ) ; else in = new FileInputStream ( creationBean . getCustomPomLocation ( ) ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Utils . copyStreamSafely ( in , out ) ; String tpl = out . toString ( "UTF-8" ) . replace ( TPL_NAME , creationBean . getProjectName ( ) ) . replace ( TPL_POM_GROUP , creationBean . getGroupId ( ) ) . replace ( TPL_POM_PLUGIN_VERSION , creationBean . getPluginVersion ( ) ) . replace ( TPL_VERSION , creationBean . getProjectVersion ( ) ) . replace ( TPL_POM_ARTIFACT , creationBean . getArtifactId ( ) ) . replace ( TPL_DESCRIPTION , creationBean . getProjectDescription ( ) ) ; File pomFile = new File ( targetDirectory , "pom.xml" ) ; Utils . copyStream ( new ByteArrayInputStream ( tpl . getBytes ( StandardCharsets . UTF_8 ) ) , pomFile ) ; in = ProjectUtils . class . getResourceAsStream ( "/application-skeleton.props" ) ; out = new ByteArrayOutputStream ( ) ; Utils . copyStreamSafely ( in , out ) ; tpl = out . toString ( "UTF-8" ) . replace ( TPL_NAME , creationBean . getProjectName ( ) ) . replace ( TPL_DESCRIPTION , "${project.description}" ) ; if ( ! creationBean . getProjectVersion ( ) . contains ( "$" ) ) tpl = tpl . replace ( TPL_VERSION , "${project.version}" ) ; else tpl = tpl . replace ( TPL_VERSION , creationBean . getProjectVersion ( ) ) ; completeProjectCreation ( rootDir , tpl , creationBean ) ; }
Creates a Maven project for Roboconf .
10,855
private static void completeProjectCreation ( File targetDirectory , String descriptorContent , CreationBean creationBean ) throws IOException { File f = new File ( targetDirectory , Constants . PROJECT_DIR_GRAPH + "/" + GRAPH_EP ) ; InputStream in = ProjectUtils . class . getResourceAsStream ( "/graph-skeleton.graph" ) ; Utils . copyStream ( in , f ) ; if ( ! creationBean . isReusableRecipe ( ) ) { f = new File ( targetDirectory , Constants . PROJECT_DIR_DESC + "/" + Constants . PROJECT_FILE_DESCRIPTOR ) ; Utils . writeStringInto ( descriptorContent , f ) ; f = new File ( targetDirectory , Constants . PROJECT_DIR_INSTANCES + "/" + INSTANCES_EP ) ; in = ProjectUtils . class . getResourceAsStream ( "/instances-skeleton.instances" ) ; Utils . copyStream ( in , f ) ; } }
Completes the creation of a Roboconf project .
10,856
private static ErrorDetails [ ] addLineAndFile ( int line , File file , ErrorDetails ... details ) { Set < ErrorDetails > updatedDetails = new LinkedHashSet < > ( ) ; if ( details != null ) updatedDetails . addAll ( Arrays . asList ( details ) ) ; if ( file != null ) { updatedDetails . add ( file ( file ) ) ; updatedDetails . add ( line ( line ) ) ; } return updatedDetails . toArray ( new ErrorDetails [ updatedDetails . size ( ) ] ) ; }
Adds details about the line number and the file .
10,857
public static Map < String , String > buildReferenceMap ( Instance instance ) { Map < String , String > result = new HashMap < > ( ) ; String instancePath = InstanceHelpers . computeInstancePath ( instance ) ; result . put ( ROBOCONF_INSTANCE_NAME , instance . getName ( ) ) ; result . put ( ROBOCONF_INSTANCE_PATH , instancePath ) ; result . put ( ROBOCONF_COMPONENT_NAME , instance . getComponent ( ) . getName ( ) ) ; result . put ( ROBOCONF_CLEAN_INSTANCE_PATH , cleanInstancePath ( instancePath ) ) ; result . put ( ROBOCONF_CLEAN_REVERSED_INSTANCE_PATH , cleanReversedInstancePath ( instancePath ) ) ; return result ; }
Builds a map with the variables defined by this class .
10,858
List < MonitoringHandlerRun > extractRuleSections ( File file , String fileContent , Properties params ) { StringBuilder sb = new StringBuilder ( ) ; List < String > sections = new ArrayList < String > ( ) ; for ( String s : Arrays . asList ( fileContent . trim ( ) . split ( "\n" ) ) ) { s = s . trim ( ) ; if ( s . length ( ) == 0 || s . startsWith ( COMMENT_DELIMITER ) ) continue ; if ( s . toLowerCase ( ) . startsWith ( RULE_BEGINNING ) ) { addSectionIfNotEmpty ( sections , sb . toString ( ) ) ; sb . setLength ( 0 ) ; } sb . append ( Utils . expandTemplate ( s , params ) + "\n" ) ; } addSectionIfNotEmpty ( sections , sb . toString ( ) ) ; List < MonitoringHandlerRun > result = new ArrayList < MonitoringHandlerRun > ( ) ; for ( String s : sections ) { Matcher m = this . eventPattern . matcher ( s ) ; if ( ! m . find ( ) ) continue ; s = s . substring ( m . end ( ) ) . trim ( ) ; MonitoringHandlerRun bean = new MonitoringHandlerRun ( ) ; bean . handlerName = m . group ( 1 ) ; bean . eventId = m . group ( 2 ) ; bean . rawRulesText = s ; result . add ( bean ) ; } return result ; }
Reads the file content extracts rules sections and prepares the handler invocations .
10,859
public void setTags ( Collection < String > tags ) { synchronized ( this . tags ) { this . tags . clear ( ) ; if ( tags != null ) this . tags . addAll ( tags ) ; } }
Replaces all the tags .
10,860
public void validate ( ) { ErrorDetails details = null ; if ( this . fileName != null ) details = ErrorDetails . file ( this . fileName ) ; if ( this . failed ) { this . errors . add ( new ModelError ( ErrorCode . REC_TARGET_INVALID_FILE_OR_CONTENT , this . modelObject , details ) ) ; } else { String id = this . props . getProperty ( Constants . TARGET_PROPERTY_ID ) ; if ( Utils . isEmptyOrWhitespaces ( id ) ) this . errors . add ( new ModelError ( ErrorCode . REC_TARGET_NO_ID , this . modelObject , details ) ) ; String handler = this . props . getProperty ( Constants . TARGET_PROPERTY_HANDLER ) ; if ( Utils . isEmptyOrWhitespaces ( handler ) ) this . errors . add ( new ModelError ( ErrorCode . REC_TARGET_NO_HANDLER , this . modelObject , details ) ) ; String name = this . props . getProperty ( Constants . TARGET_PROPERTY_NAME ) ; if ( Utils . isEmptyOrWhitespaces ( name ) ) this . errors . add ( new ModelError ( ErrorCode . REC_TARGET_NO_NAME , this . modelObject , details ) ) ; } }
Validates target properties .
10,861
public static List < ModelError > parseDirectory ( File directory , Component c ) { List < ModelError > result = new ArrayList < > ( ) ; Set < String > targetIds = new HashSet < > ( ) ; for ( File f : Utils . listDirectFiles ( directory , Constants . FILE_EXT_PROPERTIES ) ) { TargetValidator tv = new TargetValidator ( f , c ) ; tv . validate ( ) ; result . addAll ( tv . getErrors ( ) ) ; String id = tv . getProperties ( ) . getProperty ( Constants . TARGET_PROPERTY_ID ) ; if ( targetIds . contains ( id ) ) result . add ( new ModelError ( ErrorCode . REC_TARGET_CONFLICTING_ID , tv . modelObject , name ( id ) ) ) ; targetIds . add ( id ) ; } if ( targetIds . isEmpty ( ) ) result . add ( new ModelError ( ErrorCode . REC_TARGET_NO_PROPERTIES , null , directory ( directory ) ) ) ; return result ; }
Parses a directory with one or several properties files .
10,862
public static List < ModelError > parseTargetProperties ( File projectDirectory , Component c ) { List < ModelError > errors ; File dir = ResourceUtils . findInstanceResourcesDirectory ( projectDirectory , c ) ; if ( dir . isDirectory ( ) && ! Utils . listAllFiles ( dir , Constants . FILE_EXT_PROPERTIES ) . isEmpty ( ) ) errors = parseDirectory ( dir , c ) ; else errors = new ArrayList < > ( 0 ) ; return errors ; }
Parses the target properties for a given component .
10,863
static int fixSelectionLength ( String fullText , int selectionOffset , int selectionLength ) { if ( selectionLength < 0 ) selectionLength = 0 ; else if ( selectionOffset + selectionLength > fullText . length ( ) ) selectionLength = fullText . length ( ) - selectionOffset ; for ( ; selectionOffset + selectionLength < fullText . length ( ) ; selectionLength ++ ) { char c = fullText . charAt ( selectionOffset + selectionLength ) ; if ( isLineBreak ( c ) ) break ; } return selectionLength ; }
Fixes the selection length to get the whole line .
10,864
void createImage ( String imageId ) throws TargetException { File targetDirectory = this . parameters . getTargetPropertiesDirectory ( ) ; String dockerFilePath = this . parameters . getTargetProperties ( ) . get ( GENERATE_IMAGE_FROM ) ; if ( ! Utils . isEmptyOrWhitespaces ( dockerFilePath ) && targetDirectory != null ) { this . logger . fine ( "Trying to create image " + imageId + " from a Dockerfile." ) ; File dockerFile = new File ( targetDirectory , dockerFilePath ) ; if ( ! dockerFile . exists ( ) ) throw new TargetException ( "No Dockerfile was found at " + dockerFile ) ; String builtImageId ; this . logger . fine ( "Asking Docker to build the image from our Dockerfile." ) ; try { builtImageId = this . dockerClient . buildImageCmd ( dockerFile ) . withTags ( Sets . newHashSet ( imageId ) ) . withPull ( true ) . exec ( new RoboconfBuildImageResultCallback ( ) ) . awaitImageId ( ) ; } catch ( Exception e ) { Utils . logException ( this . logger , e ) ; throw new TargetException ( e ) ; } this . logger . fine ( "Image '" + builtImageId + "' was succesfully generated by Roboconf." ) ; } }
Creates an image .
10,865
public String login ( String user , String pwd ) { String token = null ; try { this . authService . authenticate ( user , pwd ) ; token = UUID . randomUUID ( ) . toString ( ) ; Long now = new Date ( ) . getTime ( ) ; this . tokenToLoginTime . put ( token , now ) ; this . tokenToUsername . put ( token , user ) ; } catch ( LoginException e ) { this . logger . severe ( "Invalid login attempt by user " + user ) ; } return token ; }
Authenticates a user and creates a new session .
10,866
public boolean isSessionValid ( final String token , long validityPeriod ) { boolean valid = false ; Long loginTime = null ; if ( token != null ) loginTime = this . tokenToLoginTime . get ( token ) ; if ( validityPeriod < 0 ) { valid = loginTime != null ; } else if ( loginTime != null ) { long now = new Date ( ) . getTime ( ) ; valid = ( now - loginTime ) <= validityPeriod * 1000 ; if ( ! valid ) logout ( token ) ; } return valid ; }
Determines whether a session is valid .
10,867
public void processEvent ( SystemEvent event ) throws AbortProcessingException { if ( ! FacesContext . getCurrentInstance ( ) . isPostback ( ) ) { insertLabelBeforeThisInputField ( ) ; insertMessageBehindThisInputField ( ) ; } }
Catching the PreRenderViewEvent allows AngularFaces to modify the JSF tree by adding a label and a message .
10,868
private boolean associateElasticIp ( ) { String elasticIp = this . targetProperties . get ( Ec2Constants . ELASTIC_IP ) ; if ( ! Utils . isEmptyOrWhitespaces ( elasticIp ) ) { this . logger . fine ( "Associating an elastic IP with the instance. IP = " + elasticIp ) ; AssociateAddressRequest associateAddressRequest = new AssociateAddressRequest ( this . machineId , elasticIp ) ; this . ec2Api . associateAddress ( associateAddressRequest ) ; } return true ; }
Associates an elastic IP with the VM .
10,869
private String createVolume ( String storageId , String snapshotId , int size ) { String volumeType = Ec2IaasHandler . findStorageProperty ( this . targetProperties , storageId , VOLUME_TYPE_PREFIX ) ; if ( volumeType == null ) volumeType = "standard" ; CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest ( ) . withAvailabilityZone ( this . availabilityZone ) . withVolumeType ( volumeType ) . withSize ( size ) ; if ( ! Utils . isEmptyOrWhitespaces ( snapshotId ) && snapshotId . startsWith ( "snap-" ) ) createVolumeRequest . withSnapshotId ( snapshotId ) ; CreateVolumeResult createVolumeResult = this . ec2Api . createVolume ( createVolumeRequest ) ; return createVolumeResult . getVolume ( ) . getVolumeId ( ) ; }
Creates volume for EBS .
10,870
private boolean volumeCreated ( String volumeId ) { DescribeVolumesRequest dvs = new DescribeVolumesRequest ( ) ; ArrayList < String > volumeIds = new ArrayList < String > ( ) ; volumeIds . add ( volumeId ) ; dvs . setVolumeIds ( volumeIds ) ; DescribeVolumesResult dvsresult = null ; try { dvsresult = this . ec2Api . describeVolumes ( dvs ) ; } catch ( Exception e ) { dvsresult = null ; } return dvsresult != null && "available" . equals ( dvsresult . getVolumes ( ) . get ( 0 ) . getState ( ) ) ; }
Checks whether volume is created .
10,871
private boolean volumesCreated ( ) { for ( Map . Entry < String , String > entry : this . storageIdToVolumeId . entrySet ( ) ) { String volumeId = entry . getValue ( ) ; if ( ! volumeCreated ( volumeId ) ) return false ; } return true ; }
Checks whether all specified volumes are created .
10,872
private String lookupVolume ( String volumeIdOrName ) { String ret = null ; if ( ! Utils . isEmptyOrWhitespaces ( volumeIdOrName ) ) { DescribeVolumesRequest dvs = new DescribeVolumesRequest ( Collections . singletonList ( volumeIdOrName ) ) ; DescribeVolumesResult dvsresult = null ; try { dvsresult = this . ec2Api . describeVolumes ( dvs ) ; } catch ( Exception e ) { dvsresult = null ; } if ( dvsresult == null || dvsresult . getVolumes ( ) == null || dvsresult . getVolumes ( ) . size ( ) < 1 ) { dvs = new DescribeVolumesRequest ( ) . withFilters ( new Filter ( ) . withName ( "tag:Name" ) . withValues ( volumeIdOrName ) ) ; try { dvsresult = this . ec2Api . describeVolumes ( dvs ) ; } catch ( Exception e ) { dvsresult = null ; } } if ( dvsresult != null && dvsresult . getVolumes ( ) != null && dvsresult . getVolumes ( ) . size ( ) > 0 ) ret = dvsresult . getVolumes ( ) . get ( 0 ) . getVolumeId ( ) ; } return ret ; }
Looks up volume by ID or Name tag .
10,873
public String get ( String key ) { String result ; try { result = this . bundle . getString ( key ) ; } catch ( MissingResourceException e ) { result = OOPS + key + '!' ; } return result ; }
Finds an internationalized string by key .
10,874
public Map < String , String > getExternalExports ( ) { return this . template != null ? this . template . externalExports : new HashMap < String , String > ( 0 ) ; }
A shortcut method to access the template s external exports mapping .
10,875
public boolean replaceApplicationBindings ( String externalExportPrefix , Set < String > applicationNames ) { boolean changed = false ; Set < String > oldApplicationNames = this . applicationBindings . remove ( externalExportPrefix ) ; if ( oldApplicationNames == null ) { changed = ! applicationNames . isEmpty ( ) ; } else if ( oldApplicationNames . size ( ) != applicationNames . size ( ) ) { changed = true ; } else { oldApplicationNames . removeAll ( applicationNames ) ; changed = ! oldApplicationNames . isEmpty ( ) ; } if ( ! applicationNames . isEmpty ( ) ) this . applicationBindings . put ( externalExportPrefix , applicationNames ) ; return changed ; }
Replaces application bindings for a given prefix .
10,876
static void interceptLoadingFiles ( Properties props ) throws IOException { Logger logger = Logger . getLogger ( UserDataHelpers . class . getName ( ) ) ; Set < String > keys = props . stringPropertyNames ( ) ; for ( final String key : keys ) { if ( ! key . startsWith ( ENCODE_FILE_CONTENT_PREFIX ) ) continue ; String realKey = key . substring ( ENCODE_FILE_CONTENT_PREFIX . length ( ) ) ; String value = props . getProperty ( realKey ) ; if ( value == null ) { logger . fine ( "No file was specified for " + realKey + ". Skipping it..." ) ; continue ; } File f = new File ( value ) ; if ( ! f . exists ( ) ) throw new IOException ( "File " + f + " was not found." ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; Utils . copyStream ( f , os ) ; String encodedFileContent = encodeToBase64 ( os . toByteArray ( ) ) ; props . put ( key , encodedFileContent ) ; } }
Intercepts the properties and loads file contents .
10,877
public void run ( String [ ] args ) throws Exception { if ( args . length != 1 ) throw new RuntimeException ( "A file path was expected as an argument." ) ; File targetFile = new File ( args [ 0 ] ) ; if ( ! targetFile . isFile ( ) ) throw new RuntimeException ( "File " + targetFile + " does not exist." ) ; Field [ ] fields = IPreferencesMngr . class . getDeclaredFields ( ) ; Map < String , String > propertyNameToComment = new HashMap < > ( ) ; for ( Field field : fields ) { String constantName = ( String ) field . get ( null ) ; PreferenceDescription annotation = field . getAnnotation ( PreferenceDescription . class ) ; if ( annotation == null ) throw new RuntimeException ( "Documentation was not written for the " + field . getName ( ) + " constant in IPreferencesMngr.java." ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( annotation . desc ( ) ) ; String [ ] values = annotation . values ( ) ; if ( values . length > 0 ) { sb . append ( "\n\nPossible values:\n" ) ; for ( String value : values ) { sb . append ( " - " ) ; sb . append ( value ) ; sb . append ( "\n" ) ; } } propertyNameToComment . put ( constantName , sb . toString ( ) ) ; } Defaults def = new Defaults ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( PreferenceKeyCategory cat : PreferenceKeyCategory . values ( ) ) { sb . append ( "\n###\n# " ) ; sb . append ( cat . getDescription ( ) ) ; sb . append ( "\n###\n" ) ; for ( Map . Entry < String , PreferenceKeyCategory > entry : def . keyToCategory . entrySet ( ) ) { if ( cat != entry . getValue ( ) ) continue ; String comment = propertyNameToComment . get ( entry . getKey ( ) ) ; comment = comment . replaceAll ( "^" , "# " ) . replace ( "\n" , "\n# " ) ; sb . append ( "\n" ) ; sb . append ( comment ) ; sb . append ( "\n" ) ; sb . append ( entry . getKey ( ) ) ; sb . append ( " = " ) ; String defaultValue = def . keyToDefaultValue . get ( entry . getKey ( ) ) ; if ( ! Utils . isEmptyOrWhitespaces ( defaultValue ) ) sb . append ( defaultValue . trim ( ) ) ; sb . append ( "\n" ) ; } sb . append ( "\n" ) ; } Utils . appendStringInto ( sb . toString ( ) , targetFile ) ; }
The real method that does the job .
10,878
public void extendComponent ( Component component ) { if ( this . extendedComponent != null ) this . extendedComponent . extendingComponents . remove ( this ) ; component . extendingComponents . add ( this ) ; this . extendedComponent = component ; }
Creates a bi - directional relation between this component and an extended one .
10,879
public List < Rule > findRulesToExecute ( ) { this . logger . fine ( "Looking for rules to execute after an event was recorded for application " + this . app ) ; List < Rule > result = new ArrayList < > ( ) ; long now = System . nanoTime ( ) ; for ( Rule rule : this . ruleNameToRule . values ( ) ) { long validPeriodStart = now - TimeUnit . SECONDS . toNanos ( rule . getDelayBetweenSucceedingInvocations ( ) ) ; Long lastExecutionTime = this . ruleNameToLastExecution . get ( rule . getRuleName ( ) ) ; if ( lastExecutionTime != null && lastExecutionTime - validPeriodStart > 0 ) { this . logger . finer ( "Ignoring the rule " + rule . getRuleName ( ) + " since the execution delay has not yet expired." ) ; continue ; } Long lastRecord = this . eventNameToLastRecordTime . get ( rule . getEventName ( ) ) ; if ( lastRecord == null ) continue ; StringBuilder sbTrigger = new StringBuilder ( ) ; sbTrigger . append ( rule . getEventName ( ) ) ; sbTrigger . append ( lastRecord ) ; String lastTrigger = this . ruleNameToLastTrigger . get ( rule . getRuleName ( ) ) ; if ( Objects . equals ( lastTrigger , sbTrigger . toString ( ) ) ) { this . logger . finer ( "Ignoring the rule " + rule . getRuleName ( ) + " since no new event occurred since its last execution." ) ; continue ; } validPeriodStart = now - TimeUnit . SECONDS . toNanos ( rule . getTimingWindow ( ) ) ; if ( rule . getTimingWindow ( ) != Rule . NO_TIMING_WINDOW && lastRecord - validPeriodStart < 0 ) { this . logger . finer ( "Ignoring the rule " + rule . getRuleName ( ) + " since no new event occurred since its last execution." ) ; continue ; } this . logger . finer ( "Rule " + rule . getRuleName ( ) + " was found following the occurrence of the " + rule . getEventName ( ) + " event." ) ; this . ruleNameToLastTrigger . put ( rule . getRuleName ( ) , sbTrigger . toString ( ) ) ; result . add ( rule ) ; } return result ; }
Finds the rules to execute after an event was recorded .
10,880
private String safeApply ( Collection < InstanceContextBean > instances , Options options , String componentPath ) throws IOException { String installerName = ( String ) options . hash . get ( "installer" ) ; final InstanceFilter filter = InstanceFilter . createFilter ( componentPath , installerName ) ; final Collection < InstanceContextBean > selectedInstances = filter . apply ( instances ) ; final StringBuilder buffer = new StringBuilder ( ) ; final Context parent = options . context ; int index = 0 ; final int last = selectedInstances . size ( ) - 1 ; for ( final InstanceContextBean instance : selectedInstances ) { final Context current = Context . newBuilder ( parent , instance ) . combine ( "@index" , index ) . combine ( "@first" , index == 0 ? "first" : "" ) . combine ( "@last" , index == last ? "last" : "" ) . combine ( "@odd" , index % 2 == 0 ? "" : "odd" ) . combine ( "@even" , index % 2 == 0 ? "even" : "" ) . build ( ) ; index ++ ; buffer . append ( options . fn ( current ) ) ; } return buffer . toString ( ) ; }
Same as above but with type - safe arguments .
10,881
private static Collection < InstanceContextBean > descendantInstances ( final InstanceContextBean instance ) { final Collection < InstanceContextBean > result = new ArrayList < InstanceContextBean > ( ) ; for ( final InstanceContextBean child : instance . getChildren ( ) ) { result . add ( child ) ; result . addAll ( descendantInstances ( child ) ) ; } return result ; }
Returns all the descendant instances of the given instance .
10,882
public Class < ? > reflectClass ( final String className ) { Preconditions . checkArgument ( className != null && className . trim ( ) . length ( ) > 0 , "className cannot be null or empty" ) ; return provider . getClassReflectionProvider ( className ) . reflectClass ( ) ; }
This method will reflect a Class object that is represented by className .
10,883
public < T > ClassController < T > on ( final Class < T > clazz ) { return new DefaultClassController < T > ( provider , clazz ) ; }
Method to access reflection on clazz .
10,884
ComputeService jcloudContext ( Map < String , String > targetProperties ) throws TargetException { validate ( targetProperties ) ; ComputeServiceContext context = ContextBuilder . newBuilder ( targetProperties . get ( PROVIDER_ID ) ) . endpoint ( targetProperties . get ( ENDPOINT ) ) . credentials ( targetProperties . get ( IDENTITY ) , targetProperties . get ( CREDENTIAL ) ) . buildView ( ComputeServiceContext . class ) ; return context . getComputeService ( ) ; }
Creates a JCloud context .
10,885
static void validate ( Map < String , String > targetProperties ) throws TargetException { checkProperty ( PROVIDER_ID , targetProperties ) ; checkProperty ( ENDPOINT , targetProperties ) ; checkProperty ( IMAGE_NAME , targetProperties ) ; checkProperty ( SECURITY_GROUP , targetProperties ) ; checkProperty ( IDENTITY , targetProperties ) ; checkProperty ( CREDENTIAL , targetProperties ) ; checkProperty ( HARDWARE_NAME , targetProperties ) ; }
Validates the target properties .
10,886
void updateAgentConfigurationFile ( TargetHandlerParameters parameters , SSHClient ssh , File tmpDir , Map < String , String > keyToNewValue ) throws IOException { this . logger . fine ( "Updating agent parameters on remote host..." ) ; String agentConfigDir = Utils . getValue ( parameters . getTargetProperties ( ) , SCP_AGENT_CONFIG_DIR , DEFAULT_SCP_AGENT_CONFIG_DIR ) ; File localAgentConfig = new File ( tmpDir , Constants . KARAF_CFG_FILE_AGENT ) ; File remoteAgentConfig = new File ( agentConfigDir , Constants . KARAF_CFG_FILE_AGENT ) ; ssh . newSCPFileTransfer ( ) . download ( remoteAgentConfig . getCanonicalPath ( ) , new FileSystemFile ( tmpDir ) ) ; String config = Utils . readFileContent ( localAgentConfig ) ; config = Utils . updateProperties ( config , keyToNewValue ) ; Utils . writeStringInto ( config , localAgentConfig ) ; ssh . newSCPFileTransfer ( ) . upload ( new FileSystemFile ( localAgentConfig ) , agentConfigDir ) ; }
Updates the configuration file of an agent .
10,887
public static void updateImports ( Instance instance , Map < String , Collection < Import > > variablePrefixToImports ) { instance . getImports ( ) . clear ( ) ; if ( variablePrefixToImports != null ) instance . getImports ( ) . putAll ( variablePrefixToImports ) ; }
Updates the imports of an instance with new values .
10,888
public static Import findImportByExportingInstance ( Collection < Import > imports , String exportingInstancePath ) { Import result = null ; if ( imports != null && exportingInstancePath != null ) { for ( Import imp : imports ) { if ( exportingInstancePath . equals ( imp . getInstancePath ( ) ) ) { result = imp ; break ; } } } return result ; }
Finds a specific import from the path of the instance that exports it .
10,889
public static Map < String , String > httpMessagingConfiguration ( String ip , int port ) { final Map < String , String > result = new LinkedHashMap < > ( ) ; result . put ( MessagingConstants . MESSAGING_TYPE_PROPERTY , HttpConstants . FACTORY_HTTP ) ; result . put ( HttpConstants . HTTP_SERVER_IP , ip == null ? HttpConstants . DEFAULT_IP : ip ) ; result . put ( HttpConstants . HTTP_SERVER_PORT , "" + ( port <= 0 ? HttpConstants . DEFAULT_PORT : port ) ) ; return result ; }
Return a HTTP messaging configuration for the given parameters .
10,890
public List < Preference > listPreferences ( ) { this . logger . finer ( "Getting all the preferences." ) ; WebResource path = this . resource . path ( UrlConstants . PREFERENCES ) ; List < Preference > result = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . get ( new GenericType < List < Preference > > ( ) { } ) ; if ( result != null ) this . logger . finer ( result . size ( ) + " preferences were found on the DM." ) ; else this . logger . finer ( "No preference was found on the DM." ) ; return result != null ? result : new ArrayList < Preference > ( ) ; }
Lists all the preferences .
10,891
public static String resolve ( String lang ) { String result ; if ( ! LANGUAGES . contains ( lang ) ) result = EN ; else result = lang ; return result ; }
Resolves a language to a supported translation .
10,892
static Map < String , String > loadContent ( String lang ) { Map < String , String > result = new LinkedHashMap < > ( ) ; try { InputStream in = TranslationBundle . class . getResourceAsStream ( "/" + lang + ".json" ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; Utils . copyStreamSafely ( in , os ) ; String content = os . toString ( "UTF-8" ) ; Matcher m = Pattern . compile ( ROW_PATTERN ) . matcher ( content ) ; while ( m . find ( ) ) { String s = m . group ( 2 ) ; try { ErrorCode ec = ErrorCode . valueOf ( m . group ( 1 ) ) ; for ( int i = 0 ; i < ec . getI18nProperties ( ) . length ; i ++ ) { s = s . replace ( "{" + i + "}" , ec . getI18nProperties ( ) [ i ] ) ; } } catch ( IllegalArgumentException e ) { } result . put ( m . group ( 1 ) , s ) ; } } catch ( Exception e ) { final Logger logger = Logger . getLogger ( TranslationBundle . class . getName ( ) ) ; Utils . logException ( logger , e ) ; } return result ; }
Loads content from JSon files .
10,893
static void parseProperties ( Map < String , String > targetProperties ) throws TargetException { String [ ] properties = { Ec2Constants . EC2_ENDPOINT , Ec2Constants . EC2_ACCESS_KEY , Ec2Constants . EC2_SECRET_KEY , Ec2Constants . AMI_VM_NODE , Ec2Constants . VM_INSTANCE_TYPE , Ec2Constants . SSH_KEY_NAME , Ec2Constants . SECURITY_GROUP_NAME } ; for ( String property : properties ) { if ( StringUtils . isBlank ( targetProperties . get ( property ) ) ) throw new TargetException ( "The value for " + property + " cannot be null or empty." ) ; } }
Parses the properties and saves them in a Java bean .
10,894
public static AmazonEC2 createEc2Client ( Map < String , String > targetProperties ) throws TargetException { parseProperties ( targetProperties ) ; AWSCredentials credentials = new BasicAWSCredentials ( targetProperties . get ( Ec2Constants . EC2_ACCESS_KEY ) , targetProperties . get ( Ec2Constants . EC2_SECRET_KEY ) ) ; AmazonEC2 ec2 = new AmazonEC2Client ( credentials ) ; ec2 . setEndpoint ( targetProperties . get ( Ec2Constants . EC2_ENDPOINT ) ) ; return ec2 ; }
Creates a client for EC2 .
10,895
private RunInstancesRequest prepareEC2RequestNode ( Map < String , String > targetProperties , String userData ) throws UnsupportedEncodingException { RunInstancesRequest runInstancesRequest = new RunInstancesRequest ( ) ; String flavor = targetProperties . get ( Ec2Constants . VM_INSTANCE_TYPE ) ; if ( Utils . isEmptyOrWhitespaces ( flavor ) ) flavor = "t1.micro" ; runInstancesRequest . setInstanceType ( flavor ) ; runInstancesRequest . setImageId ( targetProperties . get ( Ec2Constants . AMI_VM_NODE ) ) ; runInstancesRequest . setMinCount ( 1 ) ; runInstancesRequest . setMaxCount ( 1 ) ; runInstancesRequest . setKeyName ( targetProperties . get ( Ec2Constants . SSH_KEY_NAME ) ) ; String secGroup = targetProperties . get ( Ec2Constants . SECURITY_GROUP_NAME ) ; if ( Utils . isEmptyOrWhitespaces ( secGroup ) ) secGroup = "default" ; runInstancesRequest . setSecurityGroups ( Collections . singletonList ( secGroup ) ) ; String availabilityZone = targetProperties . get ( Ec2Constants . AVAILABILITY_ZONE ) ; if ( ! Utils . isEmptyOrWhitespaces ( availabilityZone ) ) runInstancesRequest . setPlacement ( new Placement ( availabilityZone ) ) ; String encodedUserData = new String ( Base64 . encodeBase64 ( userData . getBytes ( StandardCharsets . UTF_8 ) ) , "UTF-8" ) ; runInstancesRequest . setUserData ( encodedUserData ) ; return runInstancesRequest ; }
Prepares the request .
10,896
private Set < String > registerTargets ( ApplicationTemplate tpl ) throws IOException , UnauthorizedActionException { IOException conflictException = null ; Set < String > newTargetIds = new HashSet < > ( ) ; Map < Component , Set < String > > componentToTargetIds = new HashMap < > ( ) ; componentLoop : for ( Map . Entry < Component , File > entry : ResourceUtils . findScopedInstancesDirectories ( tpl ) . entrySet ( ) ) { String defaultTargetId = null ; Set < String > targetIds = new HashSet < > ( ) ; componentToTargetIds . put ( entry . getKey ( ) , targetIds ) ; for ( File f : Utils . listDirectFiles ( entry . getValue ( ) , Constants . FILE_EXT_PROPERTIES ) ) { this . logger . fine ( "Registering target " + f . getName ( ) + " from component " + entry . getKey ( ) + " in application template " + tpl ) ; String targetId ; try { targetId = this . targetsMngr . createTarget ( f , tpl ) ; } catch ( IOException e ) { conflictException = e ; break componentLoop ; } this . targetsMngr . addHint ( targetId , tpl ) ; targetIds . add ( targetId ) ; newTargetIds . add ( targetId ) ; if ( Constants . TARGET_PROPERTIES_FILE_NAME . equalsIgnoreCase ( f . getName ( ) ) ) defaultTargetId = targetId ; } if ( defaultTargetId != null ) { targetIds . clear ( ) ; targetIds . add ( defaultTargetId ) ; } } if ( conflictException != null ) { this . logger . fine ( "A conflict was found while registering " ) ; unregisterTargets ( newTargetIds ) ; throw conflictException ; } for ( Map . Entry < Component , Set < String > > entry : componentToTargetIds . entrySet ( ) ) { String key = "@" + entry . getKey ( ) . getName ( ) ; if ( entry . getValue ( ) . size ( ) == 1 ) this . targetsMngr . associateTargetWith ( entry . getValue ( ) . iterator ( ) . next ( ) , tpl , key ) ; } return newTargetIds ; }
Registers the targets available in this template .
10,897
private void unregisterTargets ( Set < String > newTargetIds ) { for ( String targetId : newTargetIds ) { try { this . targetsMngr . deleteTarget ( targetId ) ; } catch ( Exception e ) { this . logger . severe ( "A target ID that has just been registered could not be created. That's weird." ) ; Utils . logException ( this . logger , e ) ; } } }
Unregisters targets .
10,898
public static InstanceContext parse ( String s ) { String name = null , qualifier = null , instancePathOrComponentName = null ; if ( s != null ) { Matcher m = Pattern . compile ( "(.*)::(.*)::(.*)" ) . matcher ( s ) ; if ( m . matches ( ) ) { name = m . group ( 1 ) . equals ( "null" ) ? null : m . group ( 1 ) ; qualifier = m . group ( 2 ) . equals ( "null" ) ? null : m . group ( 2 ) ; instancePathOrComponentName = m . group ( 3 ) . equals ( "null" ) ? null : m . group ( 3 ) ; } } return new InstanceContext ( name , qualifier , instancePathOrComponentName ) ; }
Parses a string to resolve a target mapping key .
10,899
public static String buildTopicNameForAgent ( Instance instance ) { Instance scopedInstance = InstanceHelpers . findScopedInstance ( instance ) ; return buildTopicNameForAgent ( InstanceHelpers . computeInstancePath ( scopedInstance ) ) ; }
Builds the default topic name for an agent .