idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
11,000
void installPuppetModules ( Instance instance ) throws IOException , InterruptedException { File instanceDirectory = InstanceHelpers . findInstanceDirectoryOnAgent ( instance ) ; File modulesFile = new File ( instanceDirectory , "modules.properties" ) ; if ( ! modulesFile . exists ( ) ) return ; Properties props = Utils . readPropertiesFile ( modulesFile ) ; for ( Map . Entry < Object , Object > entry : props . entrySet ( ) ) { List < String > commands = new ArrayList < > ( ) ; commands . add ( "puppet" ) ; commands . add ( "module" ) ; commands . add ( "install" ) ; String value = entry . getValue ( ) . toString ( ) ; if ( ! Utils . isEmptyOrWhitespaces ( value ) ) { commands . add ( "--version" ) ; commands . add ( value ) ; } commands . add ( ( String ) entry . getKey ( ) ) ; commands . add ( "--target-dir" ) ; commands . add ( instanceDirectory . getAbsolutePath ( ) ) ; String [ ] params = commands . toArray ( new String [ 0 ] ) ; this . logger . fine ( "Module installation: " + Arrays . toString ( params ) ) ; int exitCode = ProgramUtils . executeCommand ( this . logger , commands , null , null , this . applicationName , this . scopedInstancePath ) ; if ( exitCode != 0 ) throw new IOException ( "Puppet modules could not be installed for " + instance + "." ) ; } }
Executes a Puppet command to install the required modules .
11,001
String generateCodeToExecute ( String className , Instance instance , PuppetState puppetState , Import importChanged , boolean importAdded ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "class{'" ) ; sb . append ( className ) ; sb . append ( "': runningState => " ) ; sb . append ( puppetState . toString ( ) . toLowerCase ( ) ) ; Map < String , String > exports = InstanceHelpers . findAllExportedVariables ( instance ) ; String args = formatExportedVariables ( exports ) ; String importedTypes = formatInstanceImports ( instance ) ; if ( ! Utils . isEmptyOrWhitespaces ( args ) ) sb . append ( ", " + args ) ; if ( ! Utils . isEmptyOrWhitespaces ( importedTypes ) ) sb . append ( ", " + importedTypes ) ; if ( importChanged != null ) { String componentName = importChanged . getComponentName ( ) ; sb . append ( ", importDiff => {" + ( importAdded ? "added => {" : "removed => {" ) + formatImport ( importChanged ) + "}, " + ( importAdded ? "removed => undef" : "added => undef" ) + ", component => " + ( componentName != null ? componentName : "undef" ) + "}" ) ; } sb . append ( "}" ) ; return sb . toString ( ) ; }
Generates the code to be injected by Puppet into the manifest .
11,002
public static void verifyTargets ( ITargetHandlerResolver targetHandlerResolver , ManagedApplication ma , ITargetsMngr targetsMngr ) { Logger logger = Logger . getLogger ( TargetHelpers . class . getName ( ) ) ; for ( Instance inst : InstanceHelpers . getAllInstances ( ma . getApplication ( ) ) ) { if ( ! InstanceHelpers . isTarget ( inst ) ) continue ; try { String path = InstanceHelpers . computeInstancePath ( inst ) ; Map < String , String > targetProperties = targetsMngr . findTargetProperties ( ma . getApplication ( ) , path ) . asMap ( ) ; targetHandlerResolver . findTargetHandler ( targetProperties ) ; } catch ( TargetException e ) { logger . warning ( e . getMessage ( ) ) ; } } }
Verifies that all the target handlers an application needs are installed .
11,003
public FileDefinition buildFileDefinition ( Graphs graphs , File targetFile , boolean addComment ) { FileDefinition result = new FileDefinition ( targetFile ) ; result . setFileType ( FileDefinition . GRAPH ) ; 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" ) ) ; } Set < String > alreadySerializedNames = new HashSet < > ( ) ; for ( Component c : ComponentHelpers . findAllComponents ( graphs ) ) { if ( alreadySerializedNames . contains ( c . getName ( ) ) ) continue ; alreadySerializedNames . add ( c . getName ( ) ) ; result . getBlocks ( ) . addAll ( buildComponent ( result , c , addComment ) ) ; for ( Facet f : ComponentHelpers . findAllFacets ( c ) ) { if ( alreadySerializedNames . contains ( f . getName ( ) ) ) continue ; alreadySerializedNames . add ( f . getName ( ) ) ; result . getBlocks ( ) . addAll ( buildFacet ( result , f , addComment ) ) ; } } for ( Facet f : graphs . getFacetNameToFacet ( ) . values ( ) ) { if ( alreadySerializedNames . contains ( f . getName ( ) ) ) continue ; alreadySerializedNames . add ( f . getName ( ) ) ; result . getBlocks ( ) . addAll ( buildFacet ( result , f , addComment ) ) ; } return result ; }
Builds a file definition from a graph .
11,004
public static Map < String , byte [ ] > storeInstanceResources ( File applicationFilesDirectory , Instance instance ) throws IOException { Map < String , byte [ ] > result = new HashMap < > ( ) ; File instanceResourcesDirectory = findInstanceResourcesDirectory ( applicationFilesDirectory , instance ) ; if ( instanceResourcesDirectory . exists ( ) && instanceResourcesDirectory . isDirectory ( ) ) result . putAll ( Utils . storeDirectoryResourcesAsBytes ( instanceResourcesDirectory ) ) ; result . putAll ( storeInstanceProbeResources ( applicationFilesDirectory , instance ) ) ; return result ; }
Stores the instance resources into a map .
11,005
public static Map < String , byte [ ] > storeInstanceProbeResources ( File applicationFilesDirectory , Instance instance ) throws IOException { String [ ] exts = { Constants . FILE_EXT_MEASURES , Constants . FILE_EXT_MEASURES + ".properties" } ; Map < String , byte [ ] > result = new HashMap < > ( ) ; for ( String ext : exts ) { String fileName = instance . getComponent ( ) . getName ( ) + ext ; File autonomicMeasureFile = new File ( applicationFilesDirectory , Constants . PROJECT_DIR_PROBES + "/" + fileName ) ; if ( ! autonomicMeasureFile . exists ( ) ) break ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; Utils . copyStream ( autonomicMeasureFile , os ) ; result . put ( autonomicMeasureFile . getName ( ) , os . toByteArray ( ) ) ; } return result ; }
Stores the instance s resources related to probes into a map .
11,006
public static File findInstanceResourcesDirectory ( File applicationFilesDirectory , Instance instance ) { return findInstanceResourcesDirectory ( applicationFilesDirectory , instance . getComponent ( ) ) ; }
Finds the resource directory for an instance .
11,007
public static Map < Component , File > findScopedInstancesDirectories ( AbstractApplication absApp ) { Map < Component , File > result = new HashMap < > ( ) ; for ( Component c : ComponentHelpers . findAllComponents ( absApp . getGraphs ( ) ) ) { if ( ! ComponentHelpers . isTarget ( c ) ) continue ; File dir = ResourceUtils . findInstanceResourcesDirectory ( absApp . getDirectory ( ) , c ) ; if ( ! dir . exists ( ) ) continue ; result . put ( c , dir ) ; } return result ; }
Finds the resource directories for scoped instances .
11,008
protected void subscribe ( String id , MessagingContext ctx ) throws IOException { if ( ! canProceed ( ) ) return ; Set < MessagingContext > sub = this . routingContext . subscriptions . get ( id ) ; if ( sub == null ) { sub = new HashSet < > ( ) ; this . routingContext . subscriptions . put ( id , sub ) ; } sub . add ( ctx ) ; }
Registers a subscription between an ID and a context .
11,009
protected void unsubscribe ( String id , MessagingContext ctx ) throws IOException { if ( ! canProceed ( ) ) return ; Set < MessagingContext > sub = this . routingContext . subscriptions . get ( id ) ; if ( sub != null ) { sub . remove ( ctx ) ; if ( sub . isEmpty ( ) ) this . routingContext . subscriptions . remove ( id ) ; } }
Unregisters a subscription between an ID and a context .
11,010
public void setPollInterval ( long pollInterval ) { this . pollInterval = pollInterval ; this . logger . fine ( "Template watcher poll interval set to " + pollInterval ) ; synchronized ( this . watcherLock ) { if ( this . templateWatcher != null ) resetWatcher ( ) ; } }
Sets the poll interval for the template watcher .
11,011
public void setTemplatesDirectory ( String templatesDirectory ) { this . logger . fine ( "Templates directory is now... " + templatesDirectory ) ; this . templatesDIR = Utils . isEmptyOrWhitespaces ( templatesDirectory ) ? null : new File ( templatesDirectory ) ; synchronized ( this . watcherLock ) { if ( this . templateWatcher != null ) resetWatcher ( ) ; } }
Sets the templates directory .
11,012
public void setOutputDirectory ( String outputDirectory ) { this . logger . fine ( "Output directory is now... " + outputDirectory ) ; this . outputDIR = Utils . isEmptyOrWhitespaces ( outputDirectory ) ? null : new File ( outputDirectory ) ; if ( this . outputDIR != null && this . dm != null ) { for ( ManagedApplication ma : this . dm . applicationMngr ( ) . getManagedApplications ( ) ) application ( ma . getApplication ( ) , EventType . CHANGED ) ; } }
Sets the output directory .
11,013
private void resetWatcher ( ) { stopWatcher ( ) ; if ( this . templatesDIR == null ) { this . logger . warning ( "The templates directory was not specified. DM templating is temporarily disabled." ) ; } else if ( this . outputDIR == null ) { this . logger . warning ( "The templates directory was not specified. DM templating is temporarily disabled." ) ; } else { this . templateWatcher = new TemplateWatcher ( this , this . templatesDIR , this . pollInterval ) ; this . templateWatcher . start ( ) ; } }
Updates the template watcher after a change in the templating manager configuration .
11,014
public static void configureFactory ( ConnectionFactory factory , Map < String , String > configuration ) throws IOException { final Logger logger = Logger . getLogger ( RabbitMqUtils . class . getName ( ) ) ; logger . fine ( "Configuring a connection factory for RabbitMQ." ) ; String messageServerIp = configuration . get ( RABBITMQ_SERVER_IP ) ; if ( messageServerIp != null ) { Map . Entry < String , Integer > entry = Utils . findUrlAndPort ( messageServerIp ) ; factory . setHost ( entry . getKey ( ) ) ; if ( entry . getValue ( ) > 0 ) factory . setPort ( entry . getValue ( ) ) ; } factory . setUsername ( configuration . get ( RABBITMQ_SERVER_USERNAME ) ) ; factory . setPassword ( configuration . get ( RABBITMQ_SERVER_PASSWORD ) ) ; factory . setConnectionTimeout ( 5000 ) ; factory . setAutomaticRecoveryEnabled ( true ) ; factory . setNetworkRecoveryInterval ( 10000 ) ; factory . setTopologyRecoveryEnabled ( true ) ; if ( Boolean . parseBoolean ( configuration . get ( RABBITMQ_USE_SSL ) ) ) { logger . fine ( "Connection factory for RabbitMQ: SSL is used." ) ; InputStream clientIS = null ; InputStream storeIS = null ; try { clientIS = new FileInputStream ( configuration . get ( RABBITMQ_SSL_KEY_STORE_PATH ) ) ; storeIS = new FileInputStream ( configuration . get ( RABBITMQ_SSL_TRUST_STORE_PATH ) ) ; char [ ] keyStorePassphrase = configuration . get ( RABBITMQ_SSL_KEY_STORE_PASSPHRASE ) . toCharArray ( ) ; KeyStore ks = KeyStore . getInstance ( getValue ( configuration , RABBITMQ_SSL_KEY_STORE_TYPE , DEFAULT_SSL_KEY_STORE_TYPE ) ) ; ks . load ( clientIS , keyStorePassphrase ) ; String value = getValue ( configuration , RABBITMQ_SSL_KEY_MNGR_FACTORY , DEFAULT_SSL_MNGR_FACTORY ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( value ) ; kmf . init ( ks , keyStorePassphrase ) ; char [ ] trustStorePassphrase = configuration . get ( RABBITMQ_SSL_TRUST_STORE_PASSPHRASE ) . toCharArray ( ) ; KeyStore tks = KeyStore . getInstance ( getValue ( configuration , RABBITMQ_SSL_TRUST_STORE_TYPE , DEFAULT_SSL_TRUST_STORE_TYPE ) ) ; tks . load ( storeIS , trustStorePassphrase ) ; value = getValue ( configuration , RABBITMQ_SSL_TRUST_MNGR_FACTORY , DEFAULT_SSL_MNGR_FACTORY ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( value ) ; tmf . init ( tks ) ; SSLContext c = SSLContext . getInstance ( getValue ( configuration , RABBITMQ_SSL_PROTOCOL , DEFAULT_SSL_PROTOCOL ) ) ; c . init ( kmf . getKeyManagers ( ) , tmf . getTrustManagers ( ) , null ) ; factory . useSslProtocol ( c ) ; } catch ( GeneralSecurityException e ) { throw new IOException ( "SSL configuration for the RabbitMQ factory failed." , e ) ; } finally { Utils . closeQuietly ( storeIS ) ; Utils . closeQuietly ( clientIS ) ; } } }
Configures the connection factory with the right settings .
11,015
public static void closeConnection ( Channel channel ) throws IOException { if ( channel != null ) { if ( channel . isOpen ( ) ) channel . close ( ) ; if ( channel . getConnection ( ) . isOpen ( ) ) channel . getConnection ( ) . close ( ) ; } }
Closes the connection to a channel .
11,016
public static String buildExchangeName ( MessagingContext ctx ) { String exchangeName ; if ( ctx . getKind ( ) == RecipientKind . DM ) exchangeName = buildExchangeNameForTheDm ( ctx . getDomain ( ) ) ; else if ( ctx . getKind ( ) == RecipientKind . INTER_APP ) exchangeName = buildExchangeNameForInterApp ( ctx . getDomain ( ) ) ; else exchangeName = RabbitMqUtils . buildExchangeNameForAgent ( ctx . getDomain ( ) , ctx . getApplicationName ( ) ) ; return exchangeName ; }
Builds an exchange name from a messaging context .
11,017
private void renderState ( FacesContext context ) throws IOException { PartialViewContext pvc = context . getPartialViewContext ( ) ; PartialResponseWriter writer = pvc . getPartialResponseWriter ( ) ; String viewStateId = Util . getViewStateId ( context ) ; writer . startUpdate ( viewStateId ) ; String state = context . getApplication ( ) . getStateManager ( ) . getViewState ( context ) ; writer . write ( state ) ; writer . endUpdate ( ) ; ClientWindow window = context . getExternalContext ( ) . getClientWindow ( ) ; if ( null != window ) { String clientWindowId = Util . getClientWindowId ( context ) ; writer . startUpdate ( clientWindowId ) ; writer . write ( window . getId ( ) ) ; writer . endUpdate ( ) ; } }
Copied from com . sun . faces . context . PartialViewContextImpl . May have to be adapted to future Mojarra or JSF versions .
11,018
public static Map < String , String > formatExportedVars ( Instance instance ) { Map < String , String > exportedVars = new HashMap < > ( ) ; for ( Instance inst = instance ; inst != null ; inst = inst . getParent ( ) ) { String prefix = "" ; if ( inst != instance ) prefix = "ANCESTOR_" + inst . getComponent ( ) . getName ( ) + "_" ; Map < String , String > exports = InstanceHelpers . findAllExportedVariables ( inst ) ; for ( Entry < String , String > entry : exports . entrySet ( ) ) { String vname = prefix + VariableHelpers . parseVariableName ( entry . getKey ( ) ) . getValue ( ) ; vname = vname . replaceAll ( "(-|%s)+" , "_" ) ; exportedVars . put ( vname , entry . getValue ( ) ) ; } } return exportedVars ; }
Formats imported variables to be used in a script as environment variables .
11,019
public static void setScriptsExecutable ( File fileOrDir ) { List < File > files = new ArrayList < > ( ) ; if ( fileOrDir . isDirectory ( ) ) files . addAll ( Utils . listAllFiles ( fileOrDir , true ) ) ; else files . add ( fileOrDir ) ; for ( File f : files ) f . setExecutable ( true ) ; }
Recursively sets all files and directories executable starting from a file or base directory .
11,020
public void switchMessagingType ( String factoryName ) { this . logger . fine ( "The messaging is requested to switch its type to " + factoryName + "." ) ; JmxWrapperForMessagingClient newMessagingClient = null ; try { IMessagingClient rawClient = createMessagingClient ( factoryName ) ; if ( rawClient != null ) { newMessagingClient = new JmxWrapperForMessagingClient ( rawClient ) ; newMessagingClient . setMessageQueue ( this . messageProcessor . getMessageQueue ( ) ) ; openConnection ( newMessagingClient ) ; } } catch ( Exception e ) { this . logger . warning ( "An error occurred while creating a new messaging client. " + e . getMessage ( ) ) ; Utils . logException ( this . logger , e ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "\n\n**** WARNING ****\n" ) ; sb . append ( "Connection failed at " ) ; sb . append ( new SimpleDateFormat ( "HH:mm:ss, 'on' EEEE dd (MMMM)" ) . format ( new Date ( ) ) ) ; sb . append ( ".\n" ) ; sb . append ( "The messaging configuration may be invalid.\n" ) ; sb . append ( "Or the messaging server may not be started yet.\n\n" ) ; sb . append ( "Consider using the 'roboconf:force-reconnect' command if you forgot to start the messaging server.\n" ) ; sb . append ( "**** WARNING ****\n" ) ; this . console . println ( sb . toString ( ) ) ; } IMessagingClient oldClient ; synchronized ( this ) { this . messagingType = factoryName ; oldClient = this . messagingClient ; if ( newMessagingClient != null ) this . messagingClient = newMessagingClient ; else resetInternalClient ( ) ; } terminateClient ( oldClient , "The previous client could not be terminated correctly." , this . logger ) ; }
Changes the internal messaging client .
11,021
protected IMessagingClient createMessagingClient ( String factoryName ) throws IOException { IMessagingClient client = null ; MessagingClientFactoryRegistry registry = getRegistry ( ) ; if ( registry != null ) { IMessagingClientFactory factory = registry . getMessagingClientFactory ( factoryName ) ; if ( factory != null ) client = factory . createClient ( this ) ; } return client ; }
Creates a new messaging client .
11,022
static void terminateClient ( IMessagingClient client , String errorMessage , Logger logger ) { try { logger . fine ( "The reconfigurable client is requesting its internal connection to be closed." ) ; if ( client != null ) client . closeConnection ( ) ; } catch ( Exception e ) { logger . warning ( errorMessage + " " + e . getMessage ( ) ) ; Utils . logException ( logger , e ) ; } finally { if ( client instanceof JmxWrapperForMessagingClient ) ( ( JmxWrapperForMessagingClient ) client ) . unregisterService ( ) ; } }
Closes the connection of a messaging client and terminates it properly .
11,023
public static int computeShapeWidth ( AbstractType type ) { Font font = GraphUtils . getDefaultFont ( ) ; BufferedImage img = new BufferedImage ( 1 , 1 , BufferedImage . TYPE_INT_ARGB ) ; FontMetrics fm = img . getGraphics ( ) . getFontMetrics ( font ) ; int width = fm . stringWidth ( type . getName ( ) ) ; width = Math . max ( width , 80 ) + 20 ; return width ; }
Computes the width of a shape for a given component or facet .
11,024
public static void writeGraph ( File outputFile , Component selectedComponent , Layout < AbstractType , String > layout , Graph < AbstractType , String > graph , AbstractEdgeShapeTransformer < AbstractType , String > edgeShapeTransformer , Map < String , String > options ) throws IOException { VisualizationImageServer < AbstractType , String > vis = new VisualizationImageServer < AbstractType , String > ( layout , layout . getSize ( ) ) ; vis . setBackground ( Color . WHITE ) ; vis . getRenderContext ( ) . setEdgeLabelTransformer ( new NoStringLabeller ( ) ) ; vis . getRenderContext ( ) . setEdgeShapeTransformer ( edgeShapeTransformer ) ; vis . getRenderContext ( ) . setVertexLabelTransformer ( new ToStringLabeller < AbstractType > ( ) ) ; vis . getRenderContext ( ) . setVertexShapeTransformer ( new VertexShape ( ) ) ; vis . getRenderContext ( ) . setVertexFontTransformer ( new VertexFont ( ) ) ; Color defaultBgColor = decode ( options . get ( DocConstants . OPTION_IMG_BACKGROUND_COLOR ) , DocConstants . DEFAULT_BACKGROUND_COLOR ) ; Color highlightBgcolor = decode ( options . get ( DocConstants . OPTION_IMG_HIGHLIGHT_BG_COLOR ) , DocConstants . DEFAULT_HIGHLIGHT_BG_COLOR ) ; vis . getRenderContext ( ) . setVertexFillPaintTransformer ( new VertexColor ( selectedComponent , defaultBgColor , highlightBgcolor ) ) ; Color defaultFgColor = decode ( options . get ( DocConstants . OPTION_IMG_FOREGROUND_COLOR ) , DocConstants . DEFAULT_FOREGROUND_COLOR ) ; vis . getRenderContext ( ) . setVertexLabelRenderer ( new MyVertexLabelRenderer ( selectedComponent , defaultFgColor ) ) ; vis . getRenderer ( ) . getVertexLabelRenderer ( ) . setPosition ( Position . CNTR ) ; BufferedImage image = ( BufferedImage ) vis . getImage ( new Point2D . Double ( layout . getSize ( ) . getWidth ( ) / 2 , layout . getSize ( ) . getHeight ( ) / 2 ) , new Dimension ( layout . getSize ( ) ) ) ; ImageIO . write ( image , "png" , outputFile ) ; }
Writes a graph as a PNG image .
11,025
static Color decode ( String value , String defaultValue ) { Color result ; try { result = Color . decode ( value ) ; } catch ( NumberFormatException e ) { Logger logger = Logger . getLogger ( GraphUtils . class . getName ( ) ) ; logger . severe ( "The specified color " + value + " could not be parsed. Back to default value: " + defaultValue ) ; Utils . logException ( logger , e ) ; result = Color . decode ( defaultValue ) ; } return result ; }
Decodes an hexadecimal color and resolves it as an AWT color .
11,026
public AgentProperties findParametersForAmazonOrOpenStack ( Logger logger ) { logger . info ( "User data are being retrieved for AWS / Openstack..." ) ; String userData = Utils . readUrlContentQuietly ( "http://169.254.169.254/latest/user-data" , logger ) ; String ip = Utils . readUrlContentQuietly ( "http://169.254.169.254/latest/meta-data/public-ipv4" , logger ) ; AgentProperties result = null ; try { result = AgentProperties . readIaasProperties ( userData , logger ) ; if ( ! AgentUtils . isValidIP ( ip ) ) { ip = Utils . readUrlContentQuietly ( "http://169.254.169.254/latest/meta-data/local-ipv4" , logger ) ; } if ( AgentUtils . isValidIP ( ip ) ) result . setIpAddress ( ip ) ; else logger . severe ( "No IP address could be retrieved (either public-ipv4 or local-ipv4)." ) ; } catch ( IOException e ) { logger . severe ( "The network properties could not be read. " + e . getMessage ( ) ) ; Utils . logException ( logger , e ) ; } return result ; }
Configures the agent from a IaaS registry .
11,027
public AgentProperties findParametersForAzure ( Logger logger ) { logger . info ( "User data are being retrieved for Microsoft Azure..." ) ; String userData = "" ; try { String userDataEncoded = getValueOfTagInXMLFile ( "/var/lib/waagent/ovf-env.xml" , "CustomData" ) ; userData = new String ( Base64 . decodeBase64 ( userDataEncoded . getBytes ( StandardCharsets . UTF_8 ) ) , "UTF-8" ) ; } catch ( IOException | ParserConfigurationException | SAXException e ) { logger . severe ( "The agent properties could not be read. " + e . getMessage ( ) ) ; Utils . logException ( logger , e ) ; } AgentProperties result = null ; String publicIPAddress ; try { result = AgentProperties . readIaasProperties ( userData , logger ) ; publicIPAddress = getSpecificAttributeOfTagInXMLFile ( "/var/lib/waagent/SharedConfig.xml" , "Endpoint" , "loadBalancedPublicAddress" ) ; result . setIpAddress ( publicIPAddress ) ; } catch ( ParserConfigurationException | SAXException e ) { logger . severe ( "The agent could not retrieve a public IP address. " + e . getMessage ( ) ) ; Utils . logException ( logger , e ) ; } catch ( IOException e ) { logger . severe ( "The agent could not retrieve its configuration. " + e . getMessage ( ) ) ; Utils . logException ( logger , e ) ; } return result ; }
Configures the agent from Azure .
11,028
public AgentProperties findParametersForVmware ( Logger logger ) { logger . info ( "User data are being retrieved for VMWare..." ) ; AgentProperties result = null ; File propertiesFile = new File ( "/tmp/roboconf.properties" ) ; try { int retries = 30 ; while ( ( ! propertiesFile . exists ( ) || ! propertiesFile . canRead ( ) ) && retries -- > 0 ) { logger . fine ( "Agent tries to read properties file " + propertiesFile + ": trial #" + ( 30 - retries ) ) ; try { Thread . sleep ( 2000 ) ; } catch ( InterruptedException e ) { throw new IOException ( "Cannot read properties file: " + e ) ; } } result = AgentProperties . readIaasProperties ( Utils . readPropertiesFile ( propertiesFile ) ) ; InputStream in = null ; try { URL userDataUrl = new URL ( "http://169.254.169.254/latest/meta-data/public-ipv4" ) ; in = userDataUrl . openStream ( ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; Utils . copyStreamSafely ( in , os ) ; String ip = os . toString ( "UTF-8" ) ; if ( ! AgentUtils . isValidIP ( ip ) ) { Utils . closeQuietly ( in ) ; userDataUrl = new URL ( "http://169.254.169.254/latest/meta-data/local-ipv4" ) ; in = userDataUrl . openStream ( ) ; os = new ByteArrayOutputStream ( ) ; Utils . copyStreamSafely ( in , os ) ; ip = os . toString ( "UTF-8" ) ; } if ( AgentUtils . isValidIP ( ip ) ) result . setIpAddress ( os . toString ( "UTF-8" ) ) ; } catch ( IOException e ) { Utils . logException ( logger , e ) ; } finally { Utils . closeQuietly ( in ) ; } } catch ( IOException e ) { logger . fine ( "Agent failed to read properties file " + propertiesFile ) ; result = null ; } return result ; }
Configures the agent from VMWare .
11,029
public AgentProperties findParametersFromUrl ( String url , Logger logger ) { logger . info ( "User data are being retrieved from URL: " + url ) ; AgentProperties result = null ; try { URI uri = UriUtils . urlToUri ( url ) ; Properties props = new Properties ( ) ; InputStream in = null ; try { in = uri . toURL ( ) . openStream ( ) ; props . load ( in ) ; } finally { Utils . closeQuietly ( in ) ; } result = AgentProperties . readIaasProperties ( props ) ; } catch ( Exception e ) { logger . fine ( "Agent parameters could not be read from " + url ) ; result = null ; } return result ; }
Retrieve the agent s configuration from an URL .
11,030
public void reconfigureMessaging ( String etcDir , Map < String , String > msgData ) throws IOException { String messagingType = msgData . get ( MessagingConstants . MESSAGING_TYPE_PROPERTY ) ; Logger . getLogger ( getClass ( ) . getName ( ) ) . fine ( "Messaging type for reconfiguration: " + messagingType ) ; if ( ! Utils . isEmptyOrWhitespaces ( etcDir ) && ! Utils . isEmptyOrWhitespaces ( messagingType ) ) { File f = new File ( etcDir , "net.roboconf.messaging." + messagingType + ".cfg" ) ; Logger logger = Logger . getLogger ( getClass ( ) . getName ( ) ) ; Properties props = Utils . readPropertiesFileQuietly ( f , logger ) ; props . putAll ( msgData ) ; props . remove ( MessagingConstants . MESSAGING_TYPE_PROPERTY ) ; Utils . writePropertiesFile ( props , f ) ; f = new File ( etcDir , Constants . KARAF_CFG_FILE_AGENT ) ; props = Utils . readPropertiesFileQuietly ( f , Logger . getLogger ( getClass ( ) . getName ( ) ) ) ; if ( messagingType != null ) { props . put ( Constants . MESSAGING_TYPE , messagingType ) ; Utils . writePropertiesFile ( props , f ) ; } } }
Reconfigures the messaging .
11,031
public static String findInstanceName ( String instancePath ) { String instanceName = "" ; Matcher m = Pattern . compile ( "([^/]+)$" ) . matcher ( instancePath ) ; if ( m . find ( ) ) instanceName = m . group ( 1 ) ; return instanceName ; }
Finds the name of an instance from its path .
11,032
public static List < Instance > findInstancesByComponentName ( AbstractApplication application , String componentName ) { List < Instance > result = new ArrayList < > ( ) ; for ( Instance inst : getAllInstances ( application ) ) { if ( componentName . equals ( inst . getComponent ( ) . getName ( ) ) ) result . add ( inst ) ; } return result ; }
Finds instances by component name .
11,033
public static Instance findRootInstance ( Instance instance ) { Instance rootInstance = instance ; while ( rootInstance . getParent ( ) != null ) rootInstance = rootInstance . getParent ( ) ; return rootInstance ; }
Finds the root instance for an instance .
11,034
public static List < Instance > findAllScopedInstances ( AbstractApplication app ) { List < Instance > instanceList = new ArrayList < > ( ) ; List < Instance > todo = new ArrayList < > ( ) ; todo . addAll ( app . getRootInstances ( ) ) ; while ( ! todo . isEmpty ( ) ) { Instance current = todo . remove ( 0 ) ; todo . addAll ( current . getChildren ( ) ) ; if ( isTarget ( current ) ) instanceList . add ( current ) ; } return instanceList ; }
Finds all the scoped instances from an application .
11,035
public static List < Instance > getAllInstances ( AbstractApplication application ) { List < Instance > result = new ArrayList < > ( ) ; for ( Instance instance : application . getRootInstances ( ) ) result . addAll ( InstanceHelpers . buildHierarchicalList ( instance ) ) ; return result ; }
Gets all the instances of an application .
11,036
public static boolean hasChildWithThisName ( AbstractApplication application , Instance parentInstance , String nameToSearch ) { boolean hasAlreadyAChildWithThisName = false ; Collection < Instance > list = parentInstance == null ? application . getRootInstances ( ) : parentInstance . getChildren ( ) ; for ( Iterator < Instance > it = list . iterator ( ) ; it . hasNext ( ) && ! hasAlreadyAChildWithThisName ; ) { hasAlreadyAChildWithThisName = Objects . equals ( nameToSearch , it . next ( ) . getName ( ) ) ; } return hasAlreadyAChildWithThisName ; }
Determines whether an instance name is not already used by a sibling instance .
11,037
public static File findInstanceDirectoryOnAgent ( Instance instance ) { String path = InstanceHelpers . computeInstancePath ( instance ) ; path = path . substring ( 1 ) . replace ( '/' , '_' ) . replace ( ' ' , '_' ) ; String installerName = ComponentHelpers . findComponentInstaller ( instance . getComponent ( ) ) ; return new File ( Constants . WORK_DIRECTORY_AGENT , installerName + "/" + path ) ; }
Finds the directory where an agent stores the files for a given instance .
11,038
public static boolean isTarget ( Instance instance ) { return instance . getComponent ( ) != null && ComponentHelpers . isTarget ( instance . getComponent ( ) ) ; }
Determines whether an instances is associated with the target installer or not .
11,039
public static String findRootInstancePath ( String scopedInstancePath ) { String result ; if ( Utils . isEmptyOrWhitespaces ( scopedInstancePath ) ) { result = "" ; } else if ( scopedInstancePath . contains ( "/" ) ) { String s = scopedInstancePath . replaceFirst ( "^/*" , "" ) ; int index = s . indexOf ( '/' ) ; result = index > 0 ? s . substring ( 0 , index ) : s ; } else { result = scopedInstancePath ; } return result ; }
Finds the root instance s path from another instance path .
11,040
public static boolean isDartControllerActive ( ) { Map < String , Object > sessionMap = FacesContext . getCurrentInstance ( ) . getExternalContext ( ) . getSessionMap ( ) ; if ( sessionMap . containsKey ( DART_CONTROLLER ) ) { return "true" . equals ( sessionMap . get ( DART_CONTROLLER ) ) ; } return false ; }
Are we to support AngularDart instead of AngularJS?
11,041
public static void setControllerName ( String name ) { Map < String , Object > sessionMap = FacesContext . getCurrentInstance ( ) . getExternalContext ( ) . getSessionMap ( ) ; sessionMap . put ( DART_CONTROLLER_NAME , name ) ; }
Sets the name of the Dart controller name as defined in the dart file (
11,042
public static String uncommentLine ( String line ) { String result = line ; if ( ! Utils . isEmptyOrWhitespaces ( line ) && line . trim ( ) . startsWith ( ParsingConstants . COMMENT_DELIMITER ) ) result = line . replaceFirst ( "^(\\s*)" + ParsingConstants . COMMENT_DELIMITER + "+" , "$1" ) ; return result ; }
Uncomments a line .
11,043
public void parse ( String line , File sourceFile , int lineNumber ) { this . rawNameToVariables . clear ( ) ; this . errors . clear ( ) ; this . cursor = 0 ; while ( this . cursor < line . length ( ) ) { char c = line . charAt ( this . cursor ) ; if ( Character . isWhitespace ( c ) || c == ',' ) this . cursor ++ ; recognizeVariable ( line , sourceFile , lineNumber ) ; } }
Parses a line and extracts exported variables .
11,044
public List < TargetWrapperDescriptor > listAllTargets ( ) { this . logger . finer ( "Listing all the available targets." ) ; WebResource path = this . resource . path ( UrlConstants . TARGETS ) ; List < TargetWrapperDescriptor > result = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . type ( MediaType . APPLICATION_JSON ) . get ( new GenericType < List < TargetWrapperDescriptor > > ( ) { } ) ; if ( result != null ) this . logger . finer ( result . size ( ) + " target descriptors were found." ) ; else this . logger . finer ( "No target descriptor was found." ) ; return result != null ? result : new ArrayList < TargetWrapperDescriptor > ( 0 ) ; }
Lists all the targets .
11,045
public String createTarget ( String targetContent ) throws TargetWsException { this . logger . finer ( "Creating a new target." ) ; WebResource path = this . resource . path ( UrlConstants . TARGETS ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . post ( ClientResponse . class , targetContent ) ; handleResponse ( response ) ; return response . getEntity ( String . class ) ; }
Creates a new target .
11,046
public void deleteTarget ( String targetId ) throws TargetWsException { this . logger . finer ( "Deleting target " + targetId ) ; WebResource path = this . resource . path ( UrlConstants . TARGETS ) . path ( targetId ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . delete ( ClientResponse . class ) ; handleResponse ( response ) ; }
Deletes a target .
11,047
public void associateTarget ( AbstractApplication app , String instancePathOrComponentName , String targetId , boolean bind ) throws TargetWsException { if ( bind ) this . logger . finer ( "Associating " + app + " :: " + instancePathOrComponentName + " with " + targetId ) ; else this . logger . finer ( "Dissociating " + app + " :: " + instancePathOrComponentName + " from " + targetId ) ; WebResource path = this . resource . path ( UrlConstants . TARGETS ) . path ( targetId ) . path ( "associations" ) . queryParam ( "bind" , Boolean . toString ( bind ) ) . queryParam ( "name" , app . getName ( ) ) ; if ( instancePathOrComponentName != null ) path = path . queryParam ( "elt" , instancePathOrComponentName ) ; if ( app instanceof ApplicationTemplate ) path = path . queryParam ( "qualifier" , ( ( ApplicationTemplate ) app ) . getVersion ( ) ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . post ( ClientResponse . class ) ; handleResponse ( response ) ; }
Associates or dissociates an application and a target .
11,048
public Row addColumn ( int index , String name , Object value ) { Objects . requireNonNull ( name , "Name of the column cannot be null" ) ; Objects . requireNonNull ( value , "Value of " + name + " cannot be null" ) ; final Column column = new Column ( index , name , value ) ; return this . addColumn ( column ) ; }
Adds or overrides a column with a default destination
11,049
public static Object selectObject ( Node node , String xpathQuery ) { Object result = node . selectObject ( xpathQuery ) ; if ( result != null && result instanceof Collection && ( ( Collection ) result ) . isEmpty ( ) ) { return null ; } else { return result ; } }
Executes an XPath query to retrieve an object . Normally if the XPath result doesn t have a result an empty collection is returned . This object checks that case and returns null accordingly .
11,050
public static String selectSingleNodeValue ( Node node , String xpathQuery ) { Node resultNode = node . selectSingleNode ( xpathQuery ) ; if ( resultNode != null ) { return resultNode . getText ( ) ; } else { return null ; } }
Executes the specified XPath query as a single node query returning the text value of the resulting single node .
11,051
@ SuppressWarnings ( "unchecked" ) public static List < String > selectNodeValues ( Node node , String xpathQuery ) { List < Node > resultNodes = node . selectNodes ( xpathQuery ) ; return extractNodeValues ( resultNodes ) ; }
Executes the specified XPath query as a multiple node query returning the text values of the resulting list of nodes .
11,052
public static List < String > selectNodeValues ( Node node , String xpathQuery , Map < String , String > namespaceUris ) { List < Node > resultNodes = selectNodes ( node , xpathQuery , namespaceUris ) ; return extractNodeValues ( resultNodes ) ; }
Executes the specified namespace aware XPath query as a multiple node query returning the text values of the resulting list of nodes .
11,053
public static Node selectSingleNode ( Node node , String xpathQuery , Map < String , String > namespaceUris ) { XPath xpath = DocumentHelper . createXPath ( xpathQuery ) ; xpath . setNamespaceURIs ( namespaceUris ) ; return xpath . selectSingleNode ( node ) ; }
Executes the specified namespace aware XPath query as a single node query returning the resulting single node .
11,054
@ SuppressWarnings ( "unchecked" ) public static List < Node > selectNodes ( Node node , String xpathQuery , Map < String , String > namespaceUris ) { XPath xpath = DocumentHelper . createXPath ( xpathQuery ) ; xpath . setNamespaceURIs ( namespaceUris ) ; return xpath . selectNodes ( node ) ; }
Executes the specified namespace aware XPath query as a multiple node query returning the resulting list of nodes .
11,055
public static String documentToPrettyString ( Document document ) { StringWriter stringWriter = new StringWriter ( ) ; OutputFormat prettyPrintFormat = OutputFormat . createPrettyPrint ( ) ; XMLWriter xmlWriter = new XMLWriter ( stringWriter , prettyPrintFormat ) ; try { xmlWriter . write ( document ) ; } catch ( IOException e ) { } return stringWriter . toString ( ) ; }
Returns the given document as a XML string in a pretty format .
11,056
public String queryDescriptorValue ( String xpathQuery ) { if ( descriptorDom != null ) { String value = ( String ) getProperty ( xpathQuery ) ; if ( value == null ) { value = XmlUtils . selectSingleNodeValue ( descriptorDom , xpathQuery ) ; } return value ; } else { return null ; } }
Queries a single descriptor node text value . First looks in the properties if not found it executes the XPath query .
11,057
@ SuppressWarnings ( "unchecked" ) public List < String > queryDescriptorValues ( String xpathQuery ) { if ( descriptorDom != null ) { List < String > value = ( List < String > ) getProperty ( xpathQuery ) ; if ( CollectionUtils . isEmpty ( value ) ) { value = XmlUtils . selectNodeValues ( descriptorDom , xpathQuery ) ; } return value ; } else { return Collections . emptyList ( ) ; } }
Queries multiple descriptor node text values . First looks in the properties if not found it executes the XPath query .
11,058
public void addProcessor ( ItemProcessor processor ) { if ( processors == null ) { processors = new ArrayList < > ( ) ; } processors . add ( processor ) ; }
Adds a processor to the pipeline of processors .
11,059
public void addProcessors ( Collection < ItemProcessor > processors ) { if ( processors == null ) { processors = new ArrayList < > ( ) ; } processors . addAll ( processors ) ; }
Adds several processors to the pipeline of processors .
11,060
protected SAXReader createXmlReader ( ) { SAXReader xmlReader = new SAXReader ( ) ; xmlReader . setMergeAdjacentText ( true ) ; xmlReader . setStripWhitespaceText ( true ) ; xmlReader . setIgnoreComments ( true ) ; try { xmlReader . setFeature ( "http://apache.org/xml/features/disallow-doctype-decl" , true ) ; xmlReader . setFeature ( "http://xml.org/sax/features/external-general-entities" , false ) ; xmlReader . setFeature ( "http://xml.org/sax/features/external-parameter-entities" , false ) ; } catch ( SAXException ex ) { LOGGER . error ( "Unable to turn off external entity loading, This could be a security risk." , ex ) ; } return xmlReader ; }
Creates and configures an XML SAX reader .
11,061
protected Map < String , Object > createMessageModel ( String attributeName , Object attributeValue ) { Map < String , Object > model = new HashMap < > ( 1 ) ; model . put ( attributeName , attributeValue ) ; return model ; }
Use instead of singleton model since it can modified
11,062
protected void addNewField ( Item item , String values ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Tagging item with field: " + newField + " and value: " + values ) ; } Document document = item . getDescriptorDom ( ) ; if ( document != null ) { Element root = document . getRootElement ( ) ; if ( root != null ) { for ( String value : values . split ( "," ) ) { Element newElement = root . addElement ( newField ) ; newElement . setText ( value ) ; } } } }
Tags the item adding the new field with the specified values .
11,063
public static String getShortName ( String longName , String containsShortNameRegex , int shortNameRegexGroup ) { Pattern pattern = Pattern . compile ( containsShortNameRegex ) ; Matcher matcher = pattern . matcher ( longName ) ; if ( matcher . matches ( ) ) { return matcher . group ( shortNameRegexGroup ) ; } else { return longName ; } }
Returns the short name representation of a long name .
11,064
public Configuration < T > setConfiguration ( Map < String , String > configuration ) { Validate . notNull ( configuration , "Properties for configuration of recorder extension can not be a null object!" ) ; this . configuration = configuration ; return this ; }
Gets configuration from Arquillian descriptor and creates instance of it .
11,065
public void setProperty ( String name , String value ) { Validate . notNullOrEmpty ( name , "Name of property can not be a null object nor an empty string!" ) ; Validate . notNull ( value , "Value of property can not be a null object!" ) ; configuration . put ( name , value ) ; }
Sets some property .
11,066
protected void writeTime ( Date start , Date stop , long duration ) throws IOException { writer . append ( "." ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.time" ) ) . append ( NEW_LINE ) ; writer . append ( "****" ) . append ( NEW_LINE ) ; writer . append ( "*" ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.start" ) ) . append ( "*" ) . append ( " " ) . append ( SIMPLE_DATE_FORMAT . format ( start ) ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "*" ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.stop" ) ) . append ( "*" ) . append ( " " ) . append ( SIMPLE_DATE_FORMAT . format ( stop ) ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "*" ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.duration" ) ) . append ( "*" ) . append ( " " ) . append ( convertDuration ( duration , TimeUnit . MILLISECONDS , TimeUnit . SECONDS ) ) . append ( "s" ) . append ( NEW_LINE ) ; writer . append ( "****" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; }
Method that is called to write test suite time to AsciiDoc document .
11,067
protected void writeDocumentHeader ( ) throws IOException { writer . append ( "= " ) . append ( this . configuration . getTitle ( ) ) . append ( NEW_LINE ) ; if ( isAttributesFileSet ( ) ) { writer . append ( "include::" ) . append ( this . configuration . getAsciiDocAttributesFile ( ) ) . append ( "[]" ) . append ( NEW_LINE ) ; } if ( isAsciidoctorOutput ( ) ) { writer . append ( ":icons: font" ) . append ( NEW_LINE ) ; } writer . append ( NEW_LINE ) ; }
First method called when report is being created . This method is used to set the document title and AsciiDoc document attributes .
11,068
protected void writeContainerProperties ( Map < String , String > properties ) throws IOException { if ( properties . size ( ) > 0 ) { writer . append ( "[cols=\"2*\", options=\"header\"]" ) . append ( NEW_LINE ) ; writer . append ( "." ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.properties" ) ) . append ( NEW_LINE ) ; writer . append ( "|===" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "|KEY" ) . append ( NEW_LINE ) ; writer . append ( "|VALUE" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; Set < Entry < String , String > > entrySet = properties . entrySet ( ) ; for ( Entry < String , String > entry : entrySet ) { writer . append ( "|" ) . append ( entry . getKey ( ) ) . append ( NEW_LINE ) ; writer . append ( "|" ) . append ( entry . getValue ( ) ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; } writer . append ( "|===" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; } }
Method that is called to write container properties to AsciiDoc document .
11,069
protected void writeProperties ( List < PropertyEntry > propertyEntries ) throws IOException { if ( containsAnyKeyValueEntryOrFileEntry ( propertyEntries ) ) { writer . append ( "[cols=\"2*\", options=\"header\"]" ) . append ( NEW_LINE ) ; writer . append ( "." ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.properties" ) ) . append ( NEW_LINE ) ; writer . append ( "|===" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "|KEY" ) . append ( NEW_LINE ) ; writer . append ( "|VALUE" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writePropertiesRows ( propertyEntries ) ; writer . append ( "|===" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; } writeTables ( propertyEntries ) ; }
Method that is called to write properties to AsciiDoc document .
11,070
protected void writeExtensions ( List < ExtensionReport > extensionReports ) throws IOException { writer . append ( "== " ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.extensions" ) ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; for ( ExtensionReport extensionReport : extensionReports ) { writer . append ( "[cols=\"2*\"]" ) . append ( NEW_LINE ) ; writer . append ( "." ) . append ( extensionReport . getQualifier ( ) ) . append ( NEW_LINE ) ; writer . append ( "|===" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "2+|" ) . append ( extensionReport . getQualifier ( ) ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "h|KEY" ) . append ( NEW_LINE ) ; writer . append ( "h|VALUE" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writeConfigurationRows ( extensionReport . getConfiguration ( ) ) ; writer . append ( "|===" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; } }
Method that is called to write extensions to AsciiDoc document .
11,071
protected void writeVideo ( VideoEntry videoEntry ) throws IOException { writer . append ( "video::" ) . append ( videoEntry . getLink ( ) ) . append ( "[]" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; }
Method that is called to write video .
11,072
protected void writeScreenshot ( ScreenshotEntry screenshotEntry ) throws IOException { int heigth = screenshotEntry . getHeight ( ) * Integer . parseInt ( this . configuration . getImageHeight ( ) ) / 100 ; int width = screenshotEntry . getWidth ( ) * Integer . parseInt ( this . configuration . getImageWidth ( ) ) / 100 ; boolean large = width > Integer . parseInt ( this . configuration . getMaxImageWidth ( ) ) ; if ( large ) { writer . append ( "." ) . append ( screenshotEntry . getPhase ( ) . name ( ) ) . append ( NEW_LINE ) ; writer . append ( screenshotEntry . getLink ( ) ) . append ( " -> file://" ) . append ( screenshotEntry . getPath ( ) ) . append ( "[" ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.screenshot" ) ) . append ( "]" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; } else { writer . append ( "." ) . append ( screenshotEntry . getPhase ( ) . name ( ) ) . append ( NEW_LINE ) ; writer . append ( "image::" ) . append ( screenshotEntry . getLink ( ) ) . append ( "[screenshot," + width + "," + heigth + "]" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; } }
Method that is called to write screenshot . This method is responsible to check the size of image .
11,073
protected void writeDeployments ( List < DeploymentReport > deploymentReports ) throws IOException { for ( DeploymentReport deploymentReport : deploymentReports ) { writer . append ( "[cols=\"3*\", options=\"header\"]" ) . append ( NEW_LINE ) ; writer . append ( "." ) . append ( this . resourceBundle . getString ( "asciidoc.reporter.deployment" ) ) . append ( NEW_LINE ) ; writer . append ( "|===" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "|NAME" ) . append ( NEW_LINE ) ; writer . append ( "|ARCHIVE" ) . append ( NEW_LINE ) ; writer . append ( "|ORDER" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "|" ) . append ( deploymentReport . getName ( ) ) . append ( NEW_LINE ) ; writer . append ( "|" ) . append ( deploymentReport . getArchiveName ( ) ) . append ( NEW_LINE ) ; writer . append ( "|" ) . append ( Integer . toString ( deploymentReport . getOrder ( ) ) ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; writer . append ( "|===" ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; if ( ! "_DEFAULT_" . equals ( deploymentReport . getProtocol ( ) ) ) { writer . append ( "NOTE: " ) . append ( deploymentReport . getProtocol ( ) ) . append ( NEW_LINE ) . append ( NEW_LINE ) ; } } }
Method that is called to write deployment information to AsciiDoc document .
11,074
public void setMaxImageWidth ( String maxImageWidth ) { try { if ( Integer . parseInt ( maxImageWidth ) > 0 ) { this . maxImageWidth = maxImageWidth ; } } catch ( NumberFormatException ex ) { LOGGER . info ( String . format ( "You are trying to parse '%s' as a number for maxImageWidth." , maxImageWidth ) ) ; } }
String has to be given as an integer number bigger than 0 .
11,075
private void validatePath ( PropertyEntry entry ) { if ( entry instanceof VideoEntry ) { VideoEntry e = ( VideoEntry ) entry ; if ( e . getPath ( ) . contains ( configuration . getRootDir ( ) . getAbsolutePath ( ) ) ) { e . setLink ( e . getPath ( ) . substring ( configuration . getRootDir ( ) . getAbsolutePath ( ) . length ( ) + 1 ) ) ; } } else if ( entry instanceof ScreenshotEntry ) { ScreenshotEntry e = ( ScreenshotEntry ) entry ; if ( e . getPath ( ) . contains ( configuration . getRootDir ( ) . getAbsolutePath ( ) ) ) { e . setLink ( e . getPath ( ) . substring ( configuration . getRootDir ( ) . getAbsolutePath ( ) . length ( ) + 1 ) ) ; } } }
Validates if the file path is in absolute form and if so relativize it .
11,076
public void write ( String filename , String content ) throws IOException { FSDataOutputStream s = getMfs ( ) . create ( new Path ( filename ) ) ; s . writeBytes ( content ) ; s . close ( ) ; }
Writes the following content to the Hadoop cluster .
11,077
public void copyResource ( String filename , String resource ) throws IOException { write ( filename , IOUtils . toByteArray ( getClass ( ) . getResource ( resource ) ) ) ; }
Copies the content of the given resource into Hadoop .
11,078
public String read ( String filename ) throws IOException { Path p = new Path ( filename ) ; int size = ( int ) getMfs ( ) . getFileStatus ( p ) . getLen ( ) ; FSDataInputStream is = getMfs ( ) . open ( p ) ; byte [ ] content = new byte [ size ] ; is . readFully ( content ) ; return new String ( content ) ; }
Fully reads the content of the given file .
11,079
public boolean exists ( Path filename ) throws IOException { try { return getMfs ( ) . listFiles ( filename , true ) . hasNext ( ) ; } catch ( FileNotFoundException e ) { return false ; } }
Checks if the given path exists on Hadoop .
11,080
public static < T extends ExecutorService > T requireNotShutdown ( final T executorService ) { if ( executorService . isShutdown ( ) ) { throw new IllegalArgumentException ( "ExecutorService is shutdown" ) ; } return executorService ; }
Validates the supplied service is not shutdown .
11,081
public static RootContainer getRootContainer ( final EntityContainer container ) { if ( ! ( container instanceof Identifiable ) ) { return null ; } EntityContainer parent = container instanceof Entity ? ( ( Entity ) container ) . getContainer ( ) : null ; UUID rootID = null ; if ( parent == null ) { rootID = ( ( Identifiable ) container ) . getID ( ) ; } else if ( container instanceof Taggable ) { final RootContainer parentRoot = ( ( Taggable ) container ) . getSingletonTag ( RootContainer . class ) ; if ( parentRoot != null ) { rootID = parentRoot . getValue ( ) ; } } if ( rootID == null ) { while ( parent instanceof Entity ) { final Entity e = ( Entity ) parent ; rootID = e . getID ( ) ; parent = e . getContainer ( ) ; } if ( ! ( parent instanceof Identifiable ) ) { return null ; } } return new RootContainer ( rootID ) ; }
Gets or calculates the root container .
11,082
protected void reset ( ) { done . set ( false ) ; performing . set ( false ) ; cancelled . set ( false ) ; estimated . set ( 0L ) ; }
Resets the context to its starting state .
11,083
public synchronized void start ( ) throws Exception { if ( running ) { return ; } List < Connector > startedConnectors = new ArrayList < Connector > ( ) ; for ( Connector each : this . connectors ) { try { each . setServer ( this ) ; each . start ( ) ; startedConnectors . add ( each ) ; } catch ( Exception e ) { for ( Connector stop : startedConnectors ) { try { stop . stop ( ) ; } catch ( Exception e2 ) { } } throw e ; } } running = true ; }
Start this server .
11,084
public synchronized void stop ( ) throws Exception { if ( ! running ) { return ; } for ( Connector each : this . connectors ) { try { each . stop ( ) ; each . setServer ( null ) ; } catch ( Exception e ) { } } running = false ; }
Stop this server .
11,085
public void cancelAllScheduledForActor ( ) { final Set < ActionContext < T > > toCancel ; synchronized ( contexts ) { toCancel = new HashSet < > ( contexts ) ; contexts . clear ( ) ; } toCancel . forEach ( cxt -> { if ( ! cxt . isDone ( ) ) { cxt . cancel ( ) ; } } ) ; }
Cancel all tasks scheduled to the current engine for the actor by this scheduler .
11,086
protected Future < ? > getFuture ( ) { long stamp = lock . tryOptimisticRead ( ) ; Future < ? > future = this . future ; if ( ! lock . validate ( stamp ) ) { stamp = lock . readLock ( ) ; try { future = this . future ; } finally { lock . unlockRead ( stamp ) ; } } return future ; }
Gets the future associated to the action task .
11,087
protected void setFuture ( final Future < ? > future ) { final long stamp = lock . writeLock ( ) ; try { this . future = future ; } finally { lock . unlockWrite ( stamp ) ; } }
Sets the future of the associated action task .
11,088
public static Object defaultValue ( final Class < ? > type ) { final Object value = WRAPPER_DEFAULTS . get ( Objects . requireNonNull ( type ) ) ; if ( value == null ) { throw new IllegalArgumentException ( "Not primitive wrapper" ) ; } return value ; }
Gets the default value for a primitive wrapper .
11,089
public static Type firstGenericTypeArg ( final Type pt ) { return pt instanceof ParameterizedType ? ( ( ParameterizedType ) pt ) . getActualTypeArguments ( ) [ 0 ] : null ; }
Gets the first generic type argument for a parameterised type .
11,090
public static Supplier < UUID > getSingleIDSupplier ( final Method m ) throws IllegalArgumentException { final EntityID [ ] entityIDs = m . getAnnotationsByType ( EntityID . class ) ; if ( entityIDs . length > 1 ) { throw new IllegalArgumentException ( "Cannot have more than one entity ID" ) ; } Supplier < UUID > idSupplier = null ; if ( entityIDs . length == 1 ) { idSupplier = toIDSupplier ( entityIDs [ 0 ] ) ; } return idSupplier ; }
Gets a single ID supplier from a method .
11,091
public static boolean returnTypeIs ( final Method m , final Class < ? > clazz ) { return clazz . equals ( toClass ( m . getGenericReturnType ( ) ) ) ; }
Whether the method return type matches the supplied type .
11,092
public static Class < ? > wrap ( final Class < ? > type ) { if ( ! type . isPrimitive ( ) ) { throw new IllegalArgumentException ( "Not primitive" ) ; } return PRIMITIVES_WRAPPERS . get ( type ) ; }
Gets the wrapper type for the primitive type .
11,093
public boolean containsOfType ( final Class < ? extends Tag > type ) { read . lock ( ) ; try { return tags . containsKey ( type ) ; } finally { read . unlock ( ) ; } }
Checks whether the tag set contains any tags of that type .
11,094
@ SuppressWarnings ( "unchecked" ) public < T extends Tag > Set < T > getOfType ( final Class < T > type ) { read . lock ( ) ; try { final Set < T > tagsOfType = ( Set < T > ) tags . get ( type ) ; return tagsOfType != null ? Collections . unmodifiableSet ( tagsOfType ) : Collections . emptySet ( ) ; } finally { read . unlock ( ) ; } }
Gets all of the tags matching the specified type .
11,095
public boolean removeOfType ( final Class < ? extends Tag > type ) { write . lock ( ) ; try { return tags . remove ( type ) != null ; } finally { write . unlock ( ) ; } }
Removes all tags of the specified type .
11,096
public static < T extends Entity > Optional < T > anyEntityOfType ( final EntityContainer container , final Class < T > type ) { return container . streamEntitiesOfType ( type ) . findAny ( ) ; }
Gets any entity within the container marked with the specified type .
11,097
public static boolean findEntityRecursively ( final EntityContainer container , final UUID id ) { final AtomicBoolean found = new AtomicBoolean ( ) ; walkEntityTree ( container , e -> { if ( id . equals ( e . getID ( ) ) ) { found . set ( true ) ; return EntityVisitResult . EXIT ; } else { return EntityVisitResult . CONTINUE ; } } ) ; return found . get ( ) ; }
Walks through the entity tree looking for an entity .
11,098
public static EntityContainer getRootContainer ( final EntityContainer container ) { Objects . requireNonNull ( container ) ; if ( container instanceof Entity ) { final EntityContainer parent = ( ( Entity ) container ) . getContainer ( ) ; if ( parent != null ) { return getRootContainer ( parent ) ; } } return container ; }
Gets the highest level parent of this container .
11,099
public static Predicate < Entity > isMarkedAsType ( final Class < ? extends Entity > type ) { return i -> i . isMarkedAsType ( type ) ; }
Checks to see if the entity has been tagged with the type .