idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
10,700
public final void evaluate ( ) { final POSEvaluator evaluator = new POSEvaluator ( this . posTagger ) ; try { evaluator . evaluate ( this . testSamples ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } System . out . println ( evaluator . getWordAccuracy ( ) ) ; }
Evaluate word accuracy .
10,701
public final void detailEvaluate ( ) { final List < EvaluationMonitor < POSSample > > listeners = new LinkedList < EvaluationMonitor < POSSample > > ( ) ; final POSTaggerFineGrainedReportListener detailedFListener = new POSTaggerFineGrainedReportListener ( System . out ) ; listeners . add ( detailedFListener ) ; final POSEvaluator evaluator = new POSEvaluator ( this . posTagger , listeners . toArray ( new POSTaggerEvaluationMonitor [ listeners . size ( ) ] ) ) ; try { evaluator . evaluate ( this . testSamples ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } detailedFListener . writeReport ( ) ; }
Detail evaluation of a model outputting the report a file .
10,702
private static Stream < Node > streamChildNodes ( Node node ) { int children = node . getChildNodes ( ) . getLength ( ) ; Node firstChild = node . getFirstChild ( ) ; if ( firstChild == null ) return Stream . empty ( ) ; return Stream . iterate ( firstChild , prev -> prev != null ? prev . getNextSibling ( ) : null ) . limit ( children ) . filter ( n -> n != null ) ; }
Needs to be thread - safe childNodes NodeList is not!
10,703
private static Stream < Node > streamAttributes ( Node node ) { final NamedNodeMap attributes = node . getAttributes ( ) ; if ( attributes == null ) return Stream . empty ( ) ; return IntStream . range ( 0 , attributes . getLength ( ) ) . mapToObj ( attributes :: item ) ; }
Needs to be thread - safe
10,704
protected void changeState ( final State newState ) { if ( state . compareAndSet ( newState . oppositeState ( ) , newState ) ) { changeSupport . firePropertyChange ( PROPERTY_NAME , ! isOpen ( newState ) , isOpen ( newState ) ) ; } }
Changes the internal state of this circuit breaker . If there is actually a change of the state value all registered change listeners are notified .
10,705
private static boolean isDelimiter ( final char ch , final char [ ] delimiters ) { if ( delimiters == null ) { return CharUtils . isWhitespace ( ch ) ; } for ( final char delimiter : delimiters ) { if ( ch == delimiter ) { return true ; } } return false ; }
Is the character a delimiter .
10,706
public T get ( ) throws ConcurrentException { T result = reference . get ( ) ; if ( result == null ) { result = initialize ( ) ; if ( ! reference . compareAndSet ( null , result ) ) { result = reference . get ( ) ; } } return result ; }
Returns the object managed by this initializer . The object is created if it is not available yet and stored internally . This method always returns the same object .
10,707
public final List < Morpheme > getMorphemes ( final String [ ] tokens , final String [ ] posTags ) { final List < String > lemmas = lemmatize ( tokens , posTags ) ; final List < Morpheme > morphemes = getMorphemesFromStrings ( tokens , posTags , lemmas ) ; return morphemes ; }
Get lemmas from a tokenized and pos tagged sentence .
10,708
public List < String > lemmatize ( String [ ] tokens , String [ ] posTags ) { String [ ] annotatedLemmas = lemmatizer . lemmatize ( tokens , posTags ) ; String [ ] decodedLemmas = lemmatizer . decodeLemmas ( tokens , annotatedLemmas ) ; final List < String > lemmas = new ArrayList < String > ( Arrays . asList ( decodedLemmas ) ) ; return lemmas ; }
Produce lemmas from a tokenized sentence and its postags .
10,709
private void initializeTransientFields ( final Class < L > listenerInterface , final ClassLoader classLoader ) { @ SuppressWarnings ( "unchecked" ) final L [ ] array = ( L [ ] ) Array . newInstance ( listenerInterface , 0 ) ; this . prototypeArray = array ; createProxy ( listenerInterface , classLoader ) ; }
Initialize transient fields .
10,710
private void createProxy ( final Class < L > listenerInterface , final ClassLoader classLoader ) { proxy = listenerInterface . cast ( Proxy . newProxyInstance ( classLoader , new Class [ ] { listenerInterface } , createInvocationHandler ( ) ) ) ; }
Create the proxy object .
10,711
@ GwtIncompatible ( "incompatible method" ) public final String translate ( final CharSequence input ) { if ( input == null ) { return null ; } try { final StringWriter writer = new StringWriter ( input . length ( ) * 2 ) ; translate ( input , writer ) ; return writer . toString ( ) ; } catch ( final IOException ioe ) { throw new RuntimeException ( ioe ) ; } }
Helper for non - Writer usage .
10,712
@ GwtIncompatible ( "incompatible method" ) private static boolean memberEquals ( final Class < ? > type , final Object o1 , final Object o2 ) { if ( o1 == o2 ) { return true ; } if ( o1 == null || o2 == null ) { return false ; } if ( type . isArray ( ) ) { return arrayMemberEquals ( type . getComponentType ( ) , o1 , o2 ) ; } if ( type . isAnnotation ( ) ) { return equals ( ( Annotation ) o1 , ( Annotation ) o2 ) ; } return o1 . equals ( o2 ) ; }
Helper method for checking whether two objects of the given type are equal . This method is used to compare the parameters of two annotation instances .
10,713
@ GwtIncompatible ( "incompatible method" ) private static boolean arrayMemberEquals ( final Class < ? > componentType , final Object o1 , final Object o2 ) { if ( componentType . isAnnotation ( ) ) { return annotationArrayMemberEquals ( ( Annotation [ ] ) o1 , ( Annotation [ ] ) o2 ) ; } if ( componentType . equals ( Byte . TYPE ) ) { return Arrays . equals ( ( byte [ ] ) o1 , ( byte [ ] ) o2 ) ; } if ( componentType . equals ( Short . TYPE ) ) { return Arrays . equals ( ( short [ ] ) o1 , ( short [ ] ) o2 ) ; } if ( componentType . equals ( Integer . TYPE ) ) { return Arrays . equals ( ( int [ ] ) o1 , ( int [ ] ) o2 ) ; } if ( componentType . equals ( Character . TYPE ) ) { return Arrays . equals ( ( char [ ] ) o1 , ( char [ ] ) o2 ) ; } if ( componentType . equals ( Long . TYPE ) ) { return Arrays . equals ( ( long [ ] ) o1 , ( long [ ] ) o2 ) ; } if ( componentType . equals ( Float . TYPE ) ) { return Arrays . equals ( ( float [ ] ) o1 , ( float [ ] ) o2 ) ; } if ( componentType . equals ( Double . TYPE ) ) { return Arrays . equals ( ( double [ ] ) o1 , ( double [ ] ) o2 ) ; } if ( componentType . equals ( Boolean . TYPE ) ) { return Arrays . equals ( ( boolean [ ] ) o1 , ( boolean [ ] ) o2 ) ; } return Arrays . equals ( ( Object [ ] ) o1 , ( Object [ ] ) o2 ) ; }
Helper method for comparing two objects of an array type .
10,714
@ GwtIncompatible ( "incompatible method" ) private static boolean annotationArrayMemberEquals ( final Annotation [ ] a1 , final Annotation [ ] a2 ) { if ( a1 . length != a2 . length ) { return false ; } for ( int i = 0 ; i < a1 . length ; i ++ ) { if ( ! equals ( a1 [ i ] , a2 [ i ] ) ) { return false ; } } return true ; }
Helper method for comparing two arrays of annotations .
10,715
private static int arrayMemberHash ( final Class < ? > componentType , final Object o ) { if ( componentType . equals ( Byte . TYPE ) ) { return Arrays . hashCode ( ( byte [ ] ) o ) ; } if ( componentType . equals ( Short . TYPE ) ) { return Arrays . hashCode ( ( short [ ] ) o ) ; } if ( componentType . equals ( Integer . TYPE ) ) { return Arrays . hashCode ( ( int [ ] ) o ) ; } if ( componentType . equals ( Character . TYPE ) ) { return Arrays . hashCode ( ( char [ ] ) o ) ; } if ( componentType . equals ( Long . TYPE ) ) { return Arrays . hashCode ( ( long [ ] ) o ) ; } if ( componentType . equals ( Float . TYPE ) ) { return Arrays . hashCode ( ( float [ ] ) o ) ; } if ( componentType . equals ( Double . TYPE ) ) { return Arrays . hashCode ( ( double [ ] ) o ) ; } if ( componentType . equals ( Boolean . TYPE ) ) { return Arrays . hashCode ( ( boolean [ ] ) o ) ; } return Arrays . hashCode ( ( Object [ ] ) o ) ; }
Helper method for generating a hash code for an array .
10,716
public static StrMatcher charSetMatcher ( final char ... chars ) { if ( chars == null || chars . length == 0 ) { return NONE_MATCHER ; } if ( chars . length == 1 ) { return new CharMatcher ( chars [ 0 ] ) ; } return new CharSetMatcher ( chars ) ; }
Constructor that creates a matcher from a set of characters .
10,717
public static StrMatcher charSetMatcher ( final String chars ) { if ( StringUtils . isEmpty ( chars ) ) { return NONE_MATCHER ; } if ( chars . length ( ) == 1 ) { return new CharMatcher ( chars . charAt ( 0 ) ) ; } return new CharSetMatcher ( chars . toCharArray ( ) ) ; }
Constructor that creates a matcher from a string representing a set of characters .
10,718
public static StrMatcher stringMatcher ( final String str ) { if ( StringUtils . isEmpty ( str ) ) { return NONE_MATCHER ; } return new StringMatcher ( str ) ; }
Constructor that creates a matcher from a string .
10,719
public final void evaluate ( ) { final LemmatizerEvaluator evaluator = new LemmatizerEvaluator ( this . lemmatizer ) ; try { evaluator . evaluate ( this . testSamples ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } System . out . println ( evaluator . getWordAccuracy ( ) ) ; }
Evaluate and print word accuracy .
10,720
private static String modify ( final String str , final String [ ] set , final boolean expect ) { final CharSet chars = CharSet . getInstance ( set ) ; final StringBuilder buffer = new StringBuilder ( str . length ( ) ) ; final char [ ] chrs = str . toCharArray ( ) ; for ( final char chr : chrs ) { if ( chars . contains ( chr ) == expect ) { buffer . append ( chr ) ; } } return buffer . toString ( ) ; }
Implementation of delete and keep
10,721
private static boolean deepEmpty ( final String [ ] strings ) { if ( strings != null ) { for ( final String s : strings ) { if ( StringUtils . isNotEmpty ( s ) ) { return false ; } } } return true ; }
Determines whether or not all the Strings in an array are empty or not .
10,722
private int readArgumentIndex ( final String pattern , final ParsePosition pos ) { final int start = pos . getIndex ( ) ; seekNonWs ( pattern , pos ) ; final StringBuilder result = new StringBuilder ( ) ; boolean error = false ; for ( ; ! error && pos . getIndex ( ) < pattern . length ( ) ; next ( pos ) ) { char c = pattern . charAt ( pos . getIndex ( ) ) ; if ( Character . isWhitespace ( c ) ) { seekNonWs ( pattern , pos ) ; c = pattern . charAt ( pos . getIndex ( ) ) ; if ( c != START_FMT && c != END_FE ) { error = true ; continue ; } } if ( ( c == START_FMT || c == END_FE ) && result . length ( ) > 0 ) { try { return Integer . parseInt ( result . toString ( ) ) ; } catch ( final NumberFormatException e ) { } } error = ! Character . isDigit ( c ) ; result . append ( c ) ; } if ( error ) { throw new IllegalArgumentException ( "Invalid format argument index at position " + start + ": " + pattern . substring ( start , pos . getIndex ( ) ) ) ; } throw new IllegalArgumentException ( "Unterminated format element at position " + start ) ; }
Read the argument index from the current format element
10,723
private String parseFormatDescription ( final String pattern , final ParsePosition pos ) { final int start = pos . getIndex ( ) ; seekNonWs ( pattern , pos ) ; final int text = pos . getIndex ( ) ; int depth = 1 ; for ( ; pos . getIndex ( ) < pattern . length ( ) ; next ( pos ) ) { switch ( pattern . charAt ( pos . getIndex ( ) ) ) { case START_FE : depth ++ ; break ; case END_FE : depth -- ; if ( depth == 0 ) { return pattern . substring ( text , pos . getIndex ( ) ) ; } break ; case QUOTE : getQuotedString ( pattern , pos ) ; break ; default : break ; } } throw new IllegalArgumentException ( "Unterminated format element at position " + start ) ; }
Parse the format component of a format element .
10,724
private boolean containsElements ( final Collection < ? > coll ) { if ( coll == null || coll . isEmpty ( ) ) { return false ; } for ( final Object name : coll ) { if ( name != null ) { return true ; } } return false ; }
Learn whether the specified Collection contains non - null elements .
10,725
public WnsNotificationResponse pushTile ( String channelUri , WnsTile tile ) throws WnsException { return this . pushTile ( channelUri , null , tile ) ; }
Pushes a tile to channelUri
10,726
public WnsNotificationResponse pushTile ( String channelUri , WnsNotificationRequestOptional optional , WnsTile tile ) throws WnsException { return this . client . push ( xmlResourceBuilder , channelUri , tile , this . retryPolicy , optional ) ; }
Pushes a tile to channelUri using optional headers
10,727
public List < WnsNotificationResponse > pushTile ( List < String > channelUris , WnsTile tile ) throws WnsException { return this . pushTile ( channelUris , null , tile ) ; }
Pushes a tile to channelUris
10,728
public WnsNotificationResponse pushToast ( String channelUri , WnsToast toast ) throws WnsException { return this . pushToast ( channelUri , null , toast ) ; }
Pushes a toast to channelUri
10,729
public WnsNotificationResponse pushToast ( String channelUri , WnsNotificationRequestOptional optional , WnsToast toast ) throws WnsException { return this . client . push ( xmlResourceBuilder , channelUri , toast , this . retryPolicy , optional ) ; }
Pushes a toast to channelUri using optional headers
10,730
public List < WnsNotificationResponse > pushToast ( List < String > channelUris , WnsToast toast ) throws WnsException { return this . pushToast ( channelUris , null , toast ) ; }
Pushes a toast to channelUris
10,731
public WnsNotificationResponse pushBadge ( String channelUri , WnsNotificationRequestOptional optional , WnsBadge badge ) throws WnsException { return this . client . push ( xmlResourceBuilder , channelUri , badge , this . retryPolicy , optional ) ; }
Pushes a badge to channelUri using optional headers
10,732
public List < WnsNotificationResponse > pushBadge ( List < String > channelUris , WnsBadge badge ) throws WnsException { return this . pushBadge ( channelUris , null , badge ) ; }
Pushes a badge to channelUris
10,733
public WnsNotificationResponse pushRaw ( String channelUri , WnsNotificationRequestOptional optional , WnsRaw raw ) throws WnsException { return this . client . push ( rawResourceBuilder , channelUri , raw , this . retryPolicy , optional ) ; }
Pushes a raw message to channelUri using optional headers
10,734
public List < WnsNotificationResponse > pushRaw ( List < String > channelUris , WnsRaw raw ) throws WnsException { return this . pushRaw ( channelUris , null , raw ) ; }
Pushes a raw message to channelUris
10,735
public void render ( File outputDirectory , ApplicationTemplate applicationTemplate , File applicationDirectory , Renderer renderer , Map < String , String > options , Map < String , String > typeAnnotations ) throws IOException { options = fixOptions ( options ) ; buildRenderer ( outputDirectory , applicationTemplate , applicationDirectory , renderer , typeAnnotations ) . render ( options ) ; }
Renders a Roboconf application into a given format .
10,736
private IRenderer buildRenderer ( File outputDirectory , ApplicationTemplate applicationTemplate , File applicationDirectory , Renderer renderer , Map < String , String > typeAnnotations ) { IRenderer result = null ; switch ( renderer ) { case HTML : result = new HtmlRenderer ( outputDirectory , applicationTemplate , applicationDirectory , typeAnnotations ) ; break ; case MARKDOWN : result = new MarkdownRenderer ( outputDirectory , applicationTemplate , applicationDirectory , typeAnnotations ) ; break ; case FOP : result = new FopRenderer ( outputDirectory , applicationTemplate , applicationDirectory , typeAnnotations ) ; break ; case PDF : result = new PdfRenderer ( outputDirectory , applicationTemplate , applicationDirectory , typeAnnotations ) ; break ; default : break ; } return result ; }
Builds the right renderer .
10,737
public static void save ( File f , Application app ) throws IOException { Properties properties = new Properties ( ) ; if ( ! Utils . isEmptyOrWhitespaces ( app . getDisplayName ( ) ) ) properties . setProperty ( APPLICATION_NAME , app . getDisplayName ( ) ) ; if ( ! Utils . isEmptyOrWhitespaces ( app . getDescription ( ) ) ) properties . setProperty ( APPLICATION_DESCRIPTION , app . getDescription ( ) ) ; if ( app . getTemplate ( ) != null ) { if ( ! Utils . isEmptyOrWhitespaces ( app . getTemplate ( ) . getName ( ) ) ) properties . setProperty ( APPLICATION_TPL_NAME , app . getTemplate ( ) . getName ( ) ) ; if ( ! Utils . isEmptyOrWhitespaces ( app . getTemplate ( ) . getVersion ( ) ) ) properties . setProperty ( APPLICATION_TPL_VERSION , app . getTemplate ( ) . getVersion ( ) ) ; } Utils . writePropertiesFile ( properties , f ) ; }
Saves an application descriptor .
10,738
public static void addResourceAfterAngularJS ( String library , String resource ) { FacesContext ctx = FacesContext . getCurrentInstance ( ) ; UIViewRoot v = ctx . getViewRoot ( ) ; Map < String , Object > viewMap = v . getViewMap ( ) ; @ SuppressWarnings ( "unchecked" ) Map < String , String > resourceMap = ( Map < String , String > ) viewMap . get ( RESOURCE_KEY ) ; if ( null == resourceMap ) { resourceMap = new HashMap < String , String > ( ) ; viewMap . put ( RESOURCE_KEY , resourceMap ) ; } String key = library + "#" + resource ; if ( ! resourceMap . containsKey ( key ) ) { resourceMap . put ( key , resource ) ; } }
Registers a JS file that needs to be include in the header of the HTML file but after jQuery and AngularJS .
10,739
public Collection < InstanceContextBean > apply ( Collection < InstanceContextBean > instances ) { final ArrayList < InstanceContextBean > result = new ArrayList < InstanceContextBean > ( ) ; for ( InstanceContextBean instance : instances ) { boolean installerMatches = this . installerName == null || this . installerName . equalsIgnoreCase ( instance . getInstaller ( ) ) ; if ( installerMatches && this . rootNode . isMatching ( instance ) ) result . add ( instance ) ; } result . trimToSize ( ) ; return Collections . unmodifiableCollection ( result ) ; }
Applies this filter to the given instances .
10,740
protected String acquireIpAddress ( TargetHandlerParameters parameters , String machineId ) { String result = null ; String ips = parameters . getTargetProperties ( ) . get ( IP_ADDRESSES ) ; ips = ips == null ? "" : ips ; for ( String ip : Utils . splitNicely ( ips , "," ) ) { if ( Utils . isEmptyOrWhitespaces ( ip ) ) continue ; if ( this . usedIps . putIfAbsent ( ip , 1 ) == null ) { this . machineIdToIp . put ( machineId , ip ) ; result = ip ; save ( this ) ; break ; } } return result ; }
Acquires an IP address among available ones .
10,741
private InstanceContext findAgentContext ( Application application , Instance instance ) { Instance scopedInstance = InstanceHelpers . findScopedInstance ( instance ) ; return new InstanceContext ( application , scopedInstance ) ; }
Builds an instance context corresponding to an agent .
10,742
public static < T extends Serializable > byte [ ] serializeObject ( T object ) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; ObjectOutputStream out = new ObjectOutputStream ( os ) ; out . writeObject ( object ) ; return os . toByteArray ( ) ; }
Serializes an object .
10,743
public static < T extends Serializable > T deserializeObject ( byte [ ] bytes , Class < T > clazz ) throws IOException , ClassNotFoundException { ByteArrayInputStream is = new ByteArrayInputStream ( bytes ) ; ObjectInputStream deserializer = new ObjectInputStream ( is ) ; return clazz . cast ( deserializer . readObject ( ) ) ; }
Deserializes an object .
10,744
static void checkErrors ( Collection < RoboconfError > errors , Logger logger ) throws InvalidApplicationException { if ( RoboconfErrorHelpers . containsCriticalErrors ( errors ) ) throw new InvalidApplicationException ( errors ) ; Collection < RoboconfError > warnings = RoboconfErrorHelpers . findWarnings ( errors ) ; for ( String warningMsg : RoboconfErrorHelpers . formatErrors ( warnings , null , true ) . values ( ) ) logger . warning ( warningMsg ) ; }
A method to check errors .
10,745
private ManagedApplication createNewApplication ( String name , String description , ApplicationTemplate tpl , File configurationDirectory ) throws AlreadyExistingException , IOException { this . logger . info ( "Creating application " + name + " from template " + tpl + "..." ) ; if ( Utils . isEmptyOrWhitespaces ( name ) ) throw new IOException ( "An application name cannot be empty." ) ; Application app = new Application ( name , tpl ) . description ( description ) ; if ( ! app . getName ( ) . matches ( ParsingConstants . PATTERN_APP_NAME ) ) throw new IOException ( "Application names cannot contain invalid characters. Letters, digits, dots, underscores, brackets, spaces and the minus symbol are allowed." ) ; if ( this . nameToManagedApplication . containsKey ( name ) ) throw new AlreadyExistingException ( name ) ; File targetDirectory = ConfigurationUtils . findApplicationDirectory ( app . getName ( ) , configurationDirectory ) ; Utils . createDirectory ( targetDirectory ) ; app . setDirectory ( targetDirectory ) ; File descFile = new File ( targetDirectory , Constants . PROJECT_DIR_DESC + "/" + Constants . PROJECT_FILE_DESCRIPTOR ) ; Utils . createDirectory ( descFile . getParentFile ( ) ) ; ApplicationDescriptor . save ( descFile , app ) ; List < File > tplDirectories = Utils . listDirectories ( tpl . getDirectory ( ) ) ; List < String > toSkip = Arrays . asList ( Constants . PROJECT_DIR_DESC , Constants . PROJECT_DIR_GRAPH , Constants . PROJECT_DIR_INSTANCES ) ; for ( File dir : tplDirectories ) { if ( toSkip . contains ( dir . getName ( ) . toLowerCase ( ) ) ) continue ; File newDir = new File ( targetDirectory , dir . getName ( ) ) ; Utils . copyDirectory ( dir , newDir ) ; } for ( Instance rootInstance : app . getRootInstances ( ) ) rootInstance . data . put ( Instance . APPLICATION_NAME , app . getName ( ) ) ; ConfigurationUtils . loadApplicationBindings ( app ) ; ManagedApplication ma = new ManagedApplication ( app ) ; this . nameToManagedApplication . put ( app . getName ( ) , ma ) ; ConfigurationUtils . saveInstances ( ma ) ; this . logger . info ( "Application " + name + " was successfully created from the template " + tpl + "." ) ; return ma ; }
Creates a new application from a template .
10,746
private static String getFileExtension ( final String filename ) { String extension = "" ; int i = filename . lastIndexOf ( '.' ) ; int p = Math . max ( filename . lastIndexOf ( '/' ) , filename . lastIndexOf ( '\\' ) ) ; if ( i > p ) extension = filename . substring ( i + 1 ) ; return extension ; }
Get the file name extension from its name .
10,747
public static Graphs loadGraph ( File graphFile , File graphDirectory , ApplicationLoadResult alr ) { FromGraphDefinition fromDef = new FromGraphDefinition ( graphDirectory ) ; Graphs graph = fromDef . buildGraphs ( graphFile ) ; alr . getParsedFiles ( ) . addAll ( fromDef . getProcessedImports ( ) ) ; if ( ! fromDef . getErrors ( ) . isEmpty ( ) ) { alr . loadErrors . addAll ( fromDef . getErrors ( ) ) ; } else { Collection < ModelError > errors = RuntimeModelValidator . validate ( graph ) ; alr . loadErrors . addAll ( errors ) ; errors = RuntimeModelValidator . validate ( graph , graphDirectory . getParentFile ( ) ) ; alr . loadErrors . addAll ( errors ) ; alr . objectToSource . putAll ( fromDef . getObjectToSource ( ) ) ; alr . typeAnnotations . putAll ( fromDef . getTypeAnnotations ( ) ) ; } return graph ; }
Loads a graph file .
10,748
public static InstancesLoadResult loadInstances ( File instancesFile , File rootDirectory , Graphs graph , String applicationName ) { InstancesLoadResult result = new InstancesLoadResult ( ) ; INST : { if ( ! instancesFile . exists ( ) ) { RoboconfError error = new RoboconfError ( ErrorCode . PROJ_MISSING_INSTANCE_EP ) ; error . setDetails ( expected ( instancesFile . getAbsolutePath ( ) ) ) ; result . loadErrors . add ( error ) ; break INST ; } FromInstanceDefinition fromDef = new FromInstanceDefinition ( rootDirectory ) ; Collection < Instance > instances = fromDef . buildInstances ( graph , instancesFile ) ; result . getParsedFiles ( ) . addAll ( fromDef . getProcessedImports ( ) ) ; if ( ! fromDef . getErrors ( ) . isEmpty ( ) ) { result . loadErrors . addAll ( fromDef . getErrors ( ) ) ; break INST ; } Collection < ModelError > errors = RuntimeModelValidator . validate ( instances ) ; result . loadErrors . addAll ( errors ) ; result . objectToSource . putAll ( fromDef . getObjectToSource ( ) ) ; result . getRootInstances ( ) . addAll ( instances ) ; } for ( Instance rootInstance : result . rootInstances ) rootInstance . data . put ( Instance . APPLICATION_NAME , applicationName ) ; return result ; }
Loads instances from a file .
10,749
public static void writeInstances ( File targetFile , Collection < Instance > rootInstances ) throws IOException { FileDefinition def = new FromInstances ( ) . buildFileDefinition ( rootInstances , targetFile , false , true ) ; ParsingModelIo . saveRelationsFile ( def , false , "\n" ) ; }
Writes all the instances into a file .
10,750
public static AbstractLifeCycleManager build ( Instance instance , String appName , IAgentClient messagingClient ) { AbstractLifeCycleManager result ; switch ( instance . getStatus ( ) ) { case DEPLOYED_STARTED : result = new DeployedStarted ( appName , messagingClient ) ; break ; case DEPLOYED_STOPPED : result = new DeployedStopped ( appName , messagingClient ) ; break ; case NOT_DEPLOYED : result = new NotDeployed ( appName , messagingClient ) ; break ; case UNRESOLVED : result = new Unresolved ( appName , messagingClient ) ; break ; case WAITING_FOR_ANCESTOR : result = new WaitingForAncestor ( appName , messagingClient ) ; break ; default : result = new TransitiveStates ( appName , messagingClient ) ; break ; } return result ; }
Builds the right handler depending on the current instance s state .
10,751
public void updateStateFromImports ( Instance impactedInstance , PluginInterface plugin , Import importChanged , InstanceStatus statusChanged ) throws IOException , PluginException { boolean haveAllImports = ImportHelpers . hasAllRequiredImports ( impactedInstance , this . logger ) ; if ( haveAllImports ) { if ( impactedInstance . getStatus ( ) == InstanceStatus . UNRESOLVED || impactedInstance . data . remove ( FORCE ) != null ) { InstanceStatus oldState = impactedInstance . getStatus ( ) ; impactedInstance . setStatus ( InstanceStatus . STARTING ) ; try { this . messagingClient . sendMessageToTheDm ( new MsgNotifInstanceChanged ( this . appName , impactedInstance ) ) ; plugin . start ( impactedInstance ) ; impactedInstance . setStatus ( InstanceStatus . DEPLOYED_STARTED ) ; this . messagingClient . sendMessageToTheDm ( new MsgNotifInstanceChanged ( this . appName , impactedInstance ) ) ; this . messagingClient . publishExports ( impactedInstance ) ; this . messagingClient . listenToRequestsFromOtherAgents ( ListenerCommand . START , impactedInstance ) ; } catch ( Exception e ) { this . logger . severe ( "An error occured while starting " + InstanceHelpers . computeInstancePath ( impactedInstance ) ) ; Utils . logException ( this . logger , e ) ; impactedInstance . setStatus ( oldState ) ; this . messagingClient . sendMessageToTheDm ( new MsgNotifInstanceChanged ( this . appName , impactedInstance ) ) ; } } else if ( impactedInstance . getStatus ( ) == InstanceStatus . DEPLOYED_STARTED ) { plugin . update ( impactedInstance , importChanged , statusChanged ) ; } else { this . logger . fine ( InstanceHelpers . computeInstancePath ( impactedInstance ) + " checked import changes but has nothing to update (1)." ) ; } } else { if ( impactedInstance . getStatus ( ) == InstanceStatus . DEPLOYED_STARTED ) { stopInstance ( impactedInstance , plugin , true ) ; } else { this . logger . fine ( InstanceHelpers . computeInstancePath ( impactedInstance ) + " checked import changes but has nothing to update (2)." ) ; } } }
Updates the status of an instance based on the imports .
10,752
public static void copyInstanceResources ( Instance instance , Map < String , byte [ ] > fileNameToFileContent ) throws IOException { File dir = InstanceHelpers . findInstanceDirectoryOnAgent ( instance ) ; Utils . createDirectory ( dir ) ; if ( fileNameToFileContent != null ) { for ( Map . Entry < String , byte [ ] > entry : fileNameToFileContent . entrySet ( ) ) { File f = new File ( dir , entry . getKey ( ) ) ; Utils . createDirectory ( f . getParentFile ( ) ) ; ByteArrayInputStream in = new ByteArrayInputStream ( entry . getValue ( ) ) ; Utils . copyStream ( in , f ) ; } } }
Copies the resources of an instance on the disk .
10,753
public static void executeScriptResources ( File scriptsDir ) throws IOException { if ( scriptsDir . isDirectory ( ) ) { List < File > scriptFiles = Utils . listAllFiles ( scriptsDir ) ; Logger logger = Logger . getLogger ( AgentUtils . class . getName ( ) ) ; for ( File script : scriptFiles ) { if ( script . getName ( ) . contains ( Constants . SCOPED_SCRIPT_AT_AGENT_SUFFIX ) ) { script . setExecutable ( true ) ; String [ ] command = { script . getAbsolutePath ( ) } ; try { ProgramUtils . executeCommand ( logger , command , script . getParentFile ( ) , null , null , null ) ; } catch ( InterruptedException e ) { Utils . logException ( logger , e ) ; } } } } }
Executes a script resource on a given instance .
10,754
public static void deleteInstanceResources ( Instance instance ) throws IOException { File dir = InstanceHelpers . findInstanceDirectoryOnAgent ( instance ) ; Utils . deleteFilesRecursively ( dir ) ; }
Deletes the resources for a given instance .
10,755
public static Map < String , byte [ ] > collectLogs ( String karafData ) throws IOException { Map < String , byte [ ] > logFiles = new HashMap < > ( 2 ) ; if ( ! Utils . isEmptyOrWhitespaces ( karafData ) ) { String [ ] names = { "karaf.log" , "roboconf.log" } ; for ( String name : names ) { File log = new File ( karafData , AgentConstants . KARAF_LOGS_DIRECTORY + "/" + name ) ; if ( ! log . exists ( ) ) continue ; String content = Utils . readFileContent ( log ) ; logFiles . put ( name , content . getBytes ( StandardCharsets . UTF_8 ) ) ; } } return logFiles ; }
Collect the main log files into a map .
10,756
public static void injectConfigurations ( String karafEtc , String applicationName , String scopedInstancePath , String domain , String ipAddress ) { File injectionDir = new File ( karafEtc , INJECTED_CONFIGS_DIR ) ; if ( injectionDir . isDirectory ( ) ) { for ( File source : Utils . listAllFiles ( injectionDir , ".cfg.tpl" ) ) { try { File target = new File ( karafEtc , source . getName ( ) . replaceFirst ( "\\.tpl$" , "" ) ) ; if ( Constants . KARAF_CFG_FILE_AGENT . equalsIgnoreCase ( target . getName ( ) ) ) continue ; String content = Utils . readFileContent ( source ) ; content = content . replace ( "<domain>" , domain ) ; content = content . replace ( "<application-name>" , applicationName ) ; content = content . replace ( "<scoped-instance-path>" , scopedInstancePath ) ; content = content . replace ( "<ip-address>" , ipAddress ) ; Utils . writeStringInto ( content , target ) ; } catch ( IOException e ) { Logger logger = Logger . getLogger ( AgentUtils . class . getName ( ) ) ; logger . severe ( "A configuration file could not be injected from " + source . getName ( ) ) ; Utils . logException ( logger , e ) ; } } } }
Generates configuration files from templates .
10,757
private void cleanupAfterView ( ) { FacesContext ctx = FacesContext . getCurrentInstance ( ) ; ResponseWriter orig = ( ResponseWriter ) ctx . getAttributes ( ) . get ( ORIGINAL_WRITER ) ; assert ( null != orig ) ; ctx . setResponseWriter ( orig ) ; }
Copied from com . sun . faces . context . PartialViewContextImpl .
10,758
public static File findTemplateDirectory ( ApplicationTemplate tpl , File configurationDirectory ) { StringBuilder sb = new StringBuilder ( TEMPLATES ) ; sb . append ( "/" ) ; sb . append ( tpl . getName ( ) ) ; if ( ! Utils . isEmptyOrWhitespaces ( tpl . getVersion ( ) ) ) { sb . append ( " - " ) ; sb . append ( tpl . getVersion ( ) ) ; } return new File ( configurationDirectory , sb . toString ( ) ) ; }
Finds the directory that contains the files for an application template .
10,759
public static void saveInstances ( Application app ) { File targetFile = new File ( app . getDirectory ( ) , Constants . PROJECT_DIR_INSTANCES + "/" + INSTANCES_FILE ) ; try { Utils . createDirectory ( targetFile . getParentFile ( ) ) ; RuntimeModelIo . writeInstances ( targetFile , app . getRootInstances ( ) ) ; } catch ( IOException e ) { Logger logger = Logger . getLogger ( ConfigurationUtils . class . getName ( ) ) ; logger . severe ( "Failed to save instances. " + e . getMessage ( ) ) ; Utils . logException ( logger , e ) ; } }
Saves the instances into a file .
10,760
public static InstancesLoadResult restoreInstances ( ManagedApplication ma ) { File sourceFile = new File ( ma . getDirectory ( ) , Constants . PROJECT_DIR_INSTANCES + "/" + INSTANCES_FILE ) ; Graphs graphs = ma . getApplication ( ) . getTemplate ( ) . getGraphs ( ) ; InstancesLoadResult result ; if ( sourceFile . exists ( ) ) result = RuntimeModelIo . loadInstances ( sourceFile , sourceFile . getParentFile ( ) , graphs , ma . getApplication ( ) . getName ( ) ) ; else result = new InstancesLoadResult ( ) ; return result ; }
Restores instances and set them in the application .
10,761
public static File findIcon ( String name , String qualifier , File configurationDirectory ) { if ( configurationDirectory == null ) return null ; File root ; if ( ! Utils . isEmptyOrWhitespaces ( qualifier ) ) { ApplicationTemplate tpl = new ApplicationTemplate ( name ) . version ( qualifier ) ; root = ConfigurationUtils . findTemplateDirectory ( tpl , configurationDirectory ) ; } else { root = ConfigurationUtils . findApplicationDirectory ( name , configurationDirectory ) ; } return IconUtils . findIcon ( root ) ; }
Finds the icon associated with an application template .
10,762
public static void loadApplicationBindings ( Application app ) { File descDir = new File ( app . getDirectory ( ) , Constants . PROJECT_DIR_DESC ) ; File appBindingsFile = new File ( descDir , APP_BINDINGS_FILE ) ; Logger logger = Logger . getLogger ( ConfigurationUtils . class . getName ( ) ) ; Properties props = Utils . readPropertiesFileQuietly ( appBindingsFile , logger ) ; for ( Map . Entry < ? , ? > entry : props . entrySet ( ) ) { for ( String part : Utils . splitNicely ( ( String ) entry . getValue ( ) , "," ) ) { if ( ! Utils . isEmptyOrWhitespaces ( part ) ) app . bindWithApplication ( ( String ) entry . getKey ( ) , part ) ; } } }
Loads the application bindings into an application .
10,763
public static void saveApplicationBindings ( Application app ) { File descDir = new File ( app . getDirectory ( ) , Constants . PROJECT_DIR_DESC ) ; File appBindingsFile = new File ( descDir , APP_BINDINGS_FILE ) ; Map < String , String > format = new HashMap < > ( ) ; for ( Map . Entry < String , Set < String > > entry : app . getApplicationBindings ( ) . entrySet ( ) ) { String s = Utils . format ( entry . getValue ( ) , ", " ) ; format . put ( entry . getKey ( ) , s ) ; } Properties props = new Properties ( ) ; props . putAll ( format ) ; try { Utils . createDirectory ( descDir ) ; Utils . writePropertiesFile ( props , appBindingsFile ) ; } catch ( IOException e ) { Logger logger = Logger . getLogger ( ConfigurationUtils . class . getName ( ) ) ; logger . severe ( "Failed to save application bindings for " + app + ". " + e . getMessage ( ) ) ; Utils . logException ( logger , e ) ; } }
Saves the application bindings into the DM s directory .
10,764
protected ParsingError error ( ErrorCode errorCode , ErrorDetails ... details ) { return new ParsingError ( errorCode , this . context . getCommandFile ( ) , this . line , details ) ; }
A shortcut method to create a parsing error with relevant information .
10,765
public static List < String > getPropertyValues ( AbstractBlockHolder holder , String propertyName ) { List < String > result = new ArrayList < > ( ) ; for ( BlockProperty p : holder . findPropertiesBlockByName ( propertyName ) ) { result . addAll ( Utils . splitNicely ( p . getValue ( ) , ParsingConstants . PROPERTY_SEPARATOR ) ) ; } return result ; }
Gets and splits property values separated by a comma .
10,766
public static Map < String , String > getData ( AbstractBlockHolder holder ) { BlockProperty p = holder . findPropertyBlockByName ( ParsingConstants . PROPERTY_INSTANCE_DATA ) ; Map < String , String > result = new HashMap < > ( ) ; String propertyValue = p == null ? null : p . getValue ( ) ; for ( String s : Utils . splitNicely ( propertyValue , ParsingConstants . PROPERTY_SEPARATOR ) ) { Map . Entry < String , String > entry = VariableHelpers . parseExportedVariable ( s ) ; result . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return result ; }
Gets and splits data separated by a comma .
10,767
public synchronized void setHttpServerIp ( final String serverIp ) { this . httpServerIp = serverIp ; this . dmClient . setHttpServerIp ( serverIp ) ; this . logger . finer ( "Server IP set to " + this . httpServerIp ) ; }
Getters and Setters
10,768
private void resetClients ( boolean shutdown ) { final List < HttpAgentClient > clients ; synchronized ( this ) { clients = new ArrayList < > ( this . agentClients ) ; this . agentClients . clear ( ) ; } for ( HttpAgentClient client : clients ) { try { final ReconfigurableClient < ? > reconfigurable = client . getReconfigurableClient ( ) ; if ( shutdown ) reconfigurable . closeConnection ( ) ; else reconfigurable . switchMessagingType ( HttpConstants . FACTORY_HTTP ) ; } catch ( Throwable t ) { this . logger . warning ( "A client has thrown an exception on reconfiguration: " + client ) ; Utils . logException ( this . logger , new RuntimeException ( t ) ) ; } } }
Closes messaging clients or requests a replacement to the reconfigurable client .
10,769
public void handlerAppears ( IMonitoringHandler handler ) { if ( handler != null ) { this . logger . info ( "Monitoring handler '" + handler . getName ( ) + "' is now available." ) ; this . handlers . add ( handler ) ; listHandlers ( this . handlers , this . logger ) ; } }
This method is invoked by iPojo every time a new monitoring handler appears .
10,770
public void handlerDisappears ( IMonitoringHandler handler ) { if ( handler == null ) { this . logger . info ( "An invalid monitoring handler is removed." ) ; } else { this . handlers . remove ( handler ) ; this . logger . info ( "Monitoring handler '" + handler . getName ( ) + "' is not available anymore." ) ; } listHandlers ( this . handlers , this . logger ) ; }
This method is invoked by iPojo every time a monitoring handler disappears .
10,771
public static void listHandlers ( List < IMonitoringHandler > handlers , Logger logger ) { if ( handlers . isEmpty ( ) ) { logger . info ( "No monitoring handler was found." ) ; } else { StringBuilder sb = new StringBuilder ( "Available monitoring handlers: " ) ; for ( Iterator < IMonitoringHandler > it = handlers . iterator ( ) ; it . hasNext ( ) ; ) { sb . append ( it . next ( ) . getName ( ) ) ; if ( it . hasNext ( ) ) sb . append ( ", " ) ; } sb . append ( "." ) ; logger . info ( sb . toString ( ) ) ; } }
This method lists the available handlers and logs them .
10,772
public String validate ( ) { String result = null ; if ( this . messagingConfiguration == null || this . messagingConfiguration . isEmpty ( ) ) result = "The message configuration cannot be null or empty." ; else if ( this . messagingConfiguration . get ( MessagingConstants . MESSAGING_TYPE_PROPERTY ) == null ) result = "The message configuration does not contain the messaging type." ; else if ( Utils . isEmptyOrWhitespaces ( this . applicationName ) ) result = "The application name cannot be null or empty." ; else if ( Utils . isEmptyOrWhitespaces ( this . scopedInstancePath ) ) result = "The scoped instance's path cannot be null or empty." ; return result ; }
Validates this bean .
10,773
public static AgentProperties readIaasProperties ( String rawProperties , Logger logger ) throws IOException { Properties props = Utils . readPropertiesQuietly ( rawProperties , logger ) ; return readIaasProperties ( props ) ; }
Creates a new bean from raw properties that will be parsed .
10,774
public static AgentProperties readIaasProperties ( Properties props ) throws IOException { File msgResourcesDirectory = new File ( System . getProperty ( "java.io.tmpdir" ) , "roboconf-messaging" ) ; props = UserDataHelpers . processUserData ( props , msgResourcesDirectory ) ; AgentProperties result = new AgentProperties ( ) ; result . setApplicationName ( updatedField ( props , UserDataHelpers . APPLICATION_NAME ) ) ; result . setScopedInstancePath ( updatedField ( props , UserDataHelpers . SCOPED_INSTANCE_PATH ) ) ; result . setDomain ( updatedField ( props , UserDataHelpers . DOMAIN ) ) ; final Map < String , String > messagingConfiguration = new LinkedHashMap < > ( ) ; List < String > toSkip = Arrays . asList ( UserDataHelpers . APPLICATION_NAME , UserDataHelpers . DOMAIN , UserDataHelpers . SCOPED_INSTANCE_PATH ) ; for ( String k : props . stringPropertyNames ( ) ) { if ( ! toSkip . contains ( k ) ) { messagingConfiguration . put ( k , updatedField ( props , k ) ) ; } } result . setMessagingConfiguration ( Collections . unmodifiableMap ( messagingConfiguration ) ) ; return result ; }
Creates a new bean from properties .
10,775
private static String updatedField ( Properties props , String fieldName ) { String property = props . getProperty ( fieldName ) ; if ( property != null ) property = property . replace ( "\\:" , ":" ) ; return property ; }
Gets a property and updates it to prevent escaped characters .
10,776
public static Message deserializeObject ( byte [ ] bytes ) throws IOException , ClassNotFoundException { ByteArrayInputStream is = new ByteArrayInputStream ( bytes ) ; ObjectInputStream deserializer = new ObjectInputStream ( is ) ; return ( Message ) deserializer . readObject ( ) ; }
Deserializes a message .
10,777
public static Map < String , String > buildHeaders ( String reqCorsHeader , String requestUri ) { Map < String , String > result = new LinkedHashMap < > ( ) ; result . put ( CORS_ALLOW_ORIGIN , requestUri ) ; result . put ( CORS_ALLOW_METHODS , VALUE_ALLOWED_METHODS ) ; result . put ( CORS_ALLOW_CREDENTIALS , VALUE_ALLOW_CREDENTIALS ) ; if ( ! Utils . isEmptyOrWhitespaces ( reqCorsHeader ) ) result . put ( CORS_ALLOW_HEADERS , reqCorsHeader ) ; return result ; }
Finds the right headers to set on the response to prevent CORS issues .
10,778
public static Version parseVersion ( String rawVersion ) { Version result = null ; Matcher m = Pattern . compile ( "^(\\d+)\\.(\\d+)(\\.\\d+)?([.-].+)?$" ) . matcher ( rawVersion ) ; if ( m . find ( ) ) { result = new Version ( Integer . parseInt ( m . group ( 1 ) ) , Integer . parseInt ( m . group ( 2 ) ) , m . group ( 3 ) == null ? 0 : Integer . parseInt ( m . group ( 3 ) . substring ( 1 ) ) , m . group ( 4 ) == null ? null : m . group ( 4 ) . substring ( 1 ) ) ; } return result ; }
Creates a version object from a string .
10,779
public static boolean containsCriticalErrors ( Collection < ? extends RoboconfError > errors ) { boolean result = false ; for ( RoboconfError error : errors ) { if ( ( result = error . getErrorCode ( ) . getLevel ( ) == ErrorLevel . SEVERE ) ) break ; } return result ; }
Determines whether a collection of errors contains at least one critical error .
10,780
public static Collection < RoboconfError > findWarnings ( Collection < ? extends RoboconfError > errors ) { Collection < RoboconfError > result = new ArrayList < > ( ) ; for ( RoboconfError error : errors ) { if ( error . getErrorCode ( ) . getLevel ( ) == ErrorLevel . WARNING ) result . add ( error ) ; } return result ; }
Finds all the warnings among a collection of Roboconf errors .
10,781
public static void filterErrors ( Collection < ? extends RoboconfError > errors , ErrorCode ... errorCodes ) { List < ErrorCode > codesToSkip = new ArrayList < > ( ) ; codesToSkip . addAll ( Arrays . asList ( errorCodes ) ) ; Collection < RoboconfError > toRemove = new ArrayList < > ( ) ; for ( RoboconfError error : errors ) { if ( codesToSkip . contains ( error . getErrorCode ( ) ) ) toRemove . add ( error ) ; } errors . removeAll ( toRemove ) ; }
Filters errors by removing those associated with specific error codes .
10,782
private void renderApplication ( ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; sb . append ( renderDocumentTitle ( ) ) ; sb . append ( renderPageBreak ( ) ) ; sb . append ( renderParagraph ( this . messages . get ( "intro" ) ) ) ; sb . append ( renderPageBreak ( ) ) ; sb . append ( renderDocumentIndex ( ) ) ; sb . append ( renderPageBreak ( ) ) ; sb . append ( startTable ( ) ) ; sb . append ( addTableLine ( this . messages . get ( "app.name" ) , this . applicationTemplate . getName ( ) ) ) ; sb . append ( addTableLine ( this . messages . get ( "app.qualifier" ) , this . applicationTemplate . getVersion ( ) ) ) ; sb . append ( endTable ( ) ) ; sb . append ( renderApplicationDescription ( ) ) ; sb . append ( renderPageBreak ( ) ) ; sb . append ( renderSections ( new ArrayList < String > ( 0 ) ) ) ; sb . append ( renderComponents ( ) ) ; sb . append ( renderInstances ( ) ) ; writeFileContent ( sb . toString ( ) ) ; }
Renders an applicationTemplate .
10,783
private void renderRecipe ( ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; if ( ! Constants . GENERATED . equalsIgnoreCase ( this . applicationTemplate . getName ( ) ) ) { sb . append ( renderDocumentTitle ( ) ) ; sb . append ( renderPageBreak ( ) ) ; sb . append ( renderParagraph ( this . messages . get ( "intro" ) ) ) ; sb . append ( renderPageBreak ( ) ) ; sb . append ( renderDocumentIndex ( ) ) ; sb . append ( renderPageBreak ( ) ) ; sb . append ( startTable ( ) ) ; sb . append ( addTableLine ( this . messages . get ( "app.name" ) , this . applicationTemplate . getName ( ) ) ) ; sb . append ( addTableLine ( this . messages . get ( "app.qualifier" ) , this . applicationTemplate . getVersion ( ) ) ) ; sb . append ( endTable ( ) ) ; sb . append ( renderApplicationDescription ( ) ) ; sb . append ( renderPageBreak ( ) ) ; sb . append ( renderSections ( new ArrayList < String > ( 0 ) ) ) ; } else { sb . append ( renderDocumentIndex ( ) ) ; sb . append ( renderPageBreak ( ) ) ; } sb . append ( renderComponents ( ) ) ; sb . append ( renderFacets ( ) ) ; writeFileContent ( sb . toString ( ) ) ; }
Renders a recipe .
10,784
private StringBuilder renderFacets ( ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; if ( ! this . applicationTemplate . getGraphs ( ) . getFacetNameToFacet ( ) . isEmpty ( ) ) { sb . append ( renderTitle1 ( this . messages . get ( "facets" ) ) ) ; sb . append ( renderParagraph ( this . messages . get ( "facets.intro" ) ) ) ; List < String > sectionNames = new ArrayList < > ( ) ; List < Facet > allFacets = new ArrayList < > ( this . applicationTemplate . getGraphs ( ) . getFacetNameToFacet ( ) . values ( ) ) ; Collections . sort ( allFacets , new AbstractTypeComparator ( ) ) ; for ( Facet facet : allFacets ) { final String sectionName = DocConstants . SECTION_FACETS + facet . getName ( ) ; StringBuilder section = startSection ( sectionName ) ; section . append ( renderTitle2 ( facet . getName ( ) ) ) ; String customInfo = readCustomInformation ( this . applicationDirectory , facet . getName ( ) , DocConstants . FACET_DETAILS ) ; if ( Utils . isEmptyOrWhitespaces ( customInfo ) ) customInfo = this . typeAnnotations . get ( facet . getName ( ) ) ; if ( ! Utils . isEmptyOrWhitespaces ( customInfo ) ) { section . append ( renderTitle3 ( this . messages . get ( "overview" ) ) ) ; section . append ( renderParagraph ( customInfo ) ) ; } Map < String , String > exportedVariables = ComponentHelpers . findAllExportedVariables ( facet ) ; section . append ( renderTitle3 ( this . messages . get ( "exports" ) ) ) ; if ( exportedVariables . isEmpty ( ) ) { String msg = MessageFormat . format ( this . messages . get ( "facet.no.export" ) , facet ) ; section . append ( renderParagraph ( msg ) ) ; } else { String msg = MessageFormat . format ( this . messages . get ( "facet.exports" ) , facet ) ; section . append ( renderParagraph ( msg ) ) ; section . append ( renderList ( convertExports ( exportedVariables ) ) ) ; } section = endSection ( sectionName , section ) ; sb . append ( section ) ; sectionNames . add ( sectionName ) ; } sb . append ( renderSections ( sectionNames ) ) ; } return sb ; }
Renders information about the facets .
10,785
private Object renderApplicationDescription ( ) throws IOException { String s ; if ( this . locale == null && ! Utils . isEmptyOrWhitespaces ( this . applicationTemplate . getDescription ( ) ) ) s = this . applicationTemplate . getDescription ( ) ; else s = readCustomInformation ( this . applicationDirectory , DocConstants . APP_DESC_PREFIX , DocConstants . FILE_SUFFIX ) ; String result = "" ; if ( ! Utils . isEmptyOrWhitespaces ( s ) ) result = renderParagraph ( s ) ; return result ; }
Renders the application s description .
10,786
private void saveImage ( final Component comp , DiagramType type , AbstractRoboconfTransformer transformer , StringBuilder sb ) throws IOException { String baseName = comp . getName ( ) + "_" + type ; String relativePath = "png/" + baseName + ".png" ; if ( this . options . containsKey ( DocConstants . OPTION_GEN_IMAGES_ONCE ) ) relativePath = "../" + relativePath ; File pngFile = new File ( this . outputDirectory , relativePath ) . getCanonicalFile ( ) ; if ( ! pngFile . exists ( ) ) { Utils . createDirectory ( pngFile . getParentFile ( ) ) ; GraphUtils . writeGraph ( pngFile , comp , transformer . getConfiguredLayout ( ) , transformer . getGraph ( ) , transformer . getEdgeShapeTransformer ( ) , this . options ) ; } sb . append ( renderImage ( comp . getName ( ) , type , relativePath ) ) ; }
Generates and saves an image .
10,787
private String readCustomInformation ( File applicationDirectory , String prefix , String suffix ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; sb . append ( prefix ) ; if ( this . locale != null ) sb . append ( "_" + this . locale ) ; sb . append ( suffix ) ; sb . insert ( 0 , "/" ) ; sb . insert ( 0 , DocConstants . DOC_DIR ) ; File f = new File ( applicationDirectory , sb . toString ( ) ) ; if ( ! f . exists ( ) ) f = new File ( f . getParentFile ( ) . getParentFile ( ) , sb . toString ( ) ) ; String result = "" ; if ( f . exists ( ) ) result = Utils . readFileContent ( f ) ; return result ; }
Reads user - specified information from the project .
10,788
private List < String > convertImports ( Collection < ImportedVariable > importedVariables ) { List < String > result = new ArrayList < > ( ) ; for ( ImportedVariable var : importedVariables ) { String componentOrFacet = VariableHelpers . parseVariableName ( var . getName ( ) ) . getKey ( ) ; String s = applyLink ( var . getName ( ) , componentOrFacet ) ; s += var . isOptional ( ) ? this . messages . get ( "optional" ) : this . messages . get ( "required" ) ; if ( var . isExternal ( ) ) s += this . messages . get ( "external" ) ; result . add ( s ) ; } return result ; }
Converts imports to a human - readable text .
10,789
private List < String > convertExports ( Map < String , String > exports ) { List < String > result = new ArrayList < > ( ) ; for ( Map . Entry < String , String > entry : exports . entrySet ( ) ) { String componentOrFacet = VariableHelpers . parseVariableName ( entry . getKey ( ) ) . getKey ( ) ; String s = Utils . isEmptyOrWhitespaces ( componentOrFacet ) ? entry . getKey ( ) : applyLink ( entry . getKey ( ) , componentOrFacet ) ; if ( ! Utils . isEmptyOrWhitespaces ( entry . getValue ( ) ) ) s += MessageFormat . format ( this . messages . get ( "default" ) , entry . getValue ( ) ) ; if ( entry . getKey ( ) . toLowerCase ( ) . endsWith ( ".ip" ) ) s += this . messages . get ( "injected" ) ; result . add ( s ) ; } return result ; }
Converts exports to a human - readable text .
10,790
private List < String > getImportComponents ( Component component ) { List < String > result = new ArrayList < > ( ) ; Map < String , Boolean > map = ComponentHelpers . findComponentDependenciesFor ( component ) ; for ( Map . Entry < String , Boolean > entry : map . entrySet ( ) ) { String s = applyLink ( entry . getKey ( ) , entry . getKey ( ) ) ; s += entry . getValue ( ) ? this . messages . get ( "optional" ) : this . messages . get ( "required" ) ; result . add ( s ) ; } return result ; }
Converts component dependencies to a human - readable text .
10,791
private String renderListAsLinks ( List < String > names ) { List < String > newNames = new ArrayList < > ( ) ; for ( String s : names ) newNames . add ( applyLink ( s , s ) ) ; return renderList ( newNames ) ; }
Renders a list as a list of links .
10,792
public void uploadZippedApplicationTemplate ( File applicationFile ) throws ManagementWsException , IOException { if ( applicationFile == null || ! applicationFile . exists ( ) || ! applicationFile . isFile ( ) ) throw new IOException ( "Expected an existing file as parameter." ) ; this . logger . finer ( "Loading an application from " + applicationFile . getAbsolutePath ( ) + "..." ) ; FormDataMultiPart part = new FormDataMultiPart ( ) ; part . bodyPart ( new FileDataBodyPart ( "file" , applicationFile , MediaType . APPLICATION_OCTET_STREAM_TYPE ) ) ; WebResource path = this . resource . path ( UrlConstants . APPLICATIONS ) . path ( "templates" ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . type ( MediaType . MULTIPART_FORM_DATA_TYPE ) . post ( ClientResponse . class , part ) ; if ( Family . SUCCESSFUL != response . getStatusInfo ( ) . getFamily ( ) ) { String value = response . getEntity ( String . class ) ; this . logger . finer ( response . getStatusInfo ( ) + ": " + value ) ; throw new ManagementWsException ( response . getStatusInfo ( ) . getStatusCode ( ) , value ) ; } this . logger . finer ( String . valueOf ( response . getStatusInfo ( ) ) ) ; }
Uploads a ZIP file and loads its application template .
10,793
public void loadUnzippedApplicationTemplate ( String localFilePath ) throws ManagementWsException { this . logger . finer ( "Loading an application from a local directory: " + localFilePath ) ; WebResource path = this . resource . path ( UrlConstants . APPLICATIONS ) . path ( "templates" ) . path ( "local" ) ; if ( localFilePath != null ) path = path . queryParam ( "local-file-path" , localFilePath ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . type ( MediaType . APPLICATION_JSON ) . post ( ClientResponse . class ) ; if ( Family . SUCCESSFUL != response . getStatusInfo ( ) . getFamily ( ) ) { String value = response . getEntity ( String . class ) ; this . logger . finer ( response . getStatusInfo ( ) + ": " + value ) ; throw new ManagementWsException ( response . getStatusInfo ( ) . getStatusCode ( ) , value ) ; } this . logger . finer ( String . valueOf ( response . getStatusInfo ( ) ) ) ; }
Loads an application template from a directory located on the DM s file system .
10,794
public Application createApplication ( String applicationName , String templateName , String templateQualifier ) throws ManagementWsException { this . logger . finer ( "Creating application " + applicationName + " from " + templateName + " - " + templateQualifier + "..." ) ; ApplicationTemplate tpl = new ApplicationTemplate ( templateName ) . version ( templateQualifier ) ; Application app = new Application ( applicationName , tpl ) ; WebResource path = this . resource . path ( UrlConstants . APPLICATIONS ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . type ( MediaType . APPLICATION_JSON ) . post ( ClientResponse . class , app ) ; if ( Family . SUCCESSFUL != response . getStatusInfo ( ) . getFamily ( ) ) throw new ManagementWsException ( response . getStatusInfo ( ) . getStatusCode ( ) , "" ) ; Application result = response . getEntity ( Application . class ) ; return result ; }
Creates an application from a template .
10,795
public List < Application > listApplications ( String exactName ) throws ManagementWsException { if ( exactName != null ) this . logger . finer ( "List/finding the application named " + exactName + "." ) ; else this . logger . finer ( "Listing all the applications." ) ; WebResource path = this . resource . path ( UrlConstants . APPLICATIONS ) ; if ( exactName != null ) path = path . queryParam ( "name" , exactName ) ; List < Application > result = this . wsClient . createBuilder ( path ) . accept ( MediaType . APPLICATION_JSON ) . get ( new GenericType < List < Application > > ( ) { } ) ; if ( result != null ) this . logger . finer ( result . size ( ) + " applications were found on the DM." ) ; else this . logger . finer ( "No application was found on the DM." ) ; return result != null ? result : new ArrayList < Application > ( ) ; }
Lists applications .
10,796
public void shutdownApplication ( String applicationName ) throws ManagementWsException { this . logger . finer ( "Removing application " + applicationName + "..." ) ; WebResource path = this . resource . path ( UrlConstants . APPLICATIONS ) . path ( applicationName ) . path ( "shutdown" ) ; ClientResponse response = this . wsClient . createBuilder ( path ) . post ( ClientResponse . class ) ; String text = response . getEntity ( String . class ) ; this . logger . finer ( text ) ; if ( Family . SUCCESSFUL != response . getStatusInfo ( ) . getFamily ( ) ) throw new ManagementWsException ( response . getStatusInfo ( ) . getStatusCode ( ) , text ) ; }
Shutdowns an application .
10,797
public static String fileTypeAsString ( int fileType ) { String result ; switch ( fileType ) { case AGGREGATOR : result = "aggregator" ; break ; case GRAPH : result = "graph" ; break ; case INSTANCE : result = "intsnace" ; break ; case UNDETERMINED : result = "undetermined" ; break ; default : result = "unknown" ; break ; } return result ; }
Transforms a file type into a string .
10,798
public static RbcfInfo findInstances ( Manager manager , String applicationName , String scopedInstancePath , PrintStream out ) { ManagedApplication ma = null ; List < Instance > scopedInstances = new ArrayList < > ( ) ; Instance scopedInstance ; if ( ( ma = manager . applicationMngr ( ) . findManagedApplicationByName ( applicationName ) ) == null ) out . println ( "Unknown application: " + applicationName + "." ) ; else if ( scopedInstancePath == null ) scopedInstances . addAll ( InstanceHelpers . findAllScopedInstances ( ma . getApplication ( ) ) ) ; else if ( ( scopedInstance = InstanceHelpers . findInstanceByPath ( ma . getApplication ( ) , scopedInstancePath ) ) == null ) out . println ( "There is no " + scopedInstancePath + " instance in " + applicationName + "." ) ; else if ( ! InstanceHelpers . isTarget ( scopedInstance ) ) out . println ( "Instance " + scopedInstancePath + " is not a scoped instance in " + applicationName + "." ) ; else scopedInstances . add ( scopedInstance ) ; return new RbcfInfo ( scopedInstances , ma ) ; }
Finds instances for a given application .
10,799
static NovaApi novaApi ( Map < String , String > targetProperties ) throws TargetException { validate ( targetProperties ) ; return ContextBuilder . newBuilder ( PROVIDER_NOVA ) . endpoint ( targetProperties . get ( API_URL ) ) . credentials ( identity ( targetProperties ) , targetProperties . get ( PASSWORD ) ) . buildApi ( NovaApi . class ) ; }
Creates a JCloud context for Nova .