repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/dsl/ParsingModelIo.java
ParsingModelIo.saveRelationsFile
public static void saveRelationsFile( FileDefinition relationsFile, boolean writeComments, String lineSeparator ) throws IOException { if( relationsFile.getEditedFile() == null ) throw new IOException( "Save operation could not be performed. The model was not loaded from a local file." ); saveRelationsFileInto( relationsFile.getEditedFile(), relationsFile, writeComments, lineSeparator ); }
java
public static void saveRelationsFile( FileDefinition relationsFile, boolean writeComments, String lineSeparator ) throws IOException { if( relationsFile.getEditedFile() == null ) throw new IOException( "Save operation could not be performed. The model was not loaded from a local file." ); saveRelationsFileInto( relationsFile.getEditedFile(), relationsFile, writeComments, lineSeparator ); }
[ "public", "static", "void", "saveRelationsFile", "(", "FileDefinition", "relationsFile", ",", "boolean", "writeComments", ",", "String", "lineSeparator", ")", "throws", "IOException", "{", "if", "(", "relationsFile", ".", "getEditedFile", "(", ")", "==", "null", "...
Saves the model into the original file. @param relationsFile the relations file @param writeComments true to write comments @param lineSeparator the line separator (if null, the OS' one is used) @throws IOException if the file could not be saved
[ "Saves", "the", "model", "into", "the", "original", "file", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/dsl/ParsingModelIo.java#L87-L94
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/dsl/ParsingModelIo.java
ParsingModelIo.saveRelationsFileInto
public static void saveRelationsFileInto( File targetFile, FileDefinition relationsFile, boolean writeComments, String lineSeparator ) throws IOException { String s = writeConfigurationFile( relationsFile, writeComments, lineSeparator ); Utils.copyStream( new ByteArrayInputStream( s.getBytes( StandardCharsets.UTF_8 )), targetFile ); }
java
public static void saveRelationsFileInto( File targetFile, FileDefinition relationsFile, boolean writeComments, String lineSeparator ) throws IOException { String s = writeConfigurationFile( relationsFile, writeComments, lineSeparator ); Utils.copyStream( new ByteArrayInputStream( s.getBytes( StandardCharsets.UTF_8 )), targetFile ); }
[ "public", "static", "void", "saveRelationsFileInto", "(", "File", "targetFile", ",", "FileDefinition", "relationsFile", ",", "boolean", "writeComments", ",", "String", "lineSeparator", ")", "throws", "IOException", "{", "String", "s", "=", "writeConfigurationFile", "(...
Saves the model into another file. @param targetFile the target file (may not exist) @param relationsFile the relations file @param writeComments true to write comments @param lineSeparator the line separator (if null, the OS' one is used) @throws IOException if the file could not be saved
[ "Saves", "the", "model", "into", "another", "file", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/dsl/ParsingModelIo.java#L105-L114
train
stephanrauh/AngularFaces
AngularFaces_2.0/AngularFaces-core/src/main/java/de/beyondjava/angularFaces/core/NGWordUtiltites.java
NGWordUtiltites.labelFromCamelCase
public static String labelFromCamelCase(String camel) { StringBuilder label = new StringBuilder(); for (int i = 0; i < camel.length(); i++) { char c = camel.charAt(i); if (Character.isDigit(c)) { if (i > 0 && Character.isAlphabetic(camel.charAt(i - 1))) label.append(" "); } if (c == '_') { label.append(" "); } else if (Character.isUpperCase(c)) { label.append(' '); label.append(Character.toLowerCase(c)); } else { label.append(c); } } return label.toString(); }
java
public static String labelFromCamelCase(String camel) { StringBuilder label = new StringBuilder(); for (int i = 0; i < camel.length(); i++) { char c = camel.charAt(i); if (Character.isDigit(c)) { if (i > 0 && Character.isAlphabetic(camel.charAt(i - 1))) label.append(" "); } if (c == '_') { label.append(" "); } else if (Character.isUpperCase(c)) { label.append(' '); label.append(Character.toLowerCase(c)); } else { label.append(c); } } return label.toString(); }
[ "public", "static", "String", "labelFromCamelCase", "(", "String", "camel", ")", "{", "StringBuilder", "label", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "camel", ".", "length", "(", ")", ";", "i", "...
Converts a camelcase variable name to a human readable text. @param camel the String to be converted @return the hopefully human readable version
[ "Converts", "a", "camelcase", "variable", "name", "to", "a", "human", "readable", "text", "." ]
43d915f004645b1bbbf2625214294dab0858ba01
https://github.com/stephanrauh/AngularFaces/blob/43d915f004645b1bbbf2625214294dab0858ba01/AngularFaces_2.0/AngularFaces-core/src/main/java/de/beyondjava/angularFaces/core/NGWordUtiltites.java#L31-L49
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/commands/CommandsExecutor.java
CommandsExecutor.findExecutor
AbstractCommandExecution findExecutor( AbstractCommandInstruction instr ) { AbstractCommandExecution result = null; if( RenameCommandInstruction.class.equals( instr.getClass())) result = new RenameCommandExecution((RenameCommandInstruction) instr); else if( ReplicateCommandInstruction.class.equals( instr.getClass())) result = new ReplicateCommandExecution((ReplicateCommandInstruction) instr, this.manager ); else if( AssociateTargetCommandInstruction.class.equals( instr.getClass())) result = new AssociateTargetCommandExecution((AssociateTargetCommandInstruction) instr, this.manager ); else if( BulkCommandInstructions.class.equals( instr.getClass())) result = new BulkCommandExecution((BulkCommandInstructions) instr, this.manager ); else if( ChangeStateCommandInstruction.class.equals( instr.getClass())) result = new ChangeStateCommandExecution((ChangeStateCommandInstruction) instr, this.manager ); else if( CreateInstanceCommandInstruction.class.equals( instr.getClass())) result = new CreateInstanceCommandExecution((CreateInstanceCommandInstruction) instr, this.manager ); else if( EmailCommandInstruction.class.equals( instr.getClass())) result = new EmailCommandExecution((EmailCommandInstruction) instr, this.manager ); else if( WriteCommandInstruction.class.equals( instr.getClass())) result = new WriteCommandExecution((WriteCommandInstruction) instr); else if( AppendCommandInstruction.class.equals( instr.getClass())) result = new AppendCommandExecution((AppendCommandInstruction) instr); else if( ExecuteCommandInstruction.class.equals( instr.getClass())) result = new ExecuteCommandExecution((ExecuteCommandInstruction) instr, this.manager ); return result; }
java
AbstractCommandExecution findExecutor( AbstractCommandInstruction instr ) { AbstractCommandExecution result = null; if( RenameCommandInstruction.class.equals( instr.getClass())) result = new RenameCommandExecution((RenameCommandInstruction) instr); else if( ReplicateCommandInstruction.class.equals( instr.getClass())) result = new ReplicateCommandExecution((ReplicateCommandInstruction) instr, this.manager ); else if( AssociateTargetCommandInstruction.class.equals( instr.getClass())) result = new AssociateTargetCommandExecution((AssociateTargetCommandInstruction) instr, this.manager ); else if( BulkCommandInstructions.class.equals( instr.getClass())) result = new BulkCommandExecution((BulkCommandInstructions) instr, this.manager ); else if( ChangeStateCommandInstruction.class.equals( instr.getClass())) result = new ChangeStateCommandExecution((ChangeStateCommandInstruction) instr, this.manager ); else if( CreateInstanceCommandInstruction.class.equals( instr.getClass())) result = new CreateInstanceCommandExecution((CreateInstanceCommandInstruction) instr, this.manager ); else if( EmailCommandInstruction.class.equals( instr.getClass())) result = new EmailCommandExecution((EmailCommandInstruction) instr, this.manager ); else if( WriteCommandInstruction.class.equals( instr.getClass())) result = new WriteCommandExecution((WriteCommandInstruction) instr); else if( AppendCommandInstruction.class.equals( instr.getClass())) result = new AppendCommandExecution((AppendCommandInstruction) instr); else if( ExecuteCommandInstruction.class.equals( instr.getClass())) result = new ExecuteCommandExecution((ExecuteCommandInstruction) instr, this.manager ); return result; }
[ "AbstractCommandExecution", "findExecutor", "(", "AbstractCommandInstruction", "instr", ")", "{", "AbstractCommandExecution", "result", "=", "null", ";", "if", "(", "RenameCommandInstruction", ".", "class", ".", "equals", "(", "instr", ".", "getClass", "(", ")", ")"...
Finds the right executor for an instruction. @param instr a non-null instruction @return an executor, or null if the instruction is not executable
[ "Finds", "the", "right", "executor", "for", "an", "instruction", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/commands/CommandsExecutor.java#L149-L184
train
stephanrauh/AngularFaces
AngularFaces_2.0/AngularFaces-core/src/main/java/de/beyondjava/angularFaces/core/i18n/I18n.java
I18n.convertPropertyFileLineToJSon
private String convertPropertyFileLineToJSon(String line, String json) { if (line==null) return json; String l = line.trim(); if (l.length()==0 || l.startsWith("//")) return json; boolean inString = l.startsWith("\""); String english; String rest; if (inString) { boolean esc = false; int i = 1; for (; i < l.length(); i++) { if (esc) esc = false; else if (l.charAt(i) == '\\') esc = true; else if (l.charAt(i) == '\"') { i++; break; } } english = l.substring(1, i - 1).replace("\\\"", "\""); rest = l.substring(i).trim(); } else { int pos = l.indexOf('='); if (pos<0) { LOGGER.severe("Illegal entry in language file: \"" + line + "\""); return json; } else { english = l.substring(0, pos).trim(); rest = l.substring(pos); } } if (!rest.startsWith("=")) { LOGGER.severe("Illegal entry in language file: \"" + line + "\""); } else { String translation; rest = rest.substring(1).trim(); if (rest.startsWith("\"")) { int pos = rest.lastIndexOf("\""); if (pos > 1) translation = rest.substring(1, pos).replace("\\\"", "\"").trim(); else translation = rest.replace("\\\"", "\""); // treat incorrect string gracefully } else translation = rest; this.translations.put(english, translation); json += ", \"" + english + "\"" + "," + "\"" + translation + "\""; } return json; }
java
private String convertPropertyFileLineToJSon(String line, String json) { if (line==null) return json; String l = line.trim(); if (l.length()==0 || l.startsWith("//")) return json; boolean inString = l.startsWith("\""); String english; String rest; if (inString) { boolean esc = false; int i = 1; for (; i < l.length(); i++) { if (esc) esc = false; else if (l.charAt(i) == '\\') esc = true; else if (l.charAt(i) == '\"') { i++; break; } } english = l.substring(1, i - 1).replace("\\\"", "\""); rest = l.substring(i).trim(); } else { int pos = l.indexOf('='); if (pos<0) { LOGGER.severe("Illegal entry in language file: \"" + line + "\""); return json; } else { english = l.substring(0, pos).trim(); rest = l.substring(pos); } } if (!rest.startsWith("=")) { LOGGER.severe("Illegal entry in language file: \"" + line + "\""); } else { String translation; rest = rest.substring(1).trim(); if (rest.startsWith("\"")) { int pos = rest.lastIndexOf("\""); if (pos > 1) translation = rest.substring(1, pos).replace("\\\"", "\"").trim(); else translation = rest.replace("\\\"", "\""); // treat incorrect string gracefully } else translation = rest; this.translations.put(english, translation); json += ", \"" + english + "\"" + "," + "\"" + translation + "\""; } return json; }
[ "private", "String", "convertPropertyFileLineToJSon", "(", "String", "line", ",", "String", "json", ")", "{", "if", "(", "line", "==", "null", ")", "return", "json", ";", "String", "l", "=", "line", ".", "trim", "(", ")", ";", "if", "(", "l", ".", "l...
Note this method has a side effect - it also fills the HashMap of translations.
[ "Note", "this", "method", "has", "a", "side", "effect", "-", "it", "also", "fills", "the", "HashMap", "of", "translations", "." ]
43d915f004645b1bbbf2625214294dab0858ba01
https://github.com/stephanrauh/AngularFaces/blob/43d915f004645b1bbbf2625214294dab0858ba01/AngularFaces_2.0/AngularFaces-core/src/main/java/de/beyondjava/angularFaces/core/i18n/I18n.java#L83-L132
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/management/Manager.java
Manager.targetAppears
public void targetAppears( TargetHandler targetItf ) { this.defaultTargetHandlerResolver.addTargetHandler( targetItf ); // When a target is deployed, we may also have to update instance states. // Consider as an example when the DM restarts. Targets may be injected // before and after the pojo was started by iPojo. // See #519 for more details. // Notice we restore instances only when the DM was started (the messaging // must be ready). If it is not started, do nothing. The "start" method // will trigger the restoration. // We consider the DM is started if the timer is not null. if( this.timer != null ) restoreInstancesFrom( targetItf ); }
java
public void targetAppears( TargetHandler targetItf ) { this.defaultTargetHandlerResolver.addTargetHandler( targetItf ); // When a target is deployed, we may also have to update instance states. // Consider as an example when the DM restarts. Targets may be injected // before and after the pojo was started by iPojo. // See #519 for more details. // Notice we restore instances only when the DM was started (the messaging // must be ready). If it is not started, do nothing. The "start" method // will trigger the restoration. // We consider the DM is started if the timer is not null. if( this.timer != null ) restoreInstancesFrom( targetItf ); }
[ "public", "void", "targetAppears", "(", "TargetHandler", "targetItf", ")", "{", "this", ".", "defaultTargetHandlerResolver", ".", "addTargetHandler", "(", "targetItf", ")", ";", "// When a target is deployed, we may also have to update instance states.", "// Consider as an exampl...
This method is invoked by iPojo every time a new target handler appears. @param targetItf the appearing target handler
[ "This", "method", "is", "invoked", "by", "iPojo", "every", "time", "a", "new", "target", "handler", "appears", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/management/Manager.java#L283-L298
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/management/Manager.java
Manager.setTargetResolver
public void setTargetResolver( ITargetHandlerResolver targetHandlerResolver ) { if( targetHandlerResolver == null ) { this.targetConfigurator.setTargetHandlerResolver( this.defaultTargetHandlerResolver ); this.instancesMngr.setTargetHandlerResolver( this.defaultTargetHandlerResolver ); } else { this.targetConfigurator.setTargetHandlerResolver( targetHandlerResolver ); this.instancesMngr.setTargetHandlerResolver( targetHandlerResolver ); } }
java
public void setTargetResolver( ITargetHandlerResolver targetHandlerResolver ) { if( targetHandlerResolver == null ) { this.targetConfigurator.setTargetHandlerResolver( this.defaultTargetHandlerResolver ); this.instancesMngr.setTargetHandlerResolver( this.defaultTargetHandlerResolver ); } else { this.targetConfigurator.setTargetHandlerResolver( targetHandlerResolver ); this.instancesMngr.setTargetHandlerResolver( targetHandlerResolver ); } }
[ "public", "void", "setTargetResolver", "(", "ITargetHandlerResolver", "targetHandlerResolver", ")", "{", "if", "(", "targetHandlerResolver", "==", "null", ")", "{", "this", ".", "targetConfigurator", ".", "setTargetHandlerResolver", "(", "this", ".", "defaultTargetHandl...
Sets the target resolver. @param targetHandlerResolver a resolver for target handlers
[ "Sets", "the", "target", "resolver", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/management/Manager.java#L425-L434
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/management/Manager.java
Manager.restoreAllInstances
void restoreAllInstances() { // instancesMngr() instead of this.instancesMngr (for unit tests). this.logger.fine( "Restoring all the instance states from the current target handlers." ); for( ManagedApplication ma : this.applicationMngr.getManagedApplications()) { // Build a new snapshot on every loop List<TargetHandler> snapshot = this.defaultTargetHandlerResolver.getTargetHandlersSnapshot(); for( TargetHandler targetHandler : snapshot ) instancesMngr().restoreInstanceStates( ma, targetHandler ); } }
java
void restoreAllInstances() { // instancesMngr() instead of this.instancesMngr (for unit tests). this.logger.fine( "Restoring all the instance states from the current target handlers." ); for( ManagedApplication ma : this.applicationMngr.getManagedApplications()) { // Build a new snapshot on every loop List<TargetHandler> snapshot = this.defaultTargetHandlerResolver.getTargetHandlersSnapshot(); for( TargetHandler targetHandler : snapshot ) instancesMngr().restoreInstanceStates( ma, targetHandler ); } }
[ "void", "restoreAllInstances", "(", ")", "{", "// instancesMngr() instead of this.instancesMngr (for unit tests).", "this", ".", "logger", ".", "fine", "(", "\"Restoring all the instance states from the current target handlers.\"", ")", ";", "for", "(", "ManagedApplication", "ma"...
Restores the states of all the instances from the current target handlers.
[ "Restores", "the", "states", "of", "all", "the", "instances", "from", "the", "current", "target", "handlers", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/management/Manager.java#L614-L625
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/management/Manager.java
Manager.restoreInstancesFrom
void restoreInstancesFrom( TargetHandler targetHandler ) { // instancesMngr() instead of this.instancesMngr (for unit tests). this.logger.fine( "Restoring the instance states with the '" + targetHandler.getTargetId() + "' target handler." ); for( ManagedApplication ma : this.applicationMngr.getManagedApplications()) instancesMngr().restoreInstanceStates( ma, targetHandler ); }
java
void restoreInstancesFrom( TargetHandler targetHandler ) { // instancesMngr() instead of this.instancesMngr (for unit tests). this.logger.fine( "Restoring the instance states with the '" + targetHandler.getTargetId() + "' target handler." ); for( ManagedApplication ma : this.applicationMngr.getManagedApplications()) instancesMngr().restoreInstanceStates( ma, targetHandler ); }
[ "void", "restoreInstancesFrom", "(", "TargetHandler", "targetHandler", ")", "{", "// instancesMngr() instead of this.instancesMngr (for unit tests).", "this", ".", "logger", ".", "fine", "(", "\"Restoring the instance states with the '\"", "+", "targetHandler", ".", "getTargetId"...
Restores the states of all the instances from a given target handler.
[ "Restores", "the", "states", "of", "all", "the", "instances", "from", "a", "given", "target", "handler", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/management/Manager.java#L631-L637
train
roboconf/roboconf-platform
core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/factory/MessagingClientFactoryRegistry.java
MessagingClientFactoryRegistry.addMessagingClientFactory
public boolean addMessagingClientFactory(IMessagingClientFactory factory) { final String type = factory.getType(); this.logger.fine("Adding messaging client factory: " + type); final boolean result = this.factories.putIfAbsent(type, factory) == null; if (result) notifyListeners(factory, true); return result; }
java
public boolean addMessagingClientFactory(IMessagingClientFactory factory) { final String type = factory.getType(); this.logger.fine("Adding messaging client factory: " + type); final boolean result = this.factories.putIfAbsent(type, factory) == null; if (result) notifyListeners(factory, true); return result; }
[ "public", "boolean", "addMessagingClientFactory", "(", "IMessagingClientFactory", "factory", ")", "{", "final", "String", "type", "=", "factory", ".", "getType", "(", ")", ";", "this", ".", "logger", ".", "fine", "(", "\"Adding messaging client factory: \"", "+", ...
Adds a messaging client factory to this registry, unless a similar one was already registered. @param factory the messaging client factory to add. @return {@code true} if the factory has been added, {@code false} if a factory with the same type was already registered.
[ "Adds", "a", "messaging", "client", "factory", "to", "this", "registry", "unless", "a", "similar", "one", "was", "already", "registered", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/factory/MessagingClientFactoryRegistry.java#L82-L91
train
roboconf/roboconf-platform
core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/factory/MessagingClientFactoryRegistry.java
MessagingClientFactoryRegistry.removeMessagingClientFactory
public boolean removeMessagingClientFactory(IMessagingClientFactory factory) { final String type = factory.getType(); this.logger.fine("Removing messaging client factory: " + type); final boolean result = this.factories.remove(type, factory); if (result) notifyListeners(factory, false); return result; }
java
public boolean removeMessagingClientFactory(IMessagingClientFactory factory) { final String type = factory.getType(); this.logger.fine("Removing messaging client factory: " + type); final boolean result = this.factories.remove(type, factory); if (result) notifyListeners(factory, false); return result; }
[ "public", "boolean", "removeMessagingClientFactory", "(", "IMessagingClientFactory", "factory", ")", "{", "final", "String", "type", "=", "factory", ".", "getType", "(", ")", ";", "this", ".", "logger", ".", "fine", "(", "\"Removing messaging client factory: \"", "+...
Removes a messaging client factory from this registry. @param factory the messaging client factory to remove. @return {@code true} if the factory has been removed, {@code false} if the factory was not registered.
[ "Removes", "a", "messaging", "client", "factory", "from", "this", "registry", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/factory/MessagingClientFactoryRegistry.java#L98-L107
train
stephanrauh/AngularFaces
AngularFaces_2.0/incubator/AngularFaces-widgets/src/main/java/de/beyondjava/angularFaces/flavors/kendo/puiBody/PuiBody.java
PuiBody.getValueToRender
public static Object getValueToRender(FacesContext context, UIComponent component) { if (component instanceof ValueHolder) { if (component instanceof EditableValueHolder) { EditableValueHolder input = (EditableValueHolder) component; Object submittedValue = input.getSubmittedValue(); ConfigContainer config = RequestContext.getCurrentInstance().getApplicationContext().getConfig(); if (config.isInterpretEmptyStringAsNull() && submittedValue == null && context.isValidationFailed() && !input.isValid()) { return null; } else if (submittedValue != null) { return submittedValue; } } ValueHolder valueHolder = (ValueHolder) component; Object value = valueHolder.getValue(); return value; } // component it not a value holder return null; }
java
public static Object getValueToRender(FacesContext context, UIComponent component) { if (component instanceof ValueHolder) { if (component instanceof EditableValueHolder) { EditableValueHolder input = (EditableValueHolder) component; Object submittedValue = input.getSubmittedValue(); ConfigContainer config = RequestContext.getCurrentInstance().getApplicationContext().getConfig(); if (config.isInterpretEmptyStringAsNull() && submittedValue == null && context.isValidationFailed() && !input.isValid()) { return null; } else if (submittedValue != null) { return submittedValue; } } ValueHolder valueHolder = (ValueHolder) component; Object value = valueHolder.getValue(); return value; } // component it not a value holder return null; }
[ "public", "static", "Object", "getValueToRender", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "{", "if", "(", "component", "instanceof", "ValueHolder", ")", "{", "if", "(", "component", "instanceof", "EditableValueHolder", ")", "{", "Edit...
This method has been copied from the PrimeFaces 5 project. Algorithm works as follows; - If it's an input component, submitted value is checked first since it'd be the value to be used in case validation errors terminates jsf lifecycle - Finally the value of the component is retrieved from backing bean and if there's a converter, converted value is returned @param context FacesContext instance @param component UIComponent instance whose value will be returned @return End text
[ "This", "method", "has", "been", "copied", "from", "the", "PrimeFaces", "5", "project", "." ]
43d915f004645b1bbbf2625214294dab0858ba01
https://github.com/stephanrauh/AngularFaces/blob/43d915f004645b1bbbf2625214294dab0858ba01/AngularFaces_2.0/incubator/AngularFaces-widgets/src/main/java/de/beyondjava/angularFaces/flavors/kendo/puiBody/PuiBody.java#L141-L163
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/management/ManagedApplication.java
ManagedApplication.acknowledgeHeartBeat
public void acknowledgeHeartBeat( Instance scopedInstance ) { String count = scopedInstance.data.get( MISSED_HEARTBEATS ); if( count != null && Integer.parseInt( count ) > THRESHOLD ) this.logger.info( "Agent " + InstanceHelpers.computeInstancePath( scopedInstance ) + " is alive and reachable again." ); // Store the moment the first ACK (without interruption) was received. // If we were deploying, store it. // If we were in problem, store it. // If we were already deployed and started, do NOT override it. if( scopedInstance.getStatus() != InstanceStatus.DEPLOYED_STARTED || ! scopedInstance.data.containsKey( Instance.RUNNING_FROM )) scopedInstance.data.put( Instance.RUNNING_FROM, String.valueOf( new Date().getTime())); scopedInstance.setStatus( InstanceStatus.DEPLOYED_STARTED ); scopedInstance.data.remove( MISSED_HEARTBEATS ); }
java
public void acknowledgeHeartBeat( Instance scopedInstance ) { String count = scopedInstance.data.get( MISSED_HEARTBEATS ); if( count != null && Integer.parseInt( count ) > THRESHOLD ) this.logger.info( "Agent " + InstanceHelpers.computeInstancePath( scopedInstance ) + " is alive and reachable again." ); // Store the moment the first ACK (without interruption) was received. // If we were deploying, store it. // If we were in problem, store it. // If we were already deployed and started, do NOT override it. if( scopedInstance.getStatus() != InstanceStatus.DEPLOYED_STARTED || ! scopedInstance.data.containsKey( Instance.RUNNING_FROM )) scopedInstance.data.put( Instance.RUNNING_FROM, String.valueOf( new Date().getTime())); scopedInstance.setStatus( InstanceStatus.DEPLOYED_STARTED ); scopedInstance.data.remove( MISSED_HEARTBEATS ); }
[ "public", "void", "acknowledgeHeartBeat", "(", "Instance", "scopedInstance", ")", "{", "String", "count", "=", "scopedInstance", ".", "data", ".", "get", "(", "MISSED_HEARTBEATS", ")", ";", "if", "(", "count", "!=", "null", "&&", "Integer", ".", "parseInt", ...
Acknowledges a heart beat. @param scopedInstance a root instance
[ "Acknowledges", "a", "heart", "beat", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/management/ManagedApplication.java#L167-L184
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/management/ManagedApplication.java
ManagedApplication.checkStates
public void checkStates( INotificationMngr notificationMngr ) { // Check the status of scoped instances Collection<Instance> scopedInstances = InstanceHelpers.findAllScopedInstances( this.application ); for( Instance scopedInstance : scopedInstances ) { // Never started instances, // or scoped instances that have been stopped by an agent, // are not processed anymore here if( scopedInstance.getStatus() == InstanceStatus.NOT_DEPLOYED || scopedInstance.getStatus() == InstanceStatus.DEPLOYING || scopedInstance.getStatus() == InstanceStatus.UNDEPLOYING ) { scopedInstance.data.remove( MISSED_HEARTBEATS ); continue; } // Otherwise String countAs = scopedInstance.data.get( MISSED_HEARTBEATS ); int count = countAs == null ? 0 : Integer.parseInt( countAs ); if( ++ count > THRESHOLD ) { scopedInstance.setStatus( InstanceStatus.PROBLEM ); notificationMngr.instance( scopedInstance, this.application, EventType.CHANGED ); this.logger.severe( "Agent " + InstanceHelpers.computeInstancePath( scopedInstance ) + " has not sent heart beats for quite a long time. Status changed to PROBLEM." ); } scopedInstance.data.put( MISSED_HEARTBEATS, String.valueOf( count )); } }
java
public void checkStates( INotificationMngr notificationMngr ) { // Check the status of scoped instances Collection<Instance> scopedInstances = InstanceHelpers.findAllScopedInstances( this.application ); for( Instance scopedInstance : scopedInstances ) { // Never started instances, // or scoped instances that have been stopped by an agent, // are not processed anymore here if( scopedInstance.getStatus() == InstanceStatus.NOT_DEPLOYED || scopedInstance.getStatus() == InstanceStatus.DEPLOYING || scopedInstance.getStatus() == InstanceStatus.UNDEPLOYING ) { scopedInstance.data.remove( MISSED_HEARTBEATS ); continue; } // Otherwise String countAs = scopedInstance.data.get( MISSED_HEARTBEATS ); int count = countAs == null ? 0 : Integer.parseInt( countAs ); if( ++ count > THRESHOLD ) { scopedInstance.setStatus( InstanceStatus.PROBLEM ); notificationMngr.instance( scopedInstance, this.application, EventType.CHANGED ); this.logger.severe( "Agent " + InstanceHelpers.computeInstancePath( scopedInstance ) + " has not sent heart beats for quite a long time. Status changed to PROBLEM." ); } scopedInstance.data.put( MISSED_HEARTBEATS, String.valueOf( count )); } }
[ "public", "void", "checkStates", "(", "INotificationMngr", "notificationMngr", ")", "{", "// Check the status of scoped instances", "Collection", "<", "Instance", ">", "scopedInstances", "=", "InstanceHelpers", ".", "findAllScopedInstances", "(", "this", ".", "application",...
Check the scoped instances states with respect to missed heart beats. @param notificationMngr
[ "Check", "the", "scoped", "instances", "states", "with", "respect", "to", "missed", "heart", "beats", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/management/ManagedApplication.java#L191-L218
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/utils/DmUtils.java
DmUtils.markScopedInstanceAsNotDeployed
public static void markScopedInstanceAsNotDeployed( Instance scopedInstance, ManagedApplication ma, INotificationMngr notificationMngr, IInstancesMngr instanceMngr ) { scopedInstance.data.remove( Instance.IP_ADDRESS ); scopedInstance.data.remove( Instance.MACHINE_ID ); scopedInstance.data.remove( Instance.TARGET_ACQUIRED ); scopedInstance.data.remove( Instance.RUNNING_FROM ); scopedInstance.data.remove( Instance.READY_FOR_CFG_MARKER ); // Update states List<Instance> instancesToDelete = new ArrayList<> (); for( Instance i : InstanceHelpers.buildHierarchicalList( scopedInstance )) { InstanceStatus oldstatus = i.getStatus(); i.setStatus( InstanceStatus.NOT_DEPLOYED ); // Send a notification only if there was a change if( oldstatus != InstanceStatus.NOT_DEPLOYED ) notificationMngr.instance( i, ma.getApplication(), EventType.CHANGED ); // DM won't send old imports upon restart... i.getImports().clear(); // Do we need to delete the instance? if( i.data.containsKey( Instance.DELETE_WHEN_NOT_DEPLOYED )) instancesToDelete.add( i ); } // Delete instances Collections.reverse( instancesToDelete ); for( Instance i : instancesToDelete ) { try { instanceMngr.removeInstance( ma, i, true ); } catch( Exception e ) { Logger logger = Logger.getLogger( DmUtils.class.getName()); logger.severe( "An error occurred while deleting an instance marked with DELETE_WHEN_NOT_DEPLOYED. Instance = " + InstanceHelpers.computeInstancePath( i ) + " App = " + ma.getName()); Utils.logException( logger, e ); } } }
java
public static void markScopedInstanceAsNotDeployed( Instance scopedInstance, ManagedApplication ma, INotificationMngr notificationMngr, IInstancesMngr instanceMngr ) { scopedInstance.data.remove( Instance.IP_ADDRESS ); scopedInstance.data.remove( Instance.MACHINE_ID ); scopedInstance.data.remove( Instance.TARGET_ACQUIRED ); scopedInstance.data.remove( Instance.RUNNING_FROM ); scopedInstance.data.remove( Instance.READY_FOR_CFG_MARKER ); // Update states List<Instance> instancesToDelete = new ArrayList<> (); for( Instance i : InstanceHelpers.buildHierarchicalList( scopedInstance )) { InstanceStatus oldstatus = i.getStatus(); i.setStatus( InstanceStatus.NOT_DEPLOYED ); // Send a notification only if there was a change if( oldstatus != InstanceStatus.NOT_DEPLOYED ) notificationMngr.instance( i, ma.getApplication(), EventType.CHANGED ); // DM won't send old imports upon restart... i.getImports().clear(); // Do we need to delete the instance? if( i.data.containsKey( Instance.DELETE_WHEN_NOT_DEPLOYED )) instancesToDelete.add( i ); } // Delete instances Collections.reverse( instancesToDelete ); for( Instance i : instancesToDelete ) { try { instanceMngr.removeInstance( ma, i, true ); } catch( Exception e ) { Logger logger = Logger.getLogger( DmUtils.class.getName()); logger.severe( "An error occurred while deleting an instance marked with DELETE_WHEN_NOT_DEPLOYED. Instance = " + InstanceHelpers.computeInstancePath( i ) + " App = " + ma.getName()); Utils.logException( logger, e ); } } }
[ "public", "static", "void", "markScopedInstanceAsNotDeployed", "(", "Instance", "scopedInstance", ",", "ManagedApplication", "ma", ",", "INotificationMngr", "notificationMngr", ",", "IInstancesMngr", "instanceMngr", ")", "{", "scopedInstance", ".", "data", ".", "remove", ...
Updates a scoped instance and its children to be marked as not deployed. @param scopedInstance a non-null scoped instance @param ma the managed application @param notificationMngr the notification manager (not null) @param instanceMngr the instances manager (not null)
[ "Updates", "a", "scoped", "instance", "and", "its", "children", "to", "be", "marked", "as", "not", "deployed", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/utils/DmUtils.java#L62-L109
train
roboconf/roboconf-platform
miscellaneous/roboconf-doc-generator/src/main/java/net/roboconf/doc/generator/internal/transformers/HierarchicalTransformer.java
HierarchicalTransformer.dealWithMainComponent
private void dealWithMainComponent() { this.typeToLocation.put( this.component, new Point2D.Double( this.hMargin, this.currentHeigth )); int width = H_PADDING + GraphUtils.computeShapeWidth( this.component ); this.maxRowWidth = Math.max( this.maxRowWidth, width ); this.aloneOnRow.add( this.component ); }
java
private void dealWithMainComponent() { this.typeToLocation.put( this.component, new Point2D.Double( this.hMargin, this.currentHeigth )); int width = H_PADDING + GraphUtils.computeShapeWidth( this.component ); this.maxRowWidth = Math.max( this.maxRowWidth, width ); this.aloneOnRow.add( this.component ); }
[ "private", "void", "dealWithMainComponent", "(", ")", "{", "this", ".", "typeToLocation", ".", "put", "(", "this", ".", "component", ",", "new", "Point2D", ".", "Double", "(", "this", ".", "hMargin", ",", "this", ".", "currentHeigth", ")", ")", ";", "int...
Finds the position for the main component.
[ "Finds", "the", "position", "for", "the", "main", "component", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-doc-generator/src/main/java/net/roboconf/doc/generator/internal/transformers/HierarchicalTransformer.java#L140-L149
train
roboconf/roboconf-platform
miscellaneous/roboconf-doc-generator/src/main/java/net/roboconf/doc/generator/internal/transformers/HierarchicalTransformer.java
HierarchicalTransformer.dealWithOthers
private void dealWithOthers( Collection<AbstractType> others ) { int col = 1; this.currentWidth = this.hMargin; for( AbstractType t : others ) { if( col > this.maxPerLine ) { col = 1; this.currentHeigth += V_PADDING + GraphUtils.SHAPE_HEIGHT; this.currentWidth = this.hMargin; } this.typeToLocation.put( t, new Point2D.Double( this.currentWidth, this.currentHeigth )); this.currentWidth += H_PADDING + GraphUtils.computeShapeWidth( t ); col ++; this.maxRowWidth = Math.max( this.maxRowWidth, this.currentWidth ); } if( others.size() == 1 ) this.aloneOnRow.add( others.iterator().next()); }
java
private void dealWithOthers( Collection<AbstractType> others ) { int col = 1; this.currentWidth = this.hMargin; for( AbstractType t : others ) { if( col > this.maxPerLine ) { col = 1; this.currentHeigth += V_PADDING + GraphUtils.SHAPE_HEIGHT; this.currentWidth = this.hMargin; } this.typeToLocation.put( t, new Point2D.Double( this.currentWidth, this.currentHeigth )); this.currentWidth += H_PADDING + GraphUtils.computeShapeWidth( t ); col ++; this.maxRowWidth = Math.max( this.maxRowWidth, this.currentWidth ); } if( others.size() == 1 ) this.aloneOnRow.add( others.iterator().next()); }
[ "private", "void", "dealWithOthers", "(", "Collection", "<", "AbstractType", ">", "others", ")", "{", "int", "col", "=", "1", ";", "this", ".", "currentWidth", "=", "this", ".", "hMargin", ";", "for", "(", "AbstractType", "t", ":", "others", ")", "{", ...
Finds the position of other components. @param others a non-null list of components
[ "Finds", "the", "position", "of", "other", "components", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-doc-generator/src/main/java/net/roboconf/doc/generator/internal/transformers/HierarchicalTransformer.java#L156-L177
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/UriUtils.java
UriUtils.buildNewURI
public static URI buildNewURI( URI referenceUri, String uriSuffix ) throws URISyntaxException { if( uriSuffix == null ) throw new IllegalArgumentException( "The URI suffix cannot be null." ); uriSuffix = uriSuffix.replaceAll( "\\\\", "/" ); URI importUri = null; try { // Absolute URL ? importUri = urlToUri( new URL( uriSuffix )); } catch( Exception e ) { try { // Relative URL ? if( ! referenceUri.toString().endsWith( "/" ) && ! uriSuffix.startsWith( "/" )) referenceUri = new URI( referenceUri.toString() + "/" ); importUri = referenceUri.resolve( new URI( null, uriSuffix, null )); } catch( Exception e2 ) { String msg = "An URI could not be built from the URI " + referenceUri.toString() + " and the suffix " + uriSuffix + "."; throw new URISyntaxException( msg, e2.getMessage()); } } return importUri.normalize(); }
java
public static URI buildNewURI( URI referenceUri, String uriSuffix ) throws URISyntaxException { if( uriSuffix == null ) throw new IllegalArgumentException( "The URI suffix cannot be null." ); uriSuffix = uriSuffix.replaceAll( "\\\\", "/" ); URI importUri = null; try { // Absolute URL ? importUri = urlToUri( new URL( uriSuffix )); } catch( Exception e ) { try { // Relative URL ? if( ! referenceUri.toString().endsWith( "/" ) && ! uriSuffix.startsWith( "/" )) referenceUri = new URI( referenceUri.toString() + "/" ); importUri = referenceUri.resolve( new URI( null, uriSuffix, null )); } catch( Exception e2 ) { String msg = "An URI could not be built from the URI " + referenceUri.toString() + " and the suffix " + uriSuffix + "."; throw new URISyntaxException( msg, e2.getMessage()); } } return importUri.normalize(); }
[ "public", "static", "URI", "buildNewURI", "(", "URI", "referenceUri", ",", "String", "uriSuffix", ")", "throws", "URISyntaxException", "{", "if", "(", "uriSuffix", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"The URI suffix cannot be null.\""...
Builds an URI from an URI and a suffix. <p> This suffix can be an absolute URL, or a relative path with respect to the first URI. In this case, the suffix is resolved with respect to the URI. </p> <p> If the suffix is already an URL, its is returned.<br> If the suffix is a relative file path and cannot be resolved, an exception is thrown. </p> <p> The returned URI is normalized. </p> @param referenceUri the reference URI (can be null) @param uriSuffix the URI suffix (not null) @return the new URI @throws URISyntaxException if the resolution failed
[ "Builds", "an", "URI", "from", "an", "URI", "and", "a", "suffix", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/UriUtils.java#L122-L151
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/ProgramUtils.java
ProgramUtils.executeCommand
public static int executeCommand( final Logger logger, final String[] command, final File workingDir, final Map<String,String> environmentVars, final String applicationName, final String scopedInstancePath) throws IOException, InterruptedException { ExecutionResult result = executeCommandWithResult( logger, command, workingDir, environmentVars, applicationName, scopedInstancePath); if( ! Utils.isEmptyOrWhitespaces( result.getNormalOutput())) logger.fine( result.getNormalOutput()); if( ! Utils.isEmptyOrWhitespaces( result.getErrorOutput())) logger.warning( result.getErrorOutput()); return result.getExitValue(); }
java
public static int executeCommand( final Logger logger, final String[] command, final File workingDir, final Map<String,String> environmentVars, final String applicationName, final String scopedInstancePath) throws IOException, InterruptedException { ExecutionResult result = executeCommandWithResult( logger, command, workingDir, environmentVars, applicationName, scopedInstancePath); if( ! Utils.isEmptyOrWhitespaces( result.getNormalOutput())) logger.fine( result.getNormalOutput()); if( ! Utils.isEmptyOrWhitespaces( result.getErrorOutput())) logger.warning( result.getErrorOutput()); return result.getExitValue(); }
[ "public", "static", "int", "executeCommand", "(", "final", "Logger", "logger", ",", "final", "String", "[", "]", "command", ",", "final", "File", "workingDir", ",", "final", "Map", "<", "String", ",", "String", ">", "environmentVars", ",", "final", "String",...
Executes a command on the VM and logs the output. @param logger a logger (not null) @param command a command to execute (not null, not empty) @param workingDir the working directory for the command @param environmentVars a map containing environment variables (can be null) @param applicationName the roboconf application name (null if not specified) @param scopedInstancePath the roboconf scoped instance path (null if not specified) @throws IOException if a new process could not be created @throws InterruptedException if the new process encountered a process
[ "Executes", "a", "command", "on", "the", "VM", "and", "logs", "the", "output", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/ProgramUtils.java#L137-L154
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/ProgramUtils.java
ProgramUtils.executeCommand
public static int executeCommand( final Logger logger, final List<String> command, final File workingDir, final Map<String,String> environmentVars, final String applicationName, final String scopedInstanceName) throws IOException, InterruptedException { return executeCommand( logger, command.toArray( new String[ 0 ]), workingDir, environmentVars, applicationName, scopedInstanceName); }
java
public static int executeCommand( final Logger logger, final List<String> command, final File workingDir, final Map<String,String> environmentVars, final String applicationName, final String scopedInstanceName) throws IOException, InterruptedException { return executeCommand( logger, command.toArray( new String[ 0 ]), workingDir, environmentVars, applicationName, scopedInstanceName); }
[ "public", "static", "int", "executeCommand", "(", "final", "Logger", "logger", ",", "final", "List", "<", "String", ">", "command", ",", "final", "File", "workingDir", ",", "final", "Map", "<", "String", ",", "String", ">", "environmentVars", ",", "final", ...
Executes a command on the VM and prints on the console its output. @param command a command to execute (not null, not empty) @param environmentVars a map containing environment variables (can be null) @param logger a logger (not null) @throws IOException if a new process could not be created @throws InterruptedException if the new process encountered a process
[ "Executes", "a", "command", "on", "the", "VM", "and", "prints", "on", "the", "console", "its", "output", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/ProgramUtils.java#L165-L175
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/DockerfileParser.java
DockerfileParser.dockerfileToCommandList
public static List<DockerCommand> dockerfileToCommandList( File dockerfile ) throws IOException { List<DockerCommand> result = new ArrayList<>(); FileInputStream in = new FileInputStream( dockerfile ); Logger logger = Logger.getLogger( DockerfileParser.class.getName()); BufferedReader br = null; try { br = new BufferedReader( new InputStreamReader( in, StandardCharsets.UTF_8 )); String line; while((line = br.readLine()) != null) { DockerCommand cmd = DockerCommand.guess(line); if( cmd != null ) result.add( cmd ); else logger.fine("Ignoring unsupported Docker instruction: " + line ); } } finally { Utils.closeQuietly( br ); Utils.closeQuietly( in ); } return result; }
java
public static List<DockerCommand> dockerfileToCommandList( File dockerfile ) throws IOException { List<DockerCommand> result = new ArrayList<>(); FileInputStream in = new FileInputStream( dockerfile ); Logger logger = Logger.getLogger( DockerfileParser.class.getName()); BufferedReader br = null; try { br = new BufferedReader( new InputStreamReader( in, StandardCharsets.UTF_8 )); String line; while((line = br.readLine()) != null) { DockerCommand cmd = DockerCommand.guess(line); if( cmd != null ) result.add( cmd ); else logger.fine("Ignoring unsupported Docker instruction: " + line ); } } finally { Utils.closeQuietly( br ); Utils.closeQuietly( in ); } return result; }
[ "public", "static", "List", "<", "DockerCommand", ">", "dockerfileToCommandList", "(", "File", "dockerfile", ")", "throws", "IOException", "{", "List", "<", "DockerCommand", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "FileInputStream", "in", ...
Parses a dockerfile to a list of commands. @throws IOException @param dockerfile a file @return a list of Docker commands
[ "Parses", "a", "dockerfile", "to", "a", "list", "of", "commands", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/DockerfileParser.java#L59-L84
train
roboconf/roboconf-platform
core/roboconf-dm-rest-services/src/main/java/net/roboconf/dm/rest/services/internal/RestApplication.java
RestApplication.enableCors
public void enableCors( boolean enableCors ) { if( enableCors ) getProperties().put( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, ResponseCorsFilter.class.getName()); else getProperties().remove( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS ); }
java
public void enableCors( boolean enableCors ) { if( enableCors ) getProperties().put( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, ResponseCorsFilter.class.getName()); else getProperties().remove( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS ); }
[ "public", "void", "enableCors", "(", "boolean", "enableCors", ")", "{", "if", "(", "enableCors", ")", "getProperties", "(", ")", ".", "put", "(", "ResourceConfig", ".", "PROPERTY_CONTAINER_RESPONSE_FILTERS", ",", "ResponseCorsFilter", ".", "class", ".", "getName",...
Enables or disables CORS. @param enableCors true to enable it
[ "Enables", "or", "disables", "CORS", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-rest-services/src/main/java/net/roboconf/dm/rest/services/internal/RestApplication.java#L169-L175
train
roboconf/roboconf-platform
core/roboconf-target-iaas-occi/src/main/java/net/roboconf/target/occi/internal/OcciVMUtils.java
OcciVMUtils.getVMIP
public static String getVMIP(String hostIpPort, String id) throws TargetException { //TODO Expecting more interoperable implem... /compute/urn:uuid:ID for Scalair, /ID for CA ! if(! hostIpPort.endsWith("/compute") && id.startsWith("urn:uuid:")) id = id.substring(9); String vmIp = null; URL url = null; try { CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); url = new URL("http://" + hostIpPort + "/" + id); } catch (MalformedURLException e) { throw new TargetException(e); } HttpURLConnection httpURLConnection = null; DataInputStream in = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setRequestProperty("Accept", "application/json"); in = new DataInputStream(httpURLConnection.getInputStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); Utils.copyStreamSafely(in, out); // Parse JSON response to extract VM IP ObjectMapper objectMapper = new ObjectMapper(); JsonResponse rsp = objectMapper.readValue(out.toString( "UTF-8" ), JsonResponse.class); vmIp = rsp.getHostsystemname(); if(Utils.isEmptyOrWhitespaces(vmIp)) vmIp = rsp.getHostname(); if(Utils.isEmptyOrWhitespaces(vmIp) && rsp.getAttributes() != null) vmIp = rsp.getAttributes().getHostname(); } catch (IOException e) { throw new TargetException(e); } finally { Utils.closeQuietly(in); if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return vmIp; }
java
public static String getVMIP(String hostIpPort, String id) throws TargetException { //TODO Expecting more interoperable implem... /compute/urn:uuid:ID for Scalair, /ID for CA ! if(! hostIpPort.endsWith("/compute") && id.startsWith("urn:uuid:")) id = id.substring(9); String vmIp = null; URL url = null; try { CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); url = new URL("http://" + hostIpPort + "/" + id); } catch (MalformedURLException e) { throw new TargetException(e); } HttpURLConnection httpURLConnection = null; DataInputStream in = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setRequestProperty("Accept", "application/json"); in = new DataInputStream(httpURLConnection.getInputStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); Utils.copyStreamSafely(in, out); // Parse JSON response to extract VM IP ObjectMapper objectMapper = new ObjectMapper(); JsonResponse rsp = objectMapper.readValue(out.toString( "UTF-8" ), JsonResponse.class); vmIp = rsp.getHostsystemname(); if(Utils.isEmptyOrWhitespaces(vmIp)) vmIp = rsp.getHostname(); if(Utils.isEmptyOrWhitespaces(vmIp) && rsp.getAttributes() != null) vmIp = rsp.getAttributes().getHostname(); } catch (IOException e) { throw new TargetException(e); } finally { Utils.closeQuietly(in); if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return vmIp; }
[ "public", "static", "String", "getVMIP", "(", "String", "hostIpPort", ",", "String", "id", ")", "throws", "TargetException", "{", "//TODO Expecting more interoperable implem... /compute/urn:uuid:ID for Scalair, /ID for CA !", "if", "(", "!", "hostIpPort", ".", "endsWith", "...
Retrieves VM IP. @param hostIpPort IP and port of OCCI server (eg. "172.16.225.91:8080") @param id Unique VM ID @return The VM's IP address @throws TargetException
[ "Retrieves", "VM", "IP", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-occi/src/main/java/net/roboconf/target/occi/internal/OcciVMUtils.java#L578-L621
train
roboconf/roboconf-platform
core/roboconf-target-iaas-occi/src/main/java/net/roboconf/target/occi/internal/OcciVMUtils.java
OcciVMUtils.isVMRunning
public static boolean isVMRunning(String hostIpPort, String id) throws TargetException { boolean result = false; String ip = OcciVMUtils.getVMIP(hostIpPort, id); try { InetAddress inet = InetAddress.getByName(ip); result = inet.isReachable(5000); } catch (Exception e) { result = false; final Logger logger = Logger.getLogger( OcciVMUtils.class.getName()); logger.info(e.getMessage()); } return result; }
java
public static boolean isVMRunning(String hostIpPort, String id) throws TargetException { boolean result = false; String ip = OcciVMUtils.getVMIP(hostIpPort, id); try { InetAddress inet = InetAddress.getByName(ip); result = inet.isReachable(5000); } catch (Exception e) { result = false; final Logger logger = Logger.getLogger( OcciVMUtils.class.getName()); logger.info(e.getMessage()); } return result; }
[ "public", "static", "boolean", "isVMRunning", "(", "String", "hostIpPort", ",", "String", "id", ")", "throws", "TargetException", "{", "boolean", "result", "=", "false", ";", "String", "ip", "=", "OcciVMUtils", ".", "getVMIP", "(", "hostIpPort", ",", "id", "...
Checks if VM is running. @param hostIpPort @param id @return @throws TargetException
[ "Checks", "if", "VM", "is", "running", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-occi/src/main/java/net/roboconf/target/occi/internal/OcciVMUtils.java#L630-L645
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/TargetsMngrImpl.java
TargetsMngrImpl.createTarget
@Override public String createTarget( String targetContent ) throws IOException { // Get the target ID TargetValidator tv = new TargetValidator( targetContent ); tv.validate(); if( RoboconfErrorHelpers.containsCriticalErrors( tv.getErrors())) throw new IOException( "There are errors in the target definition." ); // Critical section to insert a target. // Store the ID, it cannot be reused. String targetId = tv.getProperties().getProperty( Constants.TARGET_PROPERTY_ID ); String creator = tv.getProperties().getProperty( CREATED_BY ); if( this.targetIds.putIfAbsent( targetId, Boolean.TRUE ) != null ) { // No creator? Then there is a conflict. if( creator == null ) throw new IOException( "ID " + targetId + " is already used." ); // It cannot be reused, unless they were created by the same template. File createdByFile = new File( findTargetDirectory( targetId ), CREATED_BY ); String storedCreator = null; if( createdByFile.exists()) storedCreator = Utils.readFileContent( createdByFile ); // If they do not match, throw an exception if( ! Objects.equals( creator, storedCreator )) throw new IOException( "ID " + targetId + " is already used." ); // Otherwise, we can override the properties } // Rewrite the properties without the ID. // We do not want it to be modified later. // We do not serialize java.util.properties#store because it adds // a time stamp, removes user comments and looses the properties order. targetContent = targetContent.replaceAll( Constants.TARGET_PROPERTY_ID + "\\s*(:|=)[^\n]*(\n|$)", "" ); // For the same reason, we remove the "created.by" property targetContent = targetContent.replaceAll( "\n\n" + Pattern.quote( CREATED_BY ) + "\\s*(:|=)[^\n]*(\n|$)", "" ); // Write the properties File targetFile = new File( findTargetDirectory( targetId ), Constants.TARGET_PROPERTIES_FILE_NAME ); Utils.createDirectory( targetFile.getParentFile()); Utils.writeStringInto( targetContent, targetFile ); // Write the creator, if any if( creator != null ) { File createdByFile = new File( findTargetDirectory( targetId ), CREATED_BY ); Utils.writeStringInto( creator, createdByFile ); } return targetId; }
java
@Override public String createTarget( String targetContent ) throws IOException { // Get the target ID TargetValidator tv = new TargetValidator( targetContent ); tv.validate(); if( RoboconfErrorHelpers.containsCriticalErrors( tv.getErrors())) throw new IOException( "There are errors in the target definition." ); // Critical section to insert a target. // Store the ID, it cannot be reused. String targetId = tv.getProperties().getProperty( Constants.TARGET_PROPERTY_ID ); String creator = tv.getProperties().getProperty( CREATED_BY ); if( this.targetIds.putIfAbsent( targetId, Boolean.TRUE ) != null ) { // No creator? Then there is a conflict. if( creator == null ) throw new IOException( "ID " + targetId + " is already used." ); // It cannot be reused, unless they were created by the same template. File createdByFile = new File( findTargetDirectory( targetId ), CREATED_BY ); String storedCreator = null; if( createdByFile.exists()) storedCreator = Utils.readFileContent( createdByFile ); // If they do not match, throw an exception if( ! Objects.equals( creator, storedCreator )) throw new IOException( "ID " + targetId + " is already used." ); // Otherwise, we can override the properties } // Rewrite the properties without the ID. // We do not want it to be modified later. // We do not serialize java.util.properties#store because it adds // a time stamp, removes user comments and looses the properties order. targetContent = targetContent.replaceAll( Constants.TARGET_PROPERTY_ID + "\\s*(:|=)[^\n]*(\n|$)", "" ); // For the same reason, we remove the "created.by" property targetContent = targetContent.replaceAll( "\n\n" + Pattern.quote( CREATED_BY ) + "\\s*(:|=)[^\n]*(\n|$)", "" ); // Write the properties File targetFile = new File( findTargetDirectory( targetId ), Constants.TARGET_PROPERTIES_FILE_NAME ); Utils.createDirectory( targetFile.getParentFile()); Utils.writeStringInto( targetContent, targetFile ); // Write the creator, if any if( creator != null ) { File createdByFile = new File( findTargetDirectory( targetId ), CREATED_BY ); Utils.writeStringInto( creator, createdByFile ); } return targetId; }
[ "@", "Override", "public", "String", "createTarget", "(", "String", "targetContent", ")", "throws", "IOException", "{", "// Get the target ID", "TargetValidator", "tv", "=", "new", "TargetValidator", "(", "targetContent", ")", ";", "tv", ".", "validate", "(", ")",...
CRUD operations on targets
[ "CRUD", "operations", "on", "targets" ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/TargetsMngrImpl.java#L119-L172
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/TargetsMngrImpl.java
TargetsMngrImpl.findScriptResourcesForAgent
@Override public Map<String,byte[]> findScriptResourcesForAgent( String targetId ) throws IOException { Map<String,byte[]> result = new HashMap<>( 0 ); File targetDir = new File( findTargetDirectory( targetId ), Constants.PROJECT_SUB_DIR_SCRIPTS ); if( targetDir.isDirectory()){ List<String> exclusionPatterns = Arrays.asList( "(?i).*" + Pattern.quote( Constants.LOCAL_RESOURCE_PREFIX ) + ".*" ); result.putAll( Utils.storeDirectoryResourcesAsBytes( targetDir, exclusionPatterns )); } return result; }
java
@Override public Map<String,byte[]> findScriptResourcesForAgent( String targetId ) throws IOException { Map<String,byte[]> result = new HashMap<>( 0 ); File targetDir = new File( findTargetDirectory( targetId ), Constants.PROJECT_SUB_DIR_SCRIPTS ); if( targetDir.isDirectory()){ List<String> exclusionPatterns = Arrays.asList( "(?i).*" + Pattern.quote( Constants.LOCAL_RESOURCE_PREFIX ) + ".*" ); result.putAll( Utils.storeDirectoryResourcesAsBytes( targetDir, exclusionPatterns )); } return result; }
[ "@", "Override", "public", "Map", "<", "String", ",", "byte", "[", "]", ">", "findScriptResourcesForAgent", "(", "String", "targetId", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "byte", "[", "]", ">", "result", "=", "new", "HashMap", "...
Finding script resources
[ "Finding", "script", "resources" ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/TargetsMngrImpl.java#L473-L488
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/TargetsMngrImpl.java
TargetsMngrImpl.listPossibleTargets
@Override public List<TargetWrapperDescriptor> listPossibleTargets( AbstractApplication app ) { // Find the matching targets based on registered hints String key = new InstanceContext( app ).toString(); String tplKey = null; if( app instanceof Application ) tplKey = new InstanceContext(((Application) app).getTemplate()).toString(); List<File> targetDirectories = new ArrayList<> (); File dir = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS ); for( File f : Utils.listDirectories( dir )) { // If there is no hint for this target, then it is global. // We can list it. File hintsFile = new File( f, TARGETS_HINTS_FILE ); if( ! hintsFile.exists()) { targetDirectories.add( f ); continue; } // Otherwise, the key must exist in the file Properties props = Utils.readPropertiesFileQuietly( hintsFile, this.logger ); if( props.containsKey( key )) targetDirectories.add( f ); else if( tplKey != null && props.containsKey( tplKey )) targetDirectories.add( f ); } // Build the result return buildList( targetDirectories, app ); }
java
@Override public List<TargetWrapperDescriptor> listPossibleTargets( AbstractApplication app ) { // Find the matching targets based on registered hints String key = new InstanceContext( app ).toString(); String tplKey = null; if( app instanceof Application ) tplKey = new InstanceContext(((Application) app).getTemplate()).toString(); List<File> targetDirectories = new ArrayList<> (); File dir = new File( this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS ); for( File f : Utils.listDirectories( dir )) { // If there is no hint for this target, then it is global. // We can list it. File hintsFile = new File( f, TARGETS_HINTS_FILE ); if( ! hintsFile.exists()) { targetDirectories.add( f ); continue; } // Otherwise, the key must exist in the file Properties props = Utils.readPropertiesFileQuietly( hintsFile, this.logger ); if( props.containsKey( key )) targetDirectories.add( f ); else if( tplKey != null && props.containsKey( tplKey )) targetDirectories.add( f ); } // Build the result return buildList( targetDirectories, app ); }
[ "@", "Override", "public", "List", "<", "TargetWrapperDescriptor", ">", "listPossibleTargets", "(", "AbstractApplication", "app", ")", "{", "// Find the matching targets based on registered hints", "String", "key", "=", "new", "InstanceContext", "(", "app", ")", ".", "t...
In relation with hints
[ "In", "relation", "with", "hints" ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/TargetsMngrImpl.java#L547-L578
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/TargetsMngrImpl.java
TargetsMngrImpl.lockAndGetTarget
@Override public TargetProperties lockAndGetTarget( Application app, Instance scopedInstance ) throws IOException { String instancePath = InstanceHelpers.computeInstancePath( scopedInstance ); String targetId = findTargetId( app, instancePath ); if( targetId == null ) throw new IOException( "No target was found for " + app + " :: " + instancePath ); InstanceContext mappingKey = new InstanceContext( app, instancePath ); synchronized( LOCK ) { saveUsage( mappingKey, targetId, true ); } this.logger.fine( "Target " + targetId + "'s lock was acquired for " + instancePath ); TargetProperties result = findTargetProperties( app, instancePath ); Map<String,String> newTargetProperties = TargetHelpers.expandProperties( scopedInstance, result.asMap()); result.asMap().clear(); result.asMap().putAll( newTargetProperties ); return result; }
java
@Override public TargetProperties lockAndGetTarget( Application app, Instance scopedInstance ) throws IOException { String instancePath = InstanceHelpers.computeInstancePath( scopedInstance ); String targetId = findTargetId( app, instancePath ); if( targetId == null ) throw new IOException( "No target was found for " + app + " :: " + instancePath ); InstanceContext mappingKey = new InstanceContext( app, instancePath ); synchronized( LOCK ) { saveUsage( mappingKey, targetId, true ); } this.logger.fine( "Target " + targetId + "'s lock was acquired for " + instancePath ); TargetProperties result = findTargetProperties( app, instancePath ); Map<String,String> newTargetProperties = TargetHelpers.expandProperties( scopedInstance, result.asMap()); result.asMap().clear(); result.asMap().putAll( newTargetProperties ); return result; }
[ "@", "Override", "public", "TargetProperties", "lockAndGetTarget", "(", "Application", "app", ",", "Instance", "scopedInstance", ")", "throws", "IOException", "{", "String", "instancePath", "=", "InstanceHelpers", ".", "computeInstancePath", "(", "scopedInstance", ")", ...
Atomic operations...
[ "Atomic", "operations", "..." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/TargetsMngrImpl.java#L596-L618
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/commands/CreateInstanceCommandExecution.java
CreateInstanceCommandExecution.verify
public static void verify( CommandExecutionContext executionContext, Component component ) throws CommandException { if( executionContext != null && Constants.TARGET_INSTALLER.equalsIgnoreCase( component.getInstallerName()) && executionContext.getMaxVm() > 0 && executionContext.getMaxVm() <= executionContext.getGlobalVmNumber().get() && executionContext.isStrictMaxVm()) throw new CommandException( "The maximum number of VM created by the autonomic has been reached." ); }
java
public static void verify( CommandExecutionContext executionContext, Component component ) throws CommandException { if( executionContext != null && Constants.TARGET_INSTALLER.equalsIgnoreCase( component.getInstallerName()) && executionContext.getMaxVm() > 0 && executionContext.getMaxVm() <= executionContext.getGlobalVmNumber().get() && executionContext.isStrictMaxVm()) throw new CommandException( "The maximum number of VM created by the autonomic has been reached." ); }
[ "public", "static", "void", "verify", "(", "CommandExecutionContext", "executionContext", ",", "Component", "component", ")", "throws", "CommandException", "{", "if", "(", "executionContext", "!=", "null", "&&", "Constants", ".", "TARGET_INSTALLER", ".", "equalsIgnore...
Verifies a new VM model can be created according to a given context. @param executionContext @param component @throws CommandException
[ "Verifies", "a", "new", "VM", "model", "can", "be", "created", "according", "to", "a", "given", "context", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/commands/CreateInstanceCommandExecution.java#L85-L94
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/commands/CreateInstanceCommandExecution.java
CreateInstanceCommandExecution.update
public static void update( CommandExecutionContext executionContext, Instance createdInstance ) { if( executionContext != null ) { createdInstance.data.put( executionContext.getNewVmMarkerKey(), executionContext.getNewVmMarkerValue()); executionContext.getGlobalVmNumber().incrementAndGet(); executionContext.getAppVmNumber().incrementAndGet(); } }
java
public static void update( CommandExecutionContext executionContext, Instance createdInstance ) { if( executionContext != null ) { createdInstance.data.put( executionContext.getNewVmMarkerKey(), executionContext.getNewVmMarkerValue()); executionContext.getGlobalVmNumber().incrementAndGet(); executionContext.getAppVmNumber().incrementAndGet(); } }
[ "public", "static", "void", "update", "(", "CommandExecutionContext", "executionContext", ",", "Instance", "createdInstance", ")", "{", "if", "(", "executionContext", "!=", "null", ")", "{", "createdInstance", ".", "data", ".", "put", "(", "executionContext", ".",...
Updates an instance with context information. @param executionContext @param createdInstance
[ "Updates", "an", "instance", "with", "context", "information", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/commands/CreateInstanceCommandExecution.java#L102-L109
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/RecipesValidator.java
RecipesValidator.validateComponentRecipes
public static List<ModelError> validateComponentRecipes( File applicationFilesDirectory, Component component ) { List<ModelError> result; if( "puppet".equalsIgnoreCase( component.getInstallerName())) result = validatePuppetComponent( applicationFilesDirectory, component ); else if( "script".equalsIgnoreCase( component.getInstallerName())) result = validateScriptComponent( applicationFilesDirectory, component ); else result = Collections.emptyList(); return result; }
java
public static List<ModelError> validateComponentRecipes( File applicationFilesDirectory, Component component ) { List<ModelError> result; if( "puppet".equalsIgnoreCase( component.getInstallerName())) result = validatePuppetComponent( applicationFilesDirectory, component ); else if( "script".equalsIgnoreCase( component.getInstallerName())) result = validateScriptComponent( applicationFilesDirectory, component ); else result = Collections.emptyList(); return result; }
[ "public", "static", "List", "<", "ModelError", ">", "validateComponentRecipes", "(", "File", "applicationFilesDirectory", ",", "Component", "component", ")", "{", "List", "<", "ModelError", ">", "result", ";", "if", "(", "\"puppet\"", ".", "equalsIgnoreCase", "(",...
Validates the recipes of a component. @param applicationFilesDirectory the application's directory @param component the component @return a non-null list of errors
[ "Validates", "the", "recipes", "of", "a", "component", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/RecipesValidator.java#L93-L104
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/RecipesValidator.java
RecipesValidator.checkPuppetFile
private static void checkPuppetFile( File pp, boolean withUpdateParams, Component component, Collection<ModelError> errors ) throws IOException { // Try to use the Puppet validator String[] cmd = { "puppet", "parser", "validate", pp.getAbsolutePath()}; Logger logger = Logger.getLogger( RecipesValidator.class.getName()); try { int execCode = ProgramUtils.executeCommand( logger, cmd, null, null, null, null ); if( execCode != 0 ) errors.add( new ModelError( ErrorCode.REC_PUPPET_SYNTAX_ERROR, component, component( component ), file( pp ))); } catch( Exception e ) { logger.info( "Puppet parser is not available on the machine." ); } // We do not validate with puppet-lint. // Indeed, this tool is mostly about coding style and conventions. // Extract the script parameters Pattern pattern = Pattern.compile( "class [^(]+\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL ); String content = Utils.readFileContent( pp ); Matcher m = pattern.matcher( content ); Set<String> params = new HashSet<> (); if( ! m.find()) return; for( String s : m.group( 1 ).split( "," )) { Entry<String,String> entry = VariableHelpers.parseExportedVariable( s.trim()); params.add( entry.getKey()); } // Check the update parameters if( withUpdateParams ) { if( ! params.remove( "$importDiff" )) errors.add( new ModelError( ErrorCode.REC_PUPPET_MISSING_PARAM_IMPORT_DIFF, component, component( component ), file( pp ))); } // Prevent errors with start.pp, etc params.remove( "$importDiff" ); // Check the other ones if( ! params.remove( "$runningState" )) errors.add( new ModelError( ErrorCode.REC_PUPPET_MISSING_PARAM_RUNNING_STATE, component, component( component ), file( pp ))); // Imports imply some variables are expected Instance fake = new Instance( "fake" ).component( component ); for( String facetOrComponentName : VariableHelpers.findPrefixesForImportedVariables( fake )) { if( ! params.remove( "$" + facetOrComponentName.toLowerCase())) { ErrorDetails[] details = new ErrorDetails[] { name( component.getName()), file( pp ), expected( facetOrComponentName.toLowerCase()) }; errors.add( new ModelError( ErrorCode.REC_PUPPET_MISSING_PARAM_FROM_IMPORT, component, details )); } } }
java
private static void checkPuppetFile( File pp, boolean withUpdateParams, Component component, Collection<ModelError> errors ) throws IOException { // Try to use the Puppet validator String[] cmd = { "puppet", "parser", "validate", pp.getAbsolutePath()}; Logger logger = Logger.getLogger( RecipesValidator.class.getName()); try { int execCode = ProgramUtils.executeCommand( logger, cmd, null, null, null, null ); if( execCode != 0 ) errors.add( new ModelError( ErrorCode.REC_PUPPET_SYNTAX_ERROR, component, component( component ), file( pp ))); } catch( Exception e ) { logger.info( "Puppet parser is not available on the machine." ); } // We do not validate with puppet-lint. // Indeed, this tool is mostly about coding style and conventions. // Extract the script parameters Pattern pattern = Pattern.compile( "class [^(]+\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL ); String content = Utils.readFileContent( pp ); Matcher m = pattern.matcher( content ); Set<String> params = new HashSet<> (); if( ! m.find()) return; for( String s : m.group( 1 ).split( "," )) { Entry<String,String> entry = VariableHelpers.parseExportedVariable( s.trim()); params.add( entry.getKey()); } // Check the update parameters if( withUpdateParams ) { if( ! params.remove( "$importDiff" )) errors.add( new ModelError( ErrorCode.REC_PUPPET_MISSING_PARAM_IMPORT_DIFF, component, component( component ), file( pp ))); } // Prevent errors with start.pp, etc params.remove( "$importDiff" ); // Check the other ones if( ! params.remove( "$runningState" )) errors.add( new ModelError( ErrorCode.REC_PUPPET_MISSING_PARAM_RUNNING_STATE, component, component( component ), file( pp ))); // Imports imply some variables are expected Instance fake = new Instance( "fake" ).component( component ); for( String facetOrComponentName : VariableHelpers.findPrefixesForImportedVariables( fake )) { if( ! params.remove( "$" + facetOrComponentName.toLowerCase())) { ErrorDetails[] details = new ErrorDetails[] { name( component.getName()), file( pp ), expected( facetOrComponentName.toLowerCase()) }; errors.add( new ModelError( ErrorCode.REC_PUPPET_MISSING_PARAM_FROM_IMPORT, component, details )); } } }
[ "private", "static", "void", "checkPuppetFile", "(", "File", "pp", ",", "boolean", "withUpdateParams", ",", "Component", "component", ",", "Collection", "<", "ModelError", ">", "errors", ")", "throws", "IOException", "{", "// Try to use the Puppet validator", "String"...
Reads a Puppet script and validates it. @param pp the Puppet script @param withUpdateParams true if update parameters should be present @param component the component @param errors a non-null list of errors @throws IOException if the file content could be read
[ "Reads", "a", "Puppet", "script", "and", "validates", "it", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/RecipesValidator.java#L196-L254
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/ManifestUtils.java
ManifestUtils.findManifestProperty
public static String findManifestProperty( String propertyName ) { String result = null; InputStream is = null; try { is = ManifestUtils.class.getResourceAsStream( "/META-INF/MANIFEST.MF" ); Properties props = new Properties(); props.load( is ); result = findManifestProperty( props, propertyName ); } catch( IOException e ) { Logger logger = Logger.getLogger( ManifestUtils.class.getName()); logger.warning( "Could not read the bundle manifest. " + e.getMessage()); } finally { Utils.closeQuietly( is ); } return result; }
java
public static String findManifestProperty( String propertyName ) { String result = null; InputStream is = null; try { is = ManifestUtils.class.getResourceAsStream( "/META-INF/MANIFEST.MF" ); Properties props = new Properties(); props.load( is ); result = findManifestProperty( props, propertyName ); } catch( IOException e ) { Logger logger = Logger.getLogger( ManifestUtils.class.getName()); logger.warning( "Could not read the bundle manifest. " + e.getMessage()); } finally { Utils.closeQuietly( is ); } return result; }
[ "public", "static", "String", "findManifestProperty", "(", "String", "propertyName", ")", "{", "String", "result", "=", "null", ";", "InputStream", "is", "=", "null", ";", "try", "{", "is", "=", "ManifestUtils", ".", "class", ".", "getResourceAsStream", "(", ...
Finds a property in the MANIFEST file. @param propertyName the property's name @return the property's value, or null if it was not found
[ "Finds", "a", "property", "in", "the", "MANIFEST", "file", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/ManifestUtils.java#L98-L117
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/ManifestUtils.java
ManifestUtils.findManifestProperty
public static String findManifestProperty( Properties props, String propertyName ) { String result = null; for( Map.Entry<Object,Object> entry : props.entrySet()) { if( propertyName.equalsIgnoreCase( String.valueOf( entry.getKey()))) { result = String.valueOf( entry.getValue()); break; } } return result; }
java
public static String findManifestProperty( Properties props, String propertyName ) { String result = null; for( Map.Entry<Object,Object> entry : props.entrySet()) { if( propertyName.equalsIgnoreCase( String.valueOf( entry.getKey()))) { result = String.valueOf( entry.getValue()); break; } } return result; }
[ "public", "static", "String", "findManifestProperty", "(", "Properties", "props", ",", "String", "propertyName", ")", "{", "String", "result", "=", "null", ";", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "Object", ">", "entry", ":", "props", ".",...
Finds a property in the MANIFEST properties. @param props the properties @param propertyName the property's name @return the property's value, or null if it was not found
[ "Finds", "a", "property", "in", "the", "MANIFEST", "properties", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/ManifestUtils.java#L126-L137
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/errors/ErrorDetails.java
ErrorDetails.applicationTpl
public static ErrorDetails applicationTpl( String tplName, String tplVersion ) { return new ErrorDetails( tplName + " (" + tplVersion + ")", ErrorDetailsKind.APPLICATION_TEMPLATE ); }
java
public static ErrorDetails applicationTpl( String tplName, String tplVersion ) { return new ErrorDetails( tplName + " (" + tplVersion + ")", ErrorDetailsKind.APPLICATION_TEMPLATE ); }
[ "public", "static", "ErrorDetails", "applicationTpl", "(", "String", "tplName", ",", "String", "tplVersion", ")", "{", "return", "new", "ErrorDetails", "(", "tplName", "+", "\" (\"", "+", "tplVersion", "+", "\")\"", ",", "ErrorDetailsKind", ".", "APPLICATION_TEMPL...
Details for an application. @param tplName the template's name @param tplVersion the template's version @return an object with error details
[ "Details", "for", "an", "application", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/errors/ErrorDetails.java#L243-L245
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/errors/ErrorDetails.java
ErrorDetails.exception
public static ErrorDetails exception( Throwable t ) { return new ErrorDetails( Utils.writeExceptionButDoNotUseItForLogging( t ), ErrorDetailsKind.EXCEPTION ); }
java
public static ErrorDetails exception( Throwable t ) { return new ErrorDetails( Utils.writeExceptionButDoNotUseItForLogging( t ), ErrorDetailsKind.EXCEPTION ); }
[ "public", "static", "ErrorDetails", "exception", "(", "Throwable", "t", ")", "{", "return", "new", "ErrorDetails", "(", "Utils", ".", "writeExceptionButDoNotUseItForLogging", "(", "t", ")", ",", "ErrorDetailsKind", ".", "EXCEPTION", ")", ";", "}" ]
Details for an exception. @param t a throwable @return an object with error details
[ "Details", "for", "an", "exception", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/errors/ErrorDetails.java#L373-L375
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/errors/ErrorDetails.java
ErrorDetails.exceptionName
public static ErrorDetails exceptionName( Throwable t ) { return new ErrorDetails( t.getClass().getName(), ErrorDetailsKind.EXCEPTION_NAME ); }
java
public static ErrorDetails exceptionName( Throwable t ) { return new ErrorDetails( t.getClass().getName(), ErrorDetailsKind.EXCEPTION_NAME ); }
[ "public", "static", "ErrorDetails", "exceptionName", "(", "Throwable", "t", ")", "{", "return", "new", "ErrorDetails", "(", "t", ".", "getClass", "(", ")", ".", "getName", "(", ")", ",", "ErrorDetailsKind", ".", "EXCEPTION_NAME", ")", ";", "}" ]
Details for an exception name. @param t a throwable @return an object with error details
[ "Details", "for", "an", "exception", "name", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/errors/ErrorDetails.java#L383-L385
train
roboconf/roboconf-platform
core/roboconf-target-iaas-azure/src/main/java/net/roboconf/target/azure/internal/AzureIaasHandler.java
AzureIaasHandler.buildProperties
static AzureProperties buildProperties( Map<String,String> targetProperties ) throws TargetException { String[] properties = { AzureConstants.AZURE_SUBSCRIPTION_ID, AzureConstants.AZURE_KEY_STORE_FILE, AzureConstants.AZURE_KEY_STORE_PASSWORD, AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE, AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE, AzureConstants.AZURE_LOCATION, AzureConstants.AZURE_VM_SIZE, AzureConstants.AZURE_VM_TEMPLATE }; for( String property : properties ) { if( Utils.isEmptyOrWhitespaces( targetProperties.get( property ))) throw new TargetException( "The value for " + property + " cannot be null or empty." ); } // Create a bean AzureProperties azureProperties = new AzureProperties(); String s = targetProperties.get( AzureConstants.AZURE_SUBSCRIPTION_ID ); azureProperties.setSubscriptionId( s.trim()); s = targetProperties.get( AzureConstants.AZURE_KEY_STORE_FILE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_KEY_STORE_PASSWORD ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_LOCATION ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_VM_SIZE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_VM_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); return azureProperties; }
java
static AzureProperties buildProperties( Map<String,String> targetProperties ) throws TargetException { String[] properties = { AzureConstants.AZURE_SUBSCRIPTION_ID, AzureConstants.AZURE_KEY_STORE_FILE, AzureConstants.AZURE_KEY_STORE_PASSWORD, AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE, AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE, AzureConstants.AZURE_LOCATION, AzureConstants.AZURE_VM_SIZE, AzureConstants.AZURE_VM_TEMPLATE }; for( String property : properties ) { if( Utils.isEmptyOrWhitespaces( targetProperties.get( property ))) throw new TargetException( "The value for " + property + " cannot be null or empty." ); } // Create a bean AzureProperties azureProperties = new AzureProperties(); String s = targetProperties.get( AzureConstants.AZURE_SUBSCRIPTION_ID ); azureProperties.setSubscriptionId( s.trim()); s = targetProperties.get( AzureConstants.AZURE_KEY_STORE_FILE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_KEY_STORE_PASSWORD ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_LOCATION ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_VM_SIZE ); azureProperties.setKeyStoreFile( s.trim()); s = targetProperties.get( AzureConstants.AZURE_VM_TEMPLATE ); azureProperties.setKeyStoreFile( s.trim()); return azureProperties; }
[ "static", "AzureProperties", "buildProperties", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ")", "throws", "TargetException", "{", "String", "[", "]", "properties", "=", "{", "AzureConstants", ".", "AZURE_SUBSCRIPTION_ID", ",", "AzureConstants...
Validates the received properties and builds a Java bean from them. @param targetProperties the target properties @return a non-null bean @throws TargetException if properties are invalid
[ "Validates", "the", "received", "properties", "and", "builds", "a", "Java", "bean", "from", "them", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-azure/src/main/java/net/roboconf/target/azure/internal/AzureIaasHandler.java#L253-L299
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/ApplicationTemplateDescriptor.java
ApplicationTemplateDescriptor.load
public static ApplicationTemplateDescriptor load( File f ) throws IOException { // Read the file's content String fileContent = Utils.readFileContent( f ); Logger logger = Logger.getLogger( ApplicationTemplateDescriptor.class.getName()); Properties properties = Utils.readPropertiesQuietly( fileContent, logger ); if( properties.get( "fail.read" ) != null ) throw new IOException( "This is for test purpose..." ); ApplicationTemplateDescriptor result = load( properties ); // Resolve line numbers then int lineNumber = 1; for( String line : fileContent.split( "\n" )) { for( String property : ALL_PROPERTIES ) { if( line.trim().matches( "(" + LEGACY_PREFIX + ")?" + property + "\\s*[:=].*" )) { result.propertyToLine.put( property, lineNumber ); break; } } lineNumber ++; } return result; }
java
public static ApplicationTemplateDescriptor load( File f ) throws IOException { // Read the file's content String fileContent = Utils.readFileContent( f ); Logger logger = Logger.getLogger( ApplicationTemplateDescriptor.class.getName()); Properties properties = Utils.readPropertiesQuietly( fileContent, logger ); if( properties.get( "fail.read" ) != null ) throw new IOException( "This is for test purpose..." ); ApplicationTemplateDescriptor result = load( properties ); // Resolve line numbers then int lineNumber = 1; for( String line : fileContent.split( "\n" )) { for( String property : ALL_PROPERTIES ) { if( line.trim().matches( "(" + LEGACY_PREFIX + ")?" + property + "\\s*[:=].*" )) { result.propertyToLine.put( property, lineNumber ); break; } } lineNumber ++; } return result; }
[ "public", "static", "ApplicationTemplateDescriptor", "load", "(", "File", "f", ")", "throws", "IOException", "{", "// Read the file's content", "String", "fileContent", "=", "Utils", ".", "readFileContent", "(", "f", ")", ";", "Logger", "logger", "=", "Logger", "....
Loads an application template's descriptor. @param f a file @return an application descriptor (not null) @throws IOException if the file could not be read
[ "Loads", "an", "application", "template", "s", "descriptor", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/ApplicationTemplateDescriptor.java#L229-L255
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/ApplicationTemplateDescriptor.java
ApplicationTemplateDescriptor.save
public static void save( File f, ApplicationTemplateDescriptor descriptor ) throws IOException { Properties properties = new Properties(); if( descriptor.name != null ) properties.setProperty( APPLICATION_NAME, descriptor.name ); if( descriptor.version != null ) properties.setProperty( APPLICATION_VERSION, descriptor.version ); if( descriptor.dslId != null ) properties.setProperty( APPLICATION_DSL_ID, descriptor.dslId ); if( descriptor.description != null ) properties.setProperty( APPLICATION_DESCRIPTION, descriptor.description ); if( descriptor.graphEntryPoint != null ) properties.setProperty( APPLICATION_GRAPH_EP, descriptor.graphEntryPoint ); if( descriptor.instanceEntryPoint != null ) properties.setProperty( APPLICATION_INSTANCES_EP, descriptor.instanceEntryPoint ); if( descriptor.externalExportsPrefix != null ) properties.setProperty( APPLICATION_EXTERNAL_EXPORTS_PREFIX, descriptor.externalExportsPrefix ); StringBuilder sb = new StringBuilder(); for( Iterator<Map.Entry<String,String>> it = descriptor.externalExports.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String,String> entry = it.next(); sb.append( entry.getKey()); sb.append( " " ); sb.append( APPLICATION_EXTERNAL_EXPORTS_AS ); sb.append( " " ); sb.append( entry.getValue()); if( it.hasNext()) sb.append( ", " ); } if( sb.length() > 0 ) properties.setProperty( APPLICATION_EXTERNAL_EXPORTS, sb.toString()); properties.setProperty( APPLICATION_TAGS, Utils.format( descriptor.tags, ", " )); Utils.writePropertiesFile( properties, f ); }
java
public static void save( File f, ApplicationTemplateDescriptor descriptor ) throws IOException { Properties properties = new Properties(); if( descriptor.name != null ) properties.setProperty( APPLICATION_NAME, descriptor.name ); if( descriptor.version != null ) properties.setProperty( APPLICATION_VERSION, descriptor.version ); if( descriptor.dslId != null ) properties.setProperty( APPLICATION_DSL_ID, descriptor.dslId ); if( descriptor.description != null ) properties.setProperty( APPLICATION_DESCRIPTION, descriptor.description ); if( descriptor.graphEntryPoint != null ) properties.setProperty( APPLICATION_GRAPH_EP, descriptor.graphEntryPoint ); if( descriptor.instanceEntryPoint != null ) properties.setProperty( APPLICATION_INSTANCES_EP, descriptor.instanceEntryPoint ); if( descriptor.externalExportsPrefix != null ) properties.setProperty( APPLICATION_EXTERNAL_EXPORTS_PREFIX, descriptor.externalExportsPrefix ); StringBuilder sb = new StringBuilder(); for( Iterator<Map.Entry<String,String>> it = descriptor.externalExports.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String,String> entry = it.next(); sb.append( entry.getKey()); sb.append( " " ); sb.append( APPLICATION_EXTERNAL_EXPORTS_AS ); sb.append( " " ); sb.append( entry.getValue()); if( it.hasNext()) sb.append( ", " ); } if( sb.length() > 0 ) properties.setProperty( APPLICATION_EXTERNAL_EXPORTS, sb.toString()); properties.setProperty( APPLICATION_TAGS, Utils.format( descriptor.tags, ", " )); Utils.writePropertiesFile( properties, f ); }
[ "public", "static", "void", "save", "(", "File", "f", ",", "ApplicationTemplateDescriptor", "descriptor", ")", "throws", "IOException", "{", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "if", "(", "descriptor", ".", "name", "!=", "null"...
Saves an application template's descriptor. @param f the file where the properties will be saved @param descriptor an application descriptor (not null) @throws IOException if the file could not be written
[ "Saves", "an", "application", "template", "s", "descriptor", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/ApplicationTemplateDescriptor.java#L264-L305
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/ApplicationTemplateDescriptor.java
ApplicationTemplateDescriptor.getLegacyProperty
static String getLegacyProperty( Properties props, String property, String defaultValue ) { String result = props.getProperty( property, null ); if( result == null ) result = props.getProperty( LEGACY_PREFIX + property, defaultValue ); return result; }
java
static String getLegacyProperty( Properties props, String property, String defaultValue ) { String result = props.getProperty( property, null ); if( result == null ) result = props.getProperty( LEGACY_PREFIX + property, defaultValue ); return result; }
[ "static", "String", "getLegacyProperty", "(", "Properties", "props", ",", "String", "property", ",", "String", "defaultValue", ")", "{", "String", "result", "=", "props", ".", "getProperty", "(", "property", ",", "null", ")", ";", "if", "(", "result", "==", ...
Gets a property value while supporting legacy ones. @param props non-null properties @param property a non-null property name (not legacy) @param defaultValue the default value if the property is not found @return a non-null string if the property was found, the default value otherwise
[ "Gets", "a", "property", "value", "while", "supporting", "legacy", "ones", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/ApplicationTemplateDescriptor.java#L315-L322
train
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java
ProjectUtils.createProjectSkeleton
public static void createProjectSkeleton( File targetDirectory, CreationBean creationBean ) throws IOException { if( creationBean.isMavenProject()) createMavenProject( targetDirectory, creationBean ); else createSimpleProject( targetDirectory, creationBean ); }
java
public static void createProjectSkeleton( File targetDirectory, CreationBean creationBean ) throws IOException { if( creationBean.isMavenProject()) createMavenProject( targetDirectory, creationBean ); else createSimpleProject( targetDirectory, creationBean ); }
[ "public", "static", "void", "createProjectSkeleton", "(", "File", "targetDirectory", ",", "CreationBean", "creationBean", ")", "throws", "IOException", "{", "if", "(", "creationBean", ".", "isMavenProject", "(", ")", ")", "createMavenProject", "(", "targetDirectory", ...
Creates a project for Roboconf. @param targetDirectory the directory into which the Roboconf files must be copied @param creationBean the creation properties @throws IOException if something went wrong
[ "Creates", "a", "project", "for", "Roboconf", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java#L91-L97
train
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java
ProjectUtils.createRecipeDirectories
public static List<File> createRecipeDirectories( File applicationDirectory ) throws IOException { List<File> result = new ArrayList<> (); ApplicationLoadResult alr = RuntimeModelIo.loadApplicationFlexibly( applicationDirectory ); if( alr.getApplicationTemplate() != null ) { for( Component c : ComponentHelpers.findAllComponents( alr.getApplicationTemplate())) { File directory = ResourceUtils.findInstanceResourcesDirectory( applicationDirectory, c ); if( ! directory.exists()) result.add( directory ); Utils.createDirectory( directory ); } } return result; }
java
public static List<File> createRecipeDirectories( File applicationDirectory ) throws IOException { List<File> result = new ArrayList<> (); ApplicationLoadResult alr = RuntimeModelIo.loadApplicationFlexibly( applicationDirectory ); if( alr.getApplicationTemplate() != null ) { for( Component c : ComponentHelpers.findAllComponents( alr.getApplicationTemplate())) { File directory = ResourceUtils.findInstanceResourcesDirectory( applicationDirectory, c ); if( ! directory.exists()) result.add( directory ); Utils.createDirectory( directory ); } } return result; }
[ "public", "static", "List", "<", "File", ">", "createRecipeDirectories", "(", "File", "applicationDirectory", ")", "throws", "IOException", "{", "List", "<", "File", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "ApplicationLoadResult", "alr", "...
Creates the recipes directories for a Roboconf components. @param applicationDirectory the application directory @return a non-null list of the created directories @throws IOException if something went wrong
[ "Creates", "the", "recipes", "directories", "for", "a", "Roboconf", "components", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java#L114-L129
train
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java
ProjectUtils.createSimpleProject
private static void createSimpleProject( File targetDirectory, CreationBean creationBean ) throws IOException { // Create the directory structure String[] directoriesToCreate = creationBean.isReusableRecipe() ? RR_DIRECTORIES : ALL_DIRECTORIES; for( String s : directoriesToCreate ) { File dir = new File( targetDirectory, s ); Utils.createDirectory( dir ); } // Create the descriptor InputStream in = ProjectUtils.class.getResourceAsStream( "/application-skeleton.props" ); ByteArrayOutputStream out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); String tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_VERSION, creationBean.getProjectVersion()) .replace( TPL_DESCRIPTION, creationBean.getProjectDescription()); // Create the rest of the project completeProjectCreation( targetDirectory, tpl, creationBean ); }
java
private static void createSimpleProject( File targetDirectory, CreationBean creationBean ) throws IOException { // Create the directory structure String[] directoriesToCreate = creationBean.isReusableRecipe() ? RR_DIRECTORIES : ALL_DIRECTORIES; for( String s : directoriesToCreate ) { File dir = new File( targetDirectory, s ); Utils.createDirectory( dir ); } // Create the descriptor InputStream in = ProjectUtils.class.getResourceAsStream( "/application-skeleton.props" ); ByteArrayOutputStream out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); String tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_VERSION, creationBean.getProjectVersion()) .replace( TPL_DESCRIPTION, creationBean.getProjectDescription()); // Create the rest of the project completeProjectCreation( targetDirectory, tpl, creationBean ); }
[ "private", "static", "void", "createSimpleProject", "(", "File", "targetDirectory", ",", "CreationBean", "creationBean", ")", "throws", "IOException", "{", "// Create the directory structure", "String", "[", "]", "directoriesToCreate", "=", "creationBean", ".", "isReusabl...
Creates a simple project for Roboconf. @param targetDirectory the directory into which the Roboconf files must be copied @param creationBean the creation properties @throws IOException if something went wrong
[ "Creates", "a", "simple", "project", "for", "Roboconf", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java#L138-L159
train
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java
ProjectUtils.createMavenProject
private static void createMavenProject( File targetDirectory, CreationBean creationBean ) throws IOException { // Create the directory structure File rootDir = new File( targetDirectory, Constants.MAVEN_SRC_MAIN_MODEL ); String[] directoriesToCreate = creationBean.isReusableRecipe() ? RR_DIRECTORIES : ALL_DIRECTORIES; for( String s : directoriesToCreate ) { File dir = new File( rootDir, s ); Utils.createDirectory( dir ); } // Create a POM? InputStream in; if( Utils.isEmptyOrWhitespaces( creationBean.getCustomPomLocation())) in = ProjectUtils.class.getResourceAsStream( "/pom-skeleton.xml" ); else in = new FileInputStream( creationBean.getCustomPomLocation()); ByteArrayOutputStream out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); String tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_POM_GROUP, creationBean.getGroupId()) .replace( TPL_POM_PLUGIN_VERSION, creationBean.getPluginVersion()) .replace( TPL_VERSION, creationBean.getProjectVersion()) .replace( TPL_POM_ARTIFACT, creationBean.getArtifactId()) .replace( TPL_DESCRIPTION, creationBean.getProjectDescription()); File pomFile = new File( targetDirectory, "pom.xml" ); Utils.copyStream( new ByteArrayInputStream( tpl.getBytes( StandardCharsets.UTF_8 )), pomFile ); // Create the descriptor in = ProjectUtils.class.getResourceAsStream( "/application-skeleton.props" ); out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_DESCRIPTION, "${project.description}" ); // If for some reason, the project version is already a Maven expression, // keep it untouched. Such a thing may cause troubles with a real POM, // as versions should not reference properties. But it may be used for tests anyway. if( ! creationBean.getProjectVersion().contains( "$" )) tpl = tpl.replace( TPL_VERSION, "${project.version}" ); else tpl = tpl.replace( TPL_VERSION, creationBean.getProjectVersion()); // Create the rest of the project completeProjectCreation( rootDir, tpl, creationBean ); }
java
private static void createMavenProject( File targetDirectory, CreationBean creationBean ) throws IOException { // Create the directory structure File rootDir = new File( targetDirectory, Constants.MAVEN_SRC_MAIN_MODEL ); String[] directoriesToCreate = creationBean.isReusableRecipe() ? RR_DIRECTORIES : ALL_DIRECTORIES; for( String s : directoriesToCreate ) { File dir = new File( rootDir, s ); Utils.createDirectory( dir ); } // Create a POM? InputStream in; if( Utils.isEmptyOrWhitespaces( creationBean.getCustomPomLocation())) in = ProjectUtils.class.getResourceAsStream( "/pom-skeleton.xml" ); else in = new FileInputStream( creationBean.getCustomPomLocation()); ByteArrayOutputStream out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); String tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_POM_GROUP, creationBean.getGroupId()) .replace( TPL_POM_PLUGIN_VERSION, creationBean.getPluginVersion()) .replace( TPL_VERSION, creationBean.getProjectVersion()) .replace( TPL_POM_ARTIFACT, creationBean.getArtifactId()) .replace( TPL_DESCRIPTION, creationBean.getProjectDescription()); File pomFile = new File( targetDirectory, "pom.xml" ); Utils.copyStream( new ByteArrayInputStream( tpl.getBytes( StandardCharsets.UTF_8 )), pomFile ); // Create the descriptor in = ProjectUtils.class.getResourceAsStream( "/application-skeleton.props" ); out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_DESCRIPTION, "${project.description}" ); // If for some reason, the project version is already a Maven expression, // keep it untouched. Such a thing may cause troubles with a real POM, // as versions should not reference properties. But it may be used for tests anyway. if( ! creationBean.getProjectVersion().contains( "$" )) tpl = tpl.replace( TPL_VERSION, "${project.version}" ); else tpl = tpl.replace( TPL_VERSION, creationBean.getProjectVersion()); // Create the rest of the project completeProjectCreation( rootDir, tpl, creationBean ); }
[ "private", "static", "void", "createMavenProject", "(", "File", "targetDirectory", ",", "CreationBean", "creationBean", ")", "throws", "IOException", "{", "// Create the directory structure", "File", "rootDir", "=", "new", "File", "(", "targetDirectory", ",", "Constants...
Creates a Maven project for Roboconf. @param targetDirectory the directory into which the Roboconf files must be copied @param creationBean the creation properties @throws IOException if something went wrong
[ "Creates", "a", "Maven", "project", "for", "Roboconf", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java#L168-L216
train
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java
ProjectUtils.completeProjectCreation
private static void completeProjectCreation( File targetDirectory, String descriptorContent, CreationBean creationBean ) throws IOException { // Create a sample graph file File f = new File( targetDirectory, Constants.PROJECT_DIR_GRAPH + "/" + GRAPH_EP ); InputStream in = ProjectUtils.class.getResourceAsStream( "/graph-skeleton.graph" ); Utils.copyStream( in, f ); // Create other elements only if it is not a reusable recipe if( ! creationBean.isReusableRecipe()) { // Write the descriptor f = new File( targetDirectory, Constants.PROJECT_DIR_DESC + "/" + Constants.PROJECT_FILE_DESCRIPTOR ); Utils.writeStringInto( descriptorContent, f ); // Create a sample instances file f = new File( targetDirectory, Constants.PROJECT_DIR_INSTANCES + "/" + INSTANCES_EP ); in = ProjectUtils.class.getResourceAsStream( "/instances-skeleton.instances" ); Utils.copyStream( in, f ); } }
java
private static void completeProjectCreation( File targetDirectory, String descriptorContent, CreationBean creationBean ) throws IOException { // Create a sample graph file File f = new File( targetDirectory, Constants.PROJECT_DIR_GRAPH + "/" + GRAPH_EP ); InputStream in = ProjectUtils.class.getResourceAsStream( "/graph-skeleton.graph" ); Utils.copyStream( in, f ); // Create other elements only if it is not a reusable recipe if( ! creationBean.isReusableRecipe()) { // Write the descriptor f = new File( targetDirectory, Constants.PROJECT_DIR_DESC + "/" + Constants.PROJECT_FILE_DESCRIPTOR ); Utils.writeStringInto( descriptorContent, f ); // Create a sample instances file f = new File( targetDirectory, Constants.PROJECT_DIR_INSTANCES + "/" + INSTANCES_EP ); in = ProjectUtils.class.getResourceAsStream( "/instances-skeleton.instances" ); Utils.copyStream( in, f ); } }
[ "private", "static", "void", "completeProjectCreation", "(", "File", "targetDirectory", ",", "String", "descriptorContent", ",", "CreationBean", "creationBean", ")", "throws", "IOException", "{", "// Create a sample graph file", "File", "f", "=", "new", "File", "(", "...
Completes the creation of a Roboconf project. @param targetDirectory the directory into which the Roboconf files must be copied @param descriptorContent the descriptor's content @param creationBean the creation options @throws IOException if something went wrong
[ "Completes", "the", "creation", "of", "a", "Roboconf", "project", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java#L226-L249
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/ParsingError.java
ParsingError.addLineAndFile
private static ErrorDetails[] addLineAndFile( int line, File file, ErrorDetails... details ) { Set<ErrorDetails> updatedDetails = new LinkedHashSet<> (); if( details != null ) updatedDetails.addAll( Arrays.asList( details )); if( file != null ) { updatedDetails.add( file( file )); updatedDetails.add( line( line )); } return updatedDetails.toArray( new ErrorDetails[ updatedDetails.size()]); }
java
private static ErrorDetails[] addLineAndFile( int line, File file, ErrorDetails... details ) { Set<ErrorDetails> updatedDetails = new LinkedHashSet<> (); if( details != null ) updatedDetails.addAll( Arrays.asList( details )); if( file != null ) { updatedDetails.add( file( file )); updatedDetails.add( line( line )); } return updatedDetails.toArray( new ErrorDetails[ updatedDetails.size()]); }
[ "private", "static", "ErrorDetails", "[", "]", "addLineAndFile", "(", "int", "line", ",", "File", "file", ",", "ErrorDetails", "...", "details", ")", "{", "Set", "<", "ErrorDetails", ">", "updatedDetails", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", ...
Adds details about the line number and the file. @param line @param file @param details @return a non-null array
[ "Adds", "details", "about", "the", "line", "number", "and", "the", "file", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/ParsingError.java#L117-L129
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/DockerAndScriptUtils.java
DockerAndScriptUtils.buildReferenceMap
public static Map<String,String> buildReferenceMap( Instance instance ) { Map<String,String> result = new HashMap<> (); String instancePath = InstanceHelpers.computeInstancePath( instance ); result.put( ROBOCONF_INSTANCE_NAME, instance.getName()); result.put( ROBOCONF_INSTANCE_PATH, instancePath ); result.put( ROBOCONF_COMPONENT_NAME, instance.getComponent().getName()); result.put( ROBOCONF_CLEAN_INSTANCE_PATH, cleanInstancePath( instancePath )); result.put( ROBOCONF_CLEAN_REVERSED_INSTANCE_PATH, cleanReversedInstancePath( instancePath )); return result; }
java
public static Map<String,String> buildReferenceMap( Instance instance ) { Map<String,String> result = new HashMap<> (); String instancePath = InstanceHelpers.computeInstancePath( instance ); result.put( ROBOCONF_INSTANCE_NAME, instance.getName()); result.put( ROBOCONF_INSTANCE_PATH, instancePath ); result.put( ROBOCONF_COMPONENT_NAME, instance.getComponent().getName()); result.put( ROBOCONF_CLEAN_INSTANCE_PATH, cleanInstancePath( instancePath )); result.put( ROBOCONF_CLEAN_REVERSED_INSTANCE_PATH, cleanReversedInstancePath( instancePath )); return result; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "buildReferenceMap", "(", "Instance", "instance", ")", "{", "Map", "<", "String", ",", "String", ">", "result", "=", "new", "HashMap", "<>", "(", ")", ";", "String", "instancePath", "=", "Inst...
Builds a map with the variables defined by this class. @param instance a non-null instance @return a non-null map where all the properties here are mapped to their values for this instance
[ "Builds", "a", "map", "with", "the", "variables", "defined", "by", "this", "class", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/DockerAndScriptUtils.java#L59-L71
train
roboconf/roboconf-platform
core/roboconf-agent-monitoring/src/main/java/net/roboconf/agent/monitoring/internal/MonitoringRunnable.java
MonitoringRunnable.extractRuleSections
List<MonitoringHandlerRun> extractRuleSections( File file, String fileContent, Properties params ) { // Find rules sections StringBuilder sb = new StringBuilder(); List<String> sections = new ArrayList<String>(); for( String s : Arrays.asList( fileContent.trim().split( "\n" ))) { s = s.trim(); if( s.length() == 0 || s.startsWith( COMMENT_DELIMITER )) continue; if( s.toLowerCase().startsWith( RULE_BEGINNING )) { addSectionIfNotEmpty(sections, sb.toString()); sb.setLength( 0 ); } sb.append( Utils.expandTemplate(s, params) + "\n" ); } addSectionIfNotEmpty(sections, sb.toString()); // Now, prepare handler invocations List<MonitoringHandlerRun> result = new ArrayList<MonitoringHandlerRun> (); for( String s : sections ) { Matcher m = this.eventPattern.matcher( s ); if( ! m.find()) continue; s = s.substring( m.end()).trim(); MonitoringHandlerRun bean = new MonitoringHandlerRun(); bean.handlerName = m.group( 1 ); bean.eventId = m.group( 2 ); bean.rawRulesText = s; result.add( bean ); } return result; }
java
List<MonitoringHandlerRun> extractRuleSections( File file, String fileContent, Properties params ) { // Find rules sections StringBuilder sb = new StringBuilder(); List<String> sections = new ArrayList<String>(); for( String s : Arrays.asList( fileContent.trim().split( "\n" ))) { s = s.trim(); if( s.length() == 0 || s.startsWith( COMMENT_DELIMITER )) continue; if( s.toLowerCase().startsWith( RULE_BEGINNING )) { addSectionIfNotEmpty(sections, sb.toString()); sb.setLength( 0 ); } sb.append( Utils.expandTemplate(s, params) + "\n" ); } addSectionIfNotEmpty(sections, sb.toString()); // Now, prepare handler invocations List<MonitoringHandlerRun> result = new ArrayList<MonitoringHandlerRun> (); for( String s : sections ) { Matcher m = this.eventPattern.matcher( s ); if( ! m.find()) continue; s = s.substring( m.end()).trim(); MonitoringHandlerRun bean = new MonitoringHandlerRun(); bean.handlerName = m.group( 1 ); bean.eventId = m.group( 2 ); bean.rawRulesText = s; result.add( bean ); } return result; }
[ "List", "<", "MonitoringHandlerRun", ">", "extractRuleSections", "(", "File", "file", ",", "String", "fileContent", ",", "Properties", "params", ")", "{", "// Find rules sections", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "List", "<", "...
Reads the file content, extracts rules sections and prepares the handler invocations. @param file @param fileContent @param params @return a non-null list of handler parameters (may be empty)
[ "Reads", "the", "file", "content", "extracts", "rules", "sections", "and", "prepares", "the", "handler", "invocations", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-agent-monitoring/src/main/java/net/roboconf/agent/monitoring/internal/MonitoringRunnable.java#L162-L201
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/beans/ApplicationTemplate.java
ApplicationTemplate.setTags
public void setTags( Collection<String> tags ) { synchronized( this.tags ) { this.tags.clear(); if( tags != null ) this.tags.addAll( tags ); } }
java
public void setTags( Collection<String> tags ) { synchronized( this.tags ) { this.tags.clear(); if( tags != null ) this.tags.addAll( tags ); } }
[ "public", "void", "setTags", "(", "Collection", "<", "String", ">", "tags", ")", "{", "synchronized", "(", "this", ".", "tags", ")", "{", "this", ".", "tags", ".", "clear", "(", ")", ";", "if", "(", "tags", "!=", "null", ")", "this", ".", "tags", ...
Replaces all the tags. @param tags a (potentially null) collection of tags
[ "Replaces", "all", "the", "tags", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/beans/ApplicationTemplate.java#L254-L261
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/TargetValidator.java
TargetValidator.validate
public void validate() { ErrorDetails details = null; if( this.fileName != null ) details = ErrorDetails.file( this.fileName ); if( this.failed ) { this.errors.add( new ModelError( ErrorCode.REC_TARGET_INVALID_FILE_OR_CONTENT, this.modelObject, details )); } else { String id = this.props.getProperty( Constants.TARGET_PROPERTY_ID ); if( Utils.isEmptyOrWhitespaces( id )) this.errors.add( new ModelError( ErrorCode.REC_TARGET_NO_ID, this.modelObject, details )); String handler = this.props.getProperty( Constants.TARGET_PROPERTY_HANDLER ); if( Utils.isEmptyOrWhitespaces( handler )) this.errors.add( new ModelError( ErrorCode.REC_TARGET_NO_HANDLER, this.modelObject, details )); String name = this.props.getProperty( Constants.TARGET_PROPERTY_NAME ); if( Utils.isEmptyOrWhitespaces( name )) this.errors.add( new ModelError( ErrorCode.REC_TARGET_NO_NAME, this.modelObject, details )); } }
java
public void validate() { ErrorDetails details = null; if( this.fileName != null ) details = ErrorDetails.file( this.fileName ); if( this.failed ) { this.errors.add( new ModelError( ErrorCode.REC_TARGET_INVALID_FILE_OR_CONTENT, this.modelObject, details )); } else { String id = this.props.getProperty( Constants.TARGET_PROPERTY_ID ); if( Utils.isEmptyOrWhitespaces( id )) this.errors.add( new ModelError( ErrorCode.REC_TARGET_NO_ID, this.modelObject, details )); String handler = this.props.getProperty( Constants.TARGET_PROPERTY_HANDLER ); if( Utils.isEmptyOrWhitespaces( handler )) this.errors.add( new ModelError( ErrorCode.REC_TARGET_NO_HANDLER, this.modelObject, details )); String name = this.props.getProperty( Constants.TARGET_PROPERTY_NAME ); if( Utils.isEmptyOrWhitespaces( name )) this.errors.add( new ModelError( ErrorCode.REC_TARGET_NO_NAME, this.modelObject, details )); } }
[ "public", "void", "validate", "(", ")", "{", "ErrorDetails", "details", "=", "null", ";", "if", "(", "this", ".", "fileName", "!=", "null", ")", "details", "=", "ErrorDetails", ".", "file", "(", "this", ".", "fileName", ")", ";", "if", "(", "this", "...
Validates target properties.
[ "Validates", "target", "properties", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/TargetValidator.java#L111-L133
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/TargetValidator.java
TargetValidator.parseDirectory
public static List<ModelError> parseDirectory( File directory, Component c ) { // Validate all the properties List<ModelError> result = new ArrayList<> (); Set<String> targetIds = new HashSet<> (); for( File f : Utils.listDirectFiles( directory, Constants.FILE_EXT_PROPERTIES )) { TargetValidator tv = new TargetValidator( f, c ); tv.validate(); result.addAll( tv.getErrors()); String id = tv.getProperties().getProperty( Constants.TARGET_PROPERTY_ID ); if( targetIds.contains( id )) result.add( new ModelError( ErrorCode.REC_TARGET_CONFLICTING_ID, tv.modelObject, name( id ))); targetIds.add( id ); } // There should be properties files if( targetIds.isEmpty()) result.add( new ModelError( ErrorCode.REC_TARGET_NO_PROPERTIES, null, directory( directory ))); return result; }
java
public static List<ModelError> parseDirectory( File directory, Component c ) { // Validate all the properties List<ModelError> result = new ArrayList<> (); Set<String> targetIds = new HashSet<> (); for( File f : Utils.listDirectFiles( directory, Constants.FILE_EXT_PROPERTIES )) { TargetValidator tv = new TargetValidator( f, c ); tv.validate(); result.addAll( tv.getErrors()); String id = tv.getProperties().getProperty( Constants.TARGET_PROPERTY_ID ); if( targetIds.contains( id )) result.add( new ModelError( ErrorCode.REC_TARGET_CONFLICTING_ID, tv.modelObject, name( id ))); targetIds.add( id ); } // There should be properties files if( targetIds.isEmpty()) result.add( new ModelError( ErrorCode.REC_TARGET_NO_PROPERTIES, null, directory( directory ))); return result; }
[ "public", "static", "List", "<", "ModelError", ">", "parseDirectory", "(", "File", "directory", ",", "Component", "c", ")", "{", "// Validate all the properties", "List", "<", "ModelError", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "Set", ...
Parses a directory with one or several properties files. @param directory an existing directory @return a non-null list of errors
[ "Parses", "a", "directory", "with", "one", "or", "several", "properties", "files", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/TargetValidator.java#L167-L190
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/TargetValidator.java
TargetValidator.parseTargetProperties
public static List<ModelError> parseTargetProperties( File projectDirectory, Component c ) { List<ModelError> errors; File dir = ResourceUtils.findInstanceResourcesDirectory( projectDirectory, c ); if( dir.isDirectory() && ! Utils.listAllFiles( dir, Constants.FILE_EXT_PROPERTIES ).isEmpty()) errors = parseDirectory( dir, c ); else errors = new ArrayList<>( 0 ); return errors; }
java
public static List<ModelError> parseTargetProperties( File projectDirectory, Component c ) { List<ModelError> errors; File dir = ResourceUtils.findInstanceResourcesDirectory( projectDirectory, c ); if( dir.isDirectory() && ! Utils.listAllFiles( dir, Constants.FILE_EXT_PROPERTIES ).isEmpty()) errors = parseDirectory( dir, c ); else errors = new ArrayList<>( 0 ); return errors; }
[ "public", "static", "List", "<", "ModelError", ">", "parseTargetProperties", "(", "File", "projectDirectory", ",", "Component", "c", ")", "{", "List", "<", "ModelError", ">", "errors", ";", "File", "dir", "=", "ResourceUtils", ".", "findInstanceResourcesDirectory"...
Parses the target properties for a given component. @param projectDirectory the project's directory @param c a component @return a non-null list of errors
[ "Parses", "the", "target", "properties", "for", "a", "given", "component", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/TargetValidator.java#L199-L210
train
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/TextUtils.java
TextUtils.fixSelectionLength
static int fixSelectionLength( String fullText, int selectionOffset, int selectionLength ) { if( selectionLength < 0 ) selectionLength = 0; else if( selectionOffset + selectionLength > fullText.length()) selectionLength = fullText.length() - selectionOffset; for( ; selectionOffset + selectionLength < fullText.length(); selectionLength ++ ) { char c = fullText.charAt( selectionOffset + selectionLength ); if( isLineBreak( c )) break; } return selectionLength; }
java
static int fixSelectionLength( String fullText, int selectionOffset, int selectionLength ) { if( selectionLength < 0 ) selectionLength = 0; else if( selectionOffset + selectionLength > fullText.length()) selectionLength = fullText.length() - selectionOffset; for( ; selectionOffset + selectionLength < fullText.length(); selectionLength ++ ) { char c = fullText.charAt( selectionOffset + selectionLength ); if( isLineBreak( c )) break; } return selectionLength; }
[ "static", "int", "fixSelectionLength", "(", "String", "fullText", ",", "int", "selectionOffset", ",", "int", "selectionLength", ")", "{", "if", "(", "selectionLength", "<", "0", ")", "selectionLength", "=", "0", ";", "else", "if", "(", "selectionOffset", "+", ...
Fixes the selection length to get the whole line. @param fullText the full text (not null) @param selectionOffset a <b>valid</b> selection offset @param selectionLength the selection length @return a valid selection length (can be zero)
[ "Fixes", "the", "selection", "length", "to", "get", "the", "whole", "line", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/TextUtils.java#L123-L137
train
roboconf/roboconf-platform
core/roboconf-target-docker/src/main/java/net/roboconf/target/docker/internal/DockerMachineConfigurator.java
DockerMachineConfigurator.createImage
void createImage( String imageId ) throws TargetException { // If there is no Dockerfile, this method will do nothing File targetDirectory = this.parameters.getTargetPropertiesDirectory(); String dockerFilePath = this.parameters.getTargetProperties().get( GENERATE_IMAGE_FROM ); if( ! Utils.isEmptyOrWhitespaces( dockerFilePath ) && targetDirectory != null ) { this.logger.fine( "Trying to create image " + imageId + " from a Dockerfile." ); File dockerFile = new File( targetDirectory, dockerFilePath ); if( ! dockerFile.exists()) throw new TargetException( "No Dockerfile was found at " + dockerFile ); // Start the build. // This will block the current thread until the creation is complete. String builtImageId; this.logger.fine( "Asking Docker to build the image from our Dockerfile." ); try { builtImageId = this.dockerClient .buildImageCmd( dockerFile ) .withTags( Sets.newHashSet( imageId )) .withPull( true ) .exec( new RoboconfBuildImageResultCallback()) .awaitImageId(); } catch( Exception e ) { Utils.logException( this.logger, e ); throw new TargetException( e ); } // No need to store the real image ID... Docker has it. // Besides, we search images by both IDs and tags. // Anyway, we can log the information. this.logger.fine( "Image '" + builtImageId + "' was succesfully generated by Roboconf." ); } }
java
void createImage( String imageId ) throws TargetException { // If there is no Dockerfile, this method will do nothing File targetDirectory = this.parameters.getTargetPropertiesDirectory(); String dockerFilePath = this.parameters.getTargetProperties().get( GENERATE_IMAGE_FROM ); if( ! Utils.isEmptyOrWhitespaces( dockerFilePath ) && targetDirectory != null ) { this.logger.fine( "Trying to create image " + imageId + " from a Dockerfile." ); File dockerFile = new File( targetDirectory, dockerFilePath ); if( ! dockerFile.exists()) throw new TargetException( "No Dockerfile was found at " + dockerFile ); // Start the build. // This will block the current thread until the creation is complete. String builtImageId; this.logger.fine( "Asking Docker to build the image from our Dockerfile." ); try { builtImageId = this.dockerClient .buildImageCmd( dockerFile ) .withTags( Sets.newHashSet( imageId )) .withPull( true ) .exec( new RoboconfBuildImageResultCallback()) .awaitImageId(); } catch( Exception e ) { Utils.logException( this.logger, e ); throw new TargetException( e ); } // No need to store the real image ID... Docker has it. // Besides, we search images by both IDs and tags. // Anyway, we can log the information. this.logger.fine( "Image '" + builtImageId + "' was succesfully generated by Roboconf." ); } }
[ "void", "createImage", "(", "String", "imageId", ")", "throws", "TargetException", "{", "// If there is no Dockerfile, this method will do nothing", "File", "targetDirectory", "=", "this", ".", "parameters", ".", "getTargetPropertiesDirectory", "(", ")", ";", "String", "d...
Creates an image. @param imageId the image ID @throws TargetException if something went wrong
[ "Creates", "an", "image", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-docker/src/main/java/net/roboconf/target/docker/internal/DockerMachineConfigurator.java#L260-L294
train
roboconf/roboconf-platform
core/roboconf-dm-rest-commons/src/main/java/net/roboconf/dm/rest/commons/security/AuthenticationManager.java
AuthenticationManager.login
public String login( String user, String pwd ) { String token = null; try { this.authService.authenticate( user, pwd ); token = UUID.randomUUID().toString(); Long now = new Date().getTime(); this.tokenToLoginTime.put( token, now ); this.tokenToUsername.put( token, user ); } catch( LoginException e ) { this.logger.severe( "Invalid login attempt by user " + user ); } return token; }
java
public String login( String user, String pwd ) { String token = null; try { this.authService.authenticate( user, pwd ); token = UUID.randomUUID().toString(); Long now = new Date().getTime(); this.tokenToLoginTime.put( token, now ); this.tokenToUsername.put( token, user ); } catch( LoginException e ) { this.logger.severe( "Invalid login attempt by user " + user ); } return token; }
[ "public", "String", "login", "(", "String", "user", ",", "String", "pwd", ")", "{", "String", "token", "=", "null", ";", "try", "{", "this", ".", "authService", ".", "authenticate", "(", "user", ",", "pwd", ")", ";", "token", "=", "UUID", ".", "rando...
Authenticates a user and creates a new session. @param user a user name @param pwd a pass word @return a token if authentication worked, null if it failed
[ "Authenticates", "a", "user", "and", "creates", "a", "new", "session", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-rest-commons/src/main/java/net/roboconf/dm/rest/commons/security/AuthenticationManager.java#L103-L119
train
roboconf/roboconf-platform
core/roboconf-dm-rest-commons/src/main/java/net/roboconf/dm/rest/commons/security/AuthenticationManager.java
AuthenticationManager.isSessionValid
public boolean isSessionValid( final String token, long validityPeriod ) { boolean valid = false; Long loginTime = null; if( token != null ) loginTime = this.tokenToLoginTime.get( token ); if( validityPeriod < 0 ) { valid = loginTime != null; } else if( loginTime != null ) { long now = new Date().getTime(); valid = (now - loginTime) <= validityPeriod * 1000; // Invalid sessions should be deleted if( ! valid ) logout( token ); } return valid; }
java
public boolean isSessionValid( final String token, long validityPeriod ) { boolean valid = false; Long loginTime = null; if( token != null ) loginTime = this.tokenToLoginTime.get( token ); if( validityPeriod < 0 ) { valid = loginTime != null; } else if( loginTime != null ) { long now = new Date().getTime(); valid = (now - loginTime) <= validityPeriod * 1000; // Invalid sessions should be deleted if( ! valid ) logout( token ); } return valid; }
[ "public", "boolean", "isSessionValid", "(", "final", "String", "token", ",", "long", "validityPeriod", ")", "{", "boolean", "valid", "=", "false", ";", "Long", "loginTime", "=", "null", ";", "if", "(", "token", "!=", "null", ")", "loginTime", "=", "this", ...
Determines whether a session is valid. @param token a token @param validityPeriod the validity period for a session (in seconds, < 0 for unbound) @return true if the session is valid, false otherwise
[ "Determines", "whether", "a", "session", "is", "valid", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-rest-commons/src/main/java/net/roboconf/dm/rest/commons/security/AuthenticationManager.java#L128-L148
train
stephanrauh/AngularFaces
AngularFaces_2.0/incubator/AngularFaces-widgets/src/main/java/de/beyondjava/angularFaces/flavors/kendo/puiInputText/PuiInputText.java
PuiInputText.processEvent
@Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (!FacesContext.getCurrentInstance().isPostback()) { // if (!(getParent() instanceof Column)) { insertLabelBeforeThisInputField(); insertMessageBehindThisInputField(); } // } }
java
@Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (!FacesContext.getCurrentInstance().isPostback()) { // if (!(getParent() instanceof Column)) { insertLabelBeforeThisInputField(); insertMessageBehindThisInputField(); } // } }
[ "@", "Override", "public", "void", "processEvent", "(", "SystemEvent", "event", ")", "throws", "AbortProcessingException", "{", "if", "(", "!", "FacesContext", ".", "getCurrentInstance", "(", ")", ".", "isPostback", "(", ")", ")", "{", "// if (!(getParent() instan...
Catching the PreRenderViewEvent allows AngularFaces to modify the JSF tree by adding a label and a message.
[ "Catching", "the", "PreRenderViewEvent", "allows", "AngularFaces", "to", "modify", "the", "JSF", "tree", "by", "adding", "a", "label", "and", "a", "message", "." ]
43d915f004645b1bbbf2625214294dab0858ba01
https://github.com/stephanrauh/AngularFaces/blob/43d915f004645b1bbbf2625214294dab0858ba01/AngularFaces_2.0/incubator/AngularFaces-widgets/src/main/java/de/beyondjava/angularFaces/flavors/kendo/puiInputText/PuiInputText.java#L74-L82
train
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java
Ec2MachineConfigurator.associateElasticIp
private boolean associateElasticIp() { String elasticIp = this.targetProperties.get( Ec2Constants.ELASTIC_IP ); if( ! Utils.isEmptyOrWhitespaces( elasticIp )) { this.logger.fine( "Associating an elastic IP with the instance. IP = " + elasticIp ); AssociateAddressRequest associateAddressRequest = new AssociateAddressRequest( this.machineId, elasticIp ); this.ec2Api.associateAddress( associateAddressRequest ); } return true; }
java
private boolean associateElasticIp() { String elasticIp = this.targetProperties.get( Ec2Constants.ELASTIC_IP ); if( ! Utils.isEmptyOrWhitespaces( elasticIp )) { this.logger.fine( "Associating an elastic IP with the instance. IP = " + elasticIp ); AssociateAddressRequest associateAddressRequest = new AssociateAddressRequest( this.machineId, elasticIp ); this.ec2Api.associateAddress( associateAddressRequest ); } return true; }
[ "private", "boolean", "associateElasticIp", "(", ")", "{", "String", "elasticIp", "=", "this", ".", "targetProperties", ".", "get", "(", "Ec2Constants", ".", "ELASTIC_IP", ")", ";", "if", "(", "!", "Utils", ".", "isEmptyOrWhitespaces", "(", "elasticIp", ")", ...
Associates an elastic IP with the VM. @return true if there is nothing more to do about elastic IP configuration, false otherwise
[ "Associates", "an", "elastic", "IP", "with", "the", "VM", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java#L207-L217
train
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java
Ec2MachineConfigurator.createVolume
private String createVolume(String storageId, String snapshotId, int size) { String volumeType = Ec2IaasHandler.findStorageProperty(this.targetProperties, storageId, VOLUME_TYPE_PREFIX); if(volumeType == null) volumeType = "standard"; CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest() .withAvailabilityZone( this.availabilityZone ) .withVolumeType( volumeType ) .withSize( size ); // The size of the volume, in gigabytes. // EC2 snapshot IDs start with "snap-"... if(! Utils.isEmptyOrWhitespaces(snapshotId) && snapshotId.startsWith("snap-")) createVolumeRequest.withSnapshotId(snapshotId); CreateVolumeResult createVolumeResult = this.ec2Api.createVolume(createVolumeRequest); return createVolumeResult.getVolume().getVolumeId(); }
java
private String createVolume(String storageId, String snapshotId, int size) { String volumeType = Ec2IaasHandler.findStorageProperty(this.targetProperties, storageId, VOLUME_TYPE_PREFIX); if(volumeType == null) volumeType = "standard"; CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest() .withAvailabilityZone( this.availabilityZone ) .withVolumeType( volumeType ) .withSize( size ); // The size of the volume, in gigabytes. // EC2 snapshot IDs start with "snap-"... if(! Utils.isEmptyOrWhitespaces(snapshotId) && snapshotId.startsWith("snap-")) createVolumeRequest.withSnapshotId(snapshotId); CreateVolumeResult createVolumeResult = this.ec2Api.createVolume(createVolumeRequest); return createVolumeResult.getVolume().getVolumeId(); }
[ "private", "String", "createVolume", "(", "String", "storageId", ",", "String", "snapshotId", ",", "int", "size", ")", "{", "String", "volumeType", "=", "Ec2IaasHandler", ".", "findStorageProperty", "(", "this", ".", "targetProperties", ",", "storageId", ",", "V...
Creates volume for EBS. @return volume ID of newly created volume
[ "Creates", "volume", "for", "EBS", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java#L284-L299
train
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java
Ec2MachineConfigurator.volumeCreated
private boolean volumeCreated(String volumeId) { DescribeVolumesRequest dvs = new DescribeVolumesRequest(); ArrayList<String> volumeIds = new ArrayList<String>(); volumeIds.add(volumeId); dvs.setVolumeIds(volumeIds); DescribeVolumesResult dvsresult = null; try { dvsresult = this.ec2Api.describeVolumes(dvs); } catch(Exception e) { dvsresult = null; } return dvsresult != null && "available".equals(dvsresult.getVolumes().get(0).getState()); }
java
private boolean volumeCreated(String volumeId) { DescribeVolumesRequest dvs = new DescribeVolumesRequest(); ArrayList<String> volumeIds = new ArrayList<String>(); volumeIds.add(volumeId); dvs.setVolumeIds(volumeIds); DescribeVolumesResult dvsresult = null; try { dvsresult = this.ec2Api.describeVolumes(dvs); } catch(Exception e) { dvsresult = null; } return dvsresult != null && "available".equals(dvsresult.getVolumes().get(0).getState()); }
[ "private", "boolean", "volumeCreated", "(", "String", "volumeId", ")", "{", "DescribeVolumesRequest", "dvs", "=", "new", "DescribeVolumesRequest", "(", ")", ";", "ArrayList", "<", "String", ">", "volumeIds", "=", "new", "ArrayList", "<", "String", ">", "(", ")...
Checks whether volume is created. @param volumeId the EBS volume ID @return true if volume created, false otherwise
[ "Checks", "whether", "volume", "is", "created", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java#L306-L319
train
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java
Ec2MachineConfigurator.volumesCreated
private boolean volumesCreated() { for( Map.Entry<String,String> entry : this.storageIdToVolumeId.entrySet()) { String volumeId = entry.getValue(); if(! volumeCreated(volumeId)) return false; } return true; }
java
private boolean volumesCreated() { for( Map.Entry<String,String> entry : this.storageIdToVolumeId.entrySet()) { String volumeId = entry.getValue(); if(! volumeCreated(volumeId)) return false; } return true; }
[ "private", "boolean", "volumesCreated", "(", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "this", ".", "storageIdToVolumeId", ".", "entrySet", "(", ")", ")", "{", "String", "volumeId", "=", "entry", ".", "...
Checks whether all specified volumes are created. @return true if all volumes created, false otherwise
[ "Checks", "whether", "all", "specified", "volumes", "are", "created", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java#L325-L331
train
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java
Ec2MachineConfigurator.lookupVolume
private String lookupVolume(String volumeIdOrName) { String ret = null; if(! Utils.isEmptyOrWhitespaces(volumeIdOrName)) { // Lookup by volume ID DescribeVolumesRequest dvs = new DescribeVolumesRequest(Collections.singletonList(volumeIdOrName)); DescribeVolumesResult dvsresult = null; try { dvsresult = this.ec2Api.describeVolumes(dvs); } catch(Exception e) { dvsresult = null; } // If not found, lookup by name if(dvsresult == null || dvsresult.getVolumes() == null || dvsresult.getVolumes().size() < 1) { dvs = new DescribeVolumesRequest().withFilters(new Filter().withName("tag:Name").withValues(volumeIdOrName)); try { dvsresult = this.ec2Api.describeVolumes(dvs); } catch(Exception e) { dvsresult = null; } } if(dvsresult != null && dvsresult.getVolumes() != null && dvsresult.getVolumes().size() > 0) ret = dvsresult.getVolumes().get(0).getVolumeId(); } return ret; }
java
private String lookupVolume(String volumeIdOrName) { String ret = null; if(! Utils.isEmptyOrWhitespaces(volumeIdOrName)) { // Lookup by volume ID DescribeVolumesRequest dvs = new DescribeVolumesRequest(Collections.singletonList(volumeIdOrName)); DescribeVolumesResult dvsresult = null; try { dvsresult = this.ec2Api.describeVolumes(dvs); } catch(Exception e) { dvsresult = null; } // If not found, lookup by name if(dvsresult == null || dvsresult.getVolumes() == null || dvsresult.getVolumes().size() < 1) { dvs = new DescribeVolumesRequest().withFilters(new Filter().withName("tag:Name").withValues(volumeIdOrName)); try { dvsresult = this.ec2Api.describeVolumes(dvs); } catch(Exception e) { dvsresult = null; } } if(dvsresult != null && dvsresult.getVolumes() != null && dvsresult.getVolumes().size() > 0) ret = dvsresult.getVolumes().get(0).getVolumeId(); } return ret; }
[ "private", "String", "lookupVolume", "(", "String", "volumeIdOrName", ")", "{", "String", "ret", "=", "null", ";", "if", "(", "!", "Utils", ".", "isEmptyOrWhitespaces", "(", "volumeIdOrName", ")", ")", "{", "// Lookup by volume ID", "DescribeVolumesRequest", "dvs"...
Looks up volume, by ID or Name tag. @param volumeIdOrName the EBS volume ID or Name tag @return The volume ID of 1st matching volume found, null if no volume found
[ "Looks", "up", "volume", "by", "ID", "or", "Name", "tag", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java#L338-L367
train
roboconf/roboconf-platform
miscellaneous/roboconf-doc-generator/src/main/java/net/roboconf/doc/generator/internal/nls/Messages.java
Messages.get
public String get( String key ) { String result; try { result = this.bundle.getString( key ); } catch( MissingResourceException e ) { result = OOPS + key + '!'; } return result; }
java
public String get( String key ) { String result; try { result = this.bundle.getString( key ); } catch( MissingResourceException e ) { result = OOPS + key + '!'; } return result; }
[ "public", "String", "get", "(", "String", "key", ")", "{", "String", "result", ";", "try", "{", "result", "=", "this", ".", "bundle", ".", "getString", "(", "key", ")", ";", "}", "catch", "(", "MissingResourceException", "e", ")", "{", "result", "=", ...
Finds an internationalized string by key. @param key a non-null key @return a string (never null)
[ "Finds", "an", "internationalized", "string", "by", "key", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-doc-generator/src/main/java/net/roboconf/doc/generator/internal/nls/Messages.java#L67-L78
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/beans/Application.java
Application.getExternalExports
public Map<String,String> getExternalExports() { return this.template != null ? this.template.externalExports : new HashMap<String,String>( 0 ); }
java
public Map<String,String> getExternalExports() { return this.template != null ? this.template.externalExports : new HashMap<String,String>( 0 ); }
[ "public", "Map", "<", "String", ",", "String", ">", "getExternalExports", "(", ")", "{", "return", "this", ".", "template", "!=", "null", "?", "this", ".", "template", ".", "externalExports", ":", "new", "HashMap", "<", "String", ",", "String", ">", "(",...
A shortcut method to access the template's external exports mapping. @return a non-null map
[ "A", "shortcut", "method", "to", "access", "the", "template", "s", "external", "exports", "mapping", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/beans/Application.java#L93-L95
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/beans/Application.java
Application.replaceApplicationBindings
public boolean replaceApplicationBindings( String externalExportPrefix, Set<String> applicationNames ) { // There is a change if the set do not have the same size or if they do not contain the same // number of element. If no binding had been registered previously, then we only check whether // the new set contains something. boolean changed = false; Set<String> oldApplicationNames = this.applicationBindings.remove( externalExportPrefix ); if( oldApplicationNames == null ) { changed = ! applicationNames.isEmpty(); } else if( oldApplicationNames.size() != applicationNames.size()) { changed = true; } else { oldApplicationNames.removeAll( applicationNames ); changed = ! oldApplicationNames.isEmpty(); } // Do not register keys when there is no binding if( ! applicationNames.isEmpty()) this.applicationBindings.put( externalExportPrefix, applicationNames ); return changed; }
java
public boolean replaceApplicationBindings( String externalExportPrefix, Set<String> applicationNames ) { // There is a change if the set do not have the same size or if they do not contain the same // number of element. If no binding had been registered previously, then we only check whether // the new set contains something. boolean changed = false; Set<String> oldApplicationNames = this.applicationBindings.remove( externalExportPrefix ); if( oldApplicationNames == null ) { changed = ! applicationNames.isEmpty(); } else if( oldApplicationNames.size() != applicationNames.size()) { changed = true; } else { oldApplicationNames.removeAll( applicationNames ); changed = ! oldApplicationNames.isEmpty(); } // Do not register keys when there is no binding if( ! applicationNames.isEmpty()) this.applicationBindings.put( externalExportPrefix, applicationNames ); return changed; }
[ "public", "boolean", "replaceApplicationBindings", "(", "String", "externalExportPrefix", ",", "Set", "<", "String", ">", "applicationNames", ")", "{", "// There is a change if the set do not have the same size or if they do not contain the same", "// number of element. If no binding h...
Replaces application bindings for a given prefix. @param externalExportPrefix an external export prefix (not null) @param applicationNames a non-null set of application names @return true if bindings were modified, false otherwise
[ "Replaces", "application", "bindings", "for", "a", "given", "prefix", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/beans/Application.java#L192-L215
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/userdata/UserDataHelpers.java
UserDataHelpers.interceptLoadingFiles
static void interceptLoadingFiles( Properties props ) throws IOException { Logger logger = Logger.getLogger( UserDataHelpers.class.getName()); Set<String> keys = props.stringPropertyNames(); for( final String key : keys ) { if( ! key.startsWith( ENCODE_FILE_CONTENT_PREFIX )) continue; String realKey = key.substring( ENCODE_FILE_CONTENT_PREFIX.length()); String value = props.getProperty( realKey ); if( value == null ) { logger.fine( "No file was specified for " + realKey + ". Skipping it..." ); continue; } File f = new File( value ); if( ! f.exists()) throw new IOException( "File " + f + " was not found." ); // Read the file content as bytes ByteArrayOutputStream os = new ByteArrayOutputStream(); Utils.copyStream( f, os ); String encodedFileContent = encodeToBase64( os.toByteArray()); props.put( key, encodedFileContent ); } }
java
static void interceptLoadingFiles( Properties props ) throws IOException { Logger logger = Logger.getLogger( UserDataHelpers.class.getName()); Set<String> keys = props.stringPropertyNames(); for( final String key : keys ) { if( ! key.startsWith( ENCODE_FILE_CONTENT_PREFIX )) continue; String realKey = key.substring( ENCODE_FILE_CONTENT_PREFIX.length()); String value = props.getProperty( realKey ); if( value == null ) { logger.fine( "No file was specified for " + realKey + ". Skipping it..." ); continue; } File f = new File( value ); if( ! f.exists()) throw new IOException( "File " + f + " was not found." ); // Read the file content as bytes ByteArrayOutputStream os = new ByteArrayOutputStream(); Utils.copyStream( f, os ); String encodedFileContent = encodeToBase64( os.toByteArray()); props.put( key, encodedFileContent ); } }
[ "static", "void", "interceptLoadingFiles", "(", "Properties", "props", ")", "throws", "IOException", "{", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "UserDataHelpers", ".", "class", ".", "getName", "(", ")", ")", ";", "Set", "<", "String", ">"...
Intercepts the properties and loads file contents. @param props non-null properties @throws IOException if files had to be loaded and were not found
[ "Intercepts", "the", "properties", "and", "loads", "file", "contents", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/userdata/UserDataHelpers.java#L204-L229
train
roboconf/roboconf-platform
karaf/roboconf-karaf-prepare/src/main/java/net/roboconf/karaf/prepare/GeneratePreferencesFile.java
GeneratePreferencesFile.run
public void run( String[] args ) throws Exception { // Check the argument if( args.length != 1 ) throw new RuntimeException( "A file path was expected as an argument." ); File targetFile = new File( args[ 0 ]); if( ! targetFile.isFile()) throw new RuntimeException( "File " + targetFile + " does not exist." ); // Prepare the comments for all the properties Field[] fields = IPreferencesMngr.class.getDeclaredFields(); Map<String,String> propertyNameToComment = new HashMap<> (); for( Field field : fields ) { String constantName = (String) field.get( null ); PreferenceDescription annotation = field.getAnnotation( PreferenceDescription.class ); if( annotation == null ) throw new RuntimeException( "Documentation was not written for the " + field.getName() + " constant in IPreferencesMngr.java." ); StringBuilder sb = new StringBuilder(); sb.append( annotation.desc()); String[] values = annotation.values(); if( values.length > 0 ) { sb.append( "\n\nPossible values:\n" ); for( String value : values ) { sb.append( " - " ); sb.append( value ); sb.append( "\n" ); } } propertyNameToComment.put( constantName, sb.toString()); } // Prepare the content to generate Defaults def = new Defaults(); StringBuilder sb = new StringBuilder(); for( PreferenceKeyCategory cat : PreferenceKeyCategory.values()) { sb.append( "\n###\n# " ); sb.append( cat.getDescription()); sb.append( "\n###\n" ); for( Map.Entry<String,PreferenceKeyCategory> entry : def.keyToCategory.entrySet()) { if( cat != entry.getValue()) continue; String comment = propertyNameToComment.get( entry.getKey()); comment = comment.replaceAll( "^", "# " ).replace( "\n", "\n# " ); sb.append( "\n" ); sb.append( comment ); sb.append( "\n" ); sb.append( entry.getKey()); sb.append( " = " ); String defaultValue = def.keyToDefaultValue.get( entry.getKey()); if( ! Utils.isEmptyOrWhitespaces( defaultValue )) sb.append( defaultValue.trim()); sb.append( "\n" ); } sb.append( "\n" ); } // Update the file Utils.appendStringInto( sb.toString(), targetFile ); }
java
public void run( String[] args ) throws Exception { // Check the argument if( args.length != 1 ) throw new RuntimeException( "A file path was expected as an argument." ); File targetFile = new File( args[ 0 ]); if( ! targetFile.isFile()) throw new RuntimeException( "File " + targetFile + " does not exist." ); // Prepare the comments for all the properties Field[] fields = IPreferencesMngr.class.getDeclaredFields(); Map<String,String> propertyNameToComment = new HashMap<> (); for( Field field : fields ) { String constantName = (String) field.get( null ); PreferenceDescription annotation = field.getAnnotation( PreferenceDescription.class ); if( annotation == null ) throw new RuntimeException( "Documentation was not written for the " + field.getName() + " constant in IPreferencesMngr.java." ); StringBuilder sb = new StringBuilder(); sb.append( annotation.desc()); String[] values = annotation.values(); if( values.length > 0 ) { sb.append( "\n\nPossible values:\n" ); for( String value : values ) { sb.append( " - " ); sb.append( value ); sb.append( "\n" ); } } propertyNameToComment.put( constantName, sb.toString()); } // Prepare the content to generate Defaults def = new Defaults(); StringBuilder sb = new StringBuilder(); for( PreferenceKeyCategory cat : PreferenceKeyCategory.values()) { sb.append( "\n###\n# " ); sb.append( cat.getDescription()); sb.append( "\n###\n" ); for( Map.Entry<String,PreferenceKeyCategory> entry : def.keyToCategory.entrySet()) { if( cat != entry.getValue()) continue; String comment = propertyNameToComment.get( entry.getKey()); comment = comment.replaceAll( "^", "# " ).replace( "\n", "\n# " ); sb.append( "\n" ); sb.append( comment ); sb.append( "\n" ); sb.append( entry.getKey()); sb.append( " = " ); String defaultValue = def.keyToDefaultValue.get( entry.getKey()); if( ! Utils.isEmptyOrWhitespaces( defaultValue )) sb.append( defaultValue.trim()); sb.append( "\n" ); } sb.append( "\n" ); } // Update the file Utils.appendStringInto( sb.toString(), targetFile ); }
[ "public", "void", "run", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "// Check the argument", "if", "(", "args", ".", "length", "!=", "1", ")", "throw", "new", "RuntimeException", "(", "\"A file path was expected as an argument.\"", ")", ";...
The real method that does the job. @param args @throws Exception
[ "The", "real", "method", "that", "does", "the", "job", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/karaf/roboconf-karaf-prepare/src/main/java/net/roboconf/karaf/prepare/GeneratePreferencesFile.java#L72-L140
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/beans/Component.java
Component.extendComponent
public void extendComponent( Component component ) { if( this.extendedComponent != null ) this.extendedComponent.extendingComponents.remove( this ); component.extendingComponents.add( this ); this.extendedComponent = component; }
java
public void extendComponent( Component component ) { if( this.extendedComponent != null ) this.extendedComponent.extendingComponents.remove( this ); component.extendingComponents.add( this ); this.extendedComponent = component; }
[ "public", "void", "extendComponent", "(", "Component", "component", ")", "{", "if", "(", "this", ".", "extendedComponent", "!=", "null", ")", "this", ".", "extendedComponent", ".", "extendingComponents", ".", "remove", "(", "this", ")", ";", "component", ".", ...
Creates a bi-directional relation between this component and an extended one. @param component a component
[ "Creates", "a", "bi", "-", "directional", "relation", "between", "this", "component", "and", "an", "extended", "one", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/beans/Component.java#L121-L128
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/beans/AutonomicApplicationContext.java
AutonomicApplicationContext.findRulesToExecute
public List<Rule> findRulesToExecute() { this.logger.fine( "Looking for rules to execute after an event was recorded for application " + this.app ); List<Rule> result = new ArrayList<> (); long now = System.nanoTime(); /* * For all the rules, find if there are events that should trigger its execution. */ for( Rule rule : this.ruleNameToRule.values()) { /* * A rule can be added if... * 1 - If its last execution occurred more than "the rule's delay" ago. * 2 - This event did not already trigger the execution of the rule. * 3 - If this rule has no timing window OR if the event occurred within the timing window. */ // Check the condition "1", about the last execution. long validPeriodStart = now - TimeUnit.SECONDS.toNanos( rule.getDelayBetweenSucceedingInvocations()); Long lastExecutionTime = this.ruleNameToLastExecution.get( rule.getRuleName()); if( lastExecutionTime != null && lastExecutionTime - validPeriodStart > 0 ) { this.logger.finer( "Ignoring the rule " + rule.getRuleName() + " since the execution delay has not yet expired." ); continue; } // Check the condition "2", or said differently, did this event record already trigger // the execution of this rule? // No record? Then the rule cannot be triggered. Long lastRecord = this.eventNameToLastRecordTime.get( rule.getEventName()); if( lastRecord == null ) continue; // FIXME: for the moment, a rule is activated by a single event. // But later, it will be boolean combination of events. So, keep // the string builder to generate it. StringBuilder sbTrigger = new StringBuilder(); sbTrigger.append( rule.getEventName()); sbTrigger.append( lastRecord ); String lastTrigger = this.ruleNameToLastTrigger.get( rule.getRuleName()); if( Objects.equals( lastTrigger, sbTrigger.toString())) { this.logger.finer( "Ignoring the rule " + rule.getRuleName() + " since no new event occurred since its last execution." ); continue; } // Check the condition "3", the one that prevents a recent event from "spamming". // Too old events may not be relevant. This is why rules can define a timing window. // FIXME: with one event as a trigger, it does not really make sense. // But with a combination of events, it will. // Either there is no timing window... // ... or the last record occurred between 'now' and 'now - timing window'. validPeriodStart = now - TimeUnit.SECONDS.toNanos( rule.getTimingWindow()); if( rule.getTimingWindow() != Rule.NO_TIMING_WINDOW && lastRecord - validPeriodStart < 0 ) { this.logger.finer( "Ignoring the rule " + rule.getRuleName() + " since no new event occurred since its last execution." ); continue; } this.logger.finer( "Rule " + rule.getRuleName() + " was found following the occurrence of the " + rule.getEventName() + " event." ); this.ruleNameToLastTrigger.put( rule.getRuleName(), sbTrigger.toString()); result.add( rule ); // Other checks? /* * Long story... * Formerly, there were no commands mechanism. Reactions to events * were more simple and atomic (one reaction => one simple command, not several scripted ones). * * But, at this time, permissions were more strictly controlled. * Beyond execution time, we were also checking the last execution had completed correctly. * As an example, if the reaction to an event was "replicate this vm", we were checking that * the new VM and all its children had been deployed and started before executing it again. * There were some strong hypothesis behind. In fact, in real use cases, we cannot perform such verifications. * * Indeed, it is possible to determine from a command file what should be the name and the state * of application instances when the execution completes. We would then be able to compare the real * states with the foreseen ones. However, many things can prevent the real states from reaching or * remaining in the expected ones. As an example, a user may manually modify a state with the REST API. * Other commands, triggered by other events, may modify states and give contradictory instructions. * * In such a situation, the last execution would never been considered as completed. * This method would then prevent an event from being processed anymore. And the autonomic would become * useless. As a reminder, messages are processed one after the other in both the DM and agents. But even * if (autonomic) messages are not processed concurrently, such contradictory situations may occur. Trying to * cover such complex verifications would certainly fail and raise more bugs and problems than benefits. * * The only reasonable assumption that can be made is a safety delay between two succeeding * processing for a same event. This also has the advantage of being simple to understand and simple to predict. * If we had to provide something to help users detecting contradictions in the autonomic, it would be better * to have an analysis tool rather than finding workarounds for them at runtime. */ // So, no other check related to a previous execution. } return result; }
java
public List<Rule> findRulesToExecute() { this.logger.fine( "Looking for rules to execute after an event was recorded for application " + this.app ); List<Rule> result = new ArrayList<> (); long now = System.nanoTime(); /* * For all the rules, find if there are events that should trigger its execution. */ for( Rule rule : this.ruleNameToRule.values()) { /* * A rule can be added if... * 1 - If its last execution occurred more than "the rule's delay" ago. * 2 - This event did not already trigger the execution of the rule. * 3 - If this rule has no timing window OR if the event occurred within the timing window. */ // Check the condition "1", about the last execution. long validPeriodStart = now - TimeUnit.SECONDS.toNanos( rule.getDelayBetweenSucceedingInvocations()); Long lastExecutionTime = this.ruleNameToLastExecution.get( rule.getRuleName()); if( lastExecutionTime != null && lastExecutionTime - validPeriodStart > 0 ) { this.logger.finer( "Ignoring the rule " + rule.getRuleName() + " since the execution delay has not yet expired." ); continue; } // Check the condition "2", or said differently, did this event record already trigger // the execution of this rule? // No record? Then the rule cannot be triggered. Long lastRecord = this.eventNameToLastRecordTime.get( rule.getEventName()); if( lastRecord == null ) continue; // FIXME: for the moment, a rule is activated by a single event. // But later, it will be boolean combination of events. So, keep // the string builder to generate it. StringBuilder sbTrigger = new StringBuilder(); sbTrigger.append( rule.getEventName()); sbTrigger.append( lastRecord ); String lastTrigger = this.ruleNameToLastTrigger.get( rule.getRuleName()); if( Objects.equals( lastTrigger, sbTrigger.toString())) { this.logger.finer( "Ignoring the rule " + rule.getRuleName() + " since no new event occurred since its last execution." ); continue; } // Check the condition "3", the one that prevents a recent event from "spamming". // Too old events may not be relevant. This is why rules can define a timing window. // FIXME: with one event as a trigger, it does not really make sense. // But with a combination of events, it will. // Either there is no timing window... // ... or the last record occurred between 'now' and 'now - timing window'. validPeriodStart = now - TimeUnit.SECONDS.toNanos( rule.getTimingWindow()); if( rule.getTimingWindow() != Rule.NO_TIMING_WINDOW && lastRecord - validPeriodStart < 0 ) { this.logger.finer( "Ignoring the rule " + rule.getRuleName() + " since no new event occurred since its last execution." ); continue; } this.logger.finer( "Rule " + rule.getRuleName() + " was found following the occurrence of the " + rule.getEventName() + " event." ); this.ruleNameToLastTrigger.put( rule.getRuleName(), sbTrigger.toString()); result.add( rule ); // Other checks? /* * Long story... * Formerly, there were no commands mechanism. Reactions to events * were more simple and atomic (one reaction => one simple command, not several scripted ones). * * But, at this time, permissions were more strictly controlled. * Beyond execution time, we were also checking the last execution had completed correctly. * As an example, if the reaction to an event was "replicate this vm", we were checking that * the new VM and all its children had been deployed and started before executing it again. * There were some strong hypothesis behind. In fact, in real use cases, we cannot perform such verifications. * * Indeed, it is possible to determine from a command file what should be the name and the state * of application instances when the execution completes. We would then be able to compare the real * states with the foreseen ones. However, many things can prevent the real states from reaching or * remaining in the expected ones. As an example, a user may manually modify a state with the REST API. * Other commands, triggered by other events, may modify states and give contradictory instructions. * * In such a situation, the last execution would never been considered as completed. * This method would then prevent an event from being processed anymore. And the autonomic would become * useless. As a reminder, messages are processed one after the other in both the DM and agents. But even * if (autonomic) messages are not processed concurrently, such contradictory situations may occur. Trying to * cover such complex verifications would certainly fail and raise more bugs and problems than benefits. * * The only reasonable assumption that can be made is a safety delay between two succeeding * processing for a same event. This also has the advantage of being simple to understand and simple to predict. * If we had to provide something to help users detecting contradictions in the autonomic, it would be better * to have an analysis tool rather than finding workarounds for them at runtime. */ // So, no other check related to a previous execution. } return result; }
[ "public", "List", "<", "Rule", ">", "findRulesToExecute", "(", ")", "{", "this", ".", "logger", ".", "fine", "(", "\"Looking for rules to execute after an event was recorded for application \"", "+", "this", ".", "app", ")", ";", "List", "<", "Rule", ">", "result"...
Finds the rules to execute after an event was recorded. @return a non-null list of rules
[ "Finds", "the", "rules", "to", "execute", "after", "an", "event", "was", "recorded", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/beans/AutonomicApplicationContext.java#L109-L211
train
roboconf/roboconf-platform
core/roboconf-dm-templating/src/main/java/net/roboconf/dm/templating/internal/helpers/AllHelper.java
AllHelper.safeApply
private String safeApply( Collection<InstanceContextBean> instances, Options options, String componentPath ) throws IOException { // Parse the filter. String installerName = (String) options.hash.get( "installer" ); final InstanceFilter filter = InstanceFilter.createFilter( componentPath, installerName ); // Apply the filter. final Collection<InstanceContextBean> selectedInstances = filter.apply( instances ); // Apply the content template of the helper to each selected instance. final StringBuilder buffer = new StringBuilder(); final Context parent = options.context; int index = 0; final int last = selectedInstances.size() - 1; for( final InstanceContextBean instance : selectedInstances ) { final Context current = Context.newBuilder( parent, instance ) .combine( "@index", index ) .combine( "@first", index == 0 ? "first" : "" ) .combine( "@last", index == last ? "last" : "" ) .combine( "@odd", index % 2 == 0 ? "" : "odd" ) .combine( "@even", index % 2 == 0 ? "even" : "" ) .build(); index++; buffer.append( options.fn( current )); } return buffer.toString(); }
java
private String safeApply( Collection<InstanceContextBean> instances, Options options, String componentPath ) throws IOException { // Parse the filter. String installerName = (String) options.hash.get( "installer" ); final InstanceFilter filter = InstanceFilter.createFilter( componentPath, installerName ); // Apply the filter. final Collection<InstanceContextBean> selectedInstances = filter.apply( instances ); // Apply the content template of the helper to each selected instance. final StringBuilder buffer = new StringBuilder(); final Context parent = options.context; int index = 0; final int last = selectedInstances.size() - 1; for( final InstanceContextBean instance : selectedInstances ) { final Context current = Context.newBuilder( parent, instance ) .combine( "@index", index ) .combine( "@first", index == 0 ? "first" : "" ) .combine( "@last", index == last ? "last" : "" ) .combine( "@odd", index % 2 == 0 ? "" : "odd" ) .combine( "@even", index % 2 == 0 ? "even" : "" ) .build(); index++; buffer.append( options.fn( current )); } return buffer.toString(); }
[ "private", "String", "safeApply", "(", "Collection", "<", "InstanceContextBean", ">", "instances", ",", "Options", "options", ",", "String", "componentPath", ")", "throws", "IOException", "{", "// Parse the filter.", "String", "installerName", "=", "(", "String", ")...
Same as above, but with type-safe arguments. @param instances the instances to which this helper is applied. @param options the options of this helper invocation. @return a string result. @throws IOException if a template cannot be loaded.
[ "Same", "as", "above", "but", "with", "type", "-", "safe", "arguments", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-templating/src/main/java/net/roboconf/dm/templating/internal/helpers/AllHelper.java#L100-L130
train
roboconf/roboconf-platform
core/roboconf-dm-templating/src/main/java/net/roboconf/dm/templating/internal/helpers/AllHelper.java
AllHelper.descendantInstances
private static Collection<InstanceContextBean> descendantInstances( final InstanceContextBean instance ) { final Collection<InstanceContextBean> result = new ArrayList<InstanceContextBean>(); for (final InstanceContextBean child : instance.getChildren()) { result.add( child ); result.addAll( descendantInstances( child ) ); } return result; }
java
private static Collection<InstanceContextBean> descendantInstances( final InstanceContextBean instance ) { final Collection<InstanceContextBean> result = new ArrayList<InstanceContextBean>(); for (final InstanceContextBean child : instance.getChildren()) { result.add( child ); result.addAll( descendantInstances( child ) ); } return result; }
[ "private", "static", "Collection", "<", "InstanceContextBean", ">", "descendantInstances", "(", "final", "InstanceContextBean", "instance", ")", "{", "final", "Collection", "<", "InstanceContextBean", ">", "result", "=", "new", "ArrayList", "<", "InstanceContextBean", ...
Returns all the descendant instances of the given instance. @param instance the instance which descendants must be retrieved. @return the descendants of the given instance.
[ "Returns", "all", "the", "descendant", "instances", "of", "the", "given", "instance", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-templating/src/main/java/net/roboconf/dm/templating/internal/helpers/AllHelper.java#L138-L147
train
vidageek/mirror
src/main/java/net/vidageek/mirror/dsl/Mirror.java
Mirror.reflectClass
public Class<?> reflectClass(final String className) { Preconditions.checkArgument(className != null && className.trim().length() > 0, "className cannot be null or empty"); return provider.getClassReflectionProvider(className).reflectClass(); }
java
public Class<?> reflectClass(final String className) { Preconditions.checkArgument(className != null && className.trim().length() > 0, "className cannot be null or empty"); return provider.getClassReflectionProvider(className).reflectClass(); }
[ "public", "Class", "<", "?", ">", "reflectClass", "(", "final", "String", "className", ")", "{", "Preconditions", ".", "checkArgument", "(", "className", "!=", "null", "&&", "className", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ",", "\...
This method will reflect a Class object that is represented by className. @param className Full qualified name of the class you want to reflect. @return A Class object represented by className. @throws MirrorException if no class on current ClassLoader has class represented by className. @throws IllegalArgumentException if className is null or empty.
[ "This", "method", "will", "reflect", "a", "Class", "object", "that", "is", "represented", "by", "className", "." ]
42af9dad8c0d6e5040b75e83dbcee34bc63dd539
https://github.com/vidageek/mirror/blob/42af9dad8c0d6e5040b75e83dbcee34bc63dd539/src/main/java/net/vidageek/mirror/dsl/Mirror.java#L62-L65
train
vidageek/mirror
src/main/java/net/vidageek/mirror/dsl/Mirror.java
Mirror.on
public <T> ClassController<T> on(final Class<T> clazz) { return new DefaultClassController<T>(provider, clazz); }
java
public <T> ClassController<T> on(final Class<T> clazz) { return new DefaultClassController<T>(provider, clazz); }
[ "public", "<", "T", ">", "ClassController", "<", "T", ">", "on", "(", "final", "Class", "<", "T", ">", "clazz", ")", "{", "return", "new", "DefaultClassController", "<", "T", ">", "(", "provider", ",", "clazz", ")", ";", "}" ]
Method to access reflection on clazz. @param clazz Class object to be used. @return A object that allows you to access reflection on class clazz. @throws IllegalArgumentException if clazz is null.
[ "Method", "to", "access", "reflection", "on", "clazz", "." ]
42af9dad8c0d6e5040b75e83dbcee34bc63dd539
https://github.com/vidageek/mirror/blob/42af9dad8c0d6e5040b75e83dbcee34bc63dd539/src/main/java/net/vidageek/mirror/dsl/Mirror.java#L76-L78
train
roboconf/roboconf-platform
core/roboconf-target-jclouds/src/main/java/net/roboconf/target/jclouds/internal/JCloudsHandler.java
JCloudsHandler.jcloudContext
ComputeService jcloudContext( Map<String,String> targetProperties ) throws TargetException { validate( targetProperties ); ComputeServiceContext context = ContextBuilder .newBuilder( targetProperties.get( PROVIDER_ID )) .endpoint( targetProperties.get( ENDPOINT )) .credentials( targetProperties.get( IDENTITY ), targetProperties.get( CREDENTIAL )) .buildView( ComputeServiceContext.class ); return context.getComputeService(); }
java
ComputeService jcloudContext( Map<String,String> targetProperties ) throws TargetException { validate( targetProperties ); ComputeServiceContext context = ContextBuilder .newBuilder( targetProperties.get( PROVIDER_ID )) .endpoint( targetProperties.get( ENDPOINT )) .credentials( targetProperties.get( IDENTITY ), targetProperties.get( CREDENTIAL )) .buildView( ComputeServiceContext.class ); return context.getComputeService(); }
[ "ComputeService", "jcloudContext", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ")", "throws", "TargetException", "{", "validate", "(", "targetProperties", ")", ";", "ComputeServiceContext", "context", "=", "ContextBuilder", ".", "newBuilder", ...
Creates a JCloud context. @param targetProperties the target properties @return a non-null object @throws TargetException if the target properties are invalid
[ "Creates", "a", "JCloud", "context", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-jclouds/src/main/java/net/roboconf/target/jclouds/internal/JCloudsHandler.java#L233-L243
train
roboconf/roboconf-platform
core/roboconf-target-jclouds/src/main/java/net/roboconf/target/jclouds/internal/JCloudsHandler.java
JCloudsHandler.validate
static void validate( Map<String,String> targetProperties ) throws TargetException { checkProperty( PROVIDER_ID, targetProperties ); checkProperty( ENDPOINT, targetProperties ); checkProperty( IMAGE_NAME, targetProperties ); checkProperty( SECURITY_GROUP, targetProperties ); checkProperty( IDENTITY, targetProperties ); checkProperty( CREDENTIAL, targetProperties ); checkProperty( HARDWARE_NAME, targetProperties ); }
java
static void validate( Map<String,String> targetProperties ) throws TargetException { checkProperty( PROVIDER_ID, targetProperties ); checkProperty( ENDPOINT, targetProperties ); checkProperty( IMAGE_NAME, targetProperties ); checkProperty( SECURITY_GROUP, targetProperties ); checkProperty( IDENTITY, targetProperties ); checkProperty( CREDENTIAL, targetProperties ); checkProperty( HARDWARE_NAME, targetProperties ); }
[ "static", "void", "validate", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ")", "throws", "TargetException", "{", "checkProperty", "(", "PROVIDER_ID", ",", "targetProperties", ")", ";", "checkProperty", "(", "ENDPOINT", ",", "targetProperties...
Validates the target properties. @param targetProperties the properties @throws TargetException if an error occurred during the validation
[ "Validates", "the", "target", "properties", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-jclouds/src/main/java/net/roboconf/target/jclouds/internal/JCloudsHandler.java#L251-L260
train
roboconf/roboconf-platform
core/roboconf-target-embedded/src/main/java/net/roboconf/target/embedded/internal/ConfiguratorOnCreation.java
ConfiguratorOnCreation.updateAgentConfigurationFile
void updateAgentConfigurationFile( TargetHandlerParameters parameters, SSHClient ssh, File tmpDir, Map<String,String> keyToNewValue ) throws IOException { this.logger.fine( "Updating agent parameters on remote host..." ); // Update the agent's configuration file String agentConfigDir = Utils.getValue( parameters.getTargetProperties(), SCP_AGENT_CONFIG_DIR, DEFAULT_SCP_AGENT_CONFIG_DIR ); File localAgentConfig = new File( tmpDir, Constants.KARAF_CFG_FILE_AGENT ); File remoteAgentConfig = new File( agentConfigDir, Constants.KARAF_CFG_FILE_AGENT ); // Download remote agent config file... ssh.newSCPFileTransfer().download(remoteAgentConfig.getCanonicalPath(), new FileSystemFile(tmpDir)); // Replace "parameters" property to point on the user data file... String config = Utils.readFileContent(localAgentConfig); config = Utils.updateProperties( config, keyToNewValue ); Utils.writeStringInto(config, localAgentConfig); // Then upload agent config file back ssh.newSCPFileTransfer().upload(new FileSystemFile(localAgentConfig), agentConfigDir); }
java
void updateAgentConfigurationFile( TargetHandlerParameters parameters, SSHClient ssh, File tmpDir, Map<String,String> keyToNewValue ) throws IOException { this.logger.fine( "Updating agent parameters on remote host..." ); // Update the agent's configuration file String agentConfigDir = Utils.getValue( parameters.getTargetProperties(), SCP_AGENT_CONFIG_DIR, DEFAULT_SCP_AGENT_CONFIG_DIR ); File localAgentConfig = new File( tmpDir, Constants.KARAF_CFG_FILE_AGENT ); File remoteAgentConfig = new File( agentConfigDir, Constants.KARAF_CFG_FILE_AGENT ); // Download remote agent config file... ssh.newSCPFileTransfer().download(remoteAgentConfig.getCanonicalPath(), new FileSystemFile(tmpDir)); // Replace "parameters" property to point on the user data file... String config = Utils.readFileContent(localAgentConfig); config = Utils.updateProperties( config, keyToNewValue ); Utils.writeStringInto(config, localAgentConfig); // Then upload agent config file back ssh.newSCPFileTransfer().upload(new FileSystemFile(localAgentConfig), agentConfigDir); }
[ "void", "updateAgentConfigurationFile", "(", "TargetHandlerParameters", "parameters", ",", "SSHClient", "ssh", ",", "File", "tmpDir", ",", "Map", "<", "String", ",", "String", ">", "keyToNewValue", ")", "throws", "IOException", "{", "this", ".", "logger", ".", "...
Updates the configuration file of an agent. @param parameters @param ssh @param tmpDir @param keyToNewValue @throws IOException
[ "Updates", "the", "configuration", "file", "of", "an", "agent", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-embedded/src/main/java/net/roboconf/target/embedded/internal/ConfiguratorOnCreation.java#L241-L265
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/ImportHelpers.java
ImportHelpers.updateImports
public static void updateImports( Instance instance, Map<String,Collection<Import>> variablePrefixToImports ) { instance.getImports().clear(); if( variablePrefixToImports != null ) instance.getImports().putAll( variablePrefixToImports ); }
java
public static void updateImports( Instance instance, Map<String,Collection<Import>> variablePrefixToImports ) { instance.getImports().clear(); if( variablePrefixToImports != null ) instance.getImports().putAll( variablePrefixToImports ); }
[ "public", "static", "void", "updateImports", "(", "Instance", "instance", ",", "Map", "<", "String", ",", "Collection", "<", "Import", ">", ">", "variablePrefixToImports", ")", "{", "instance", ".", "getImports", "(", ")", ".", "clear", "(", ")", ";", "if"...
Updates the imports of an instance with new values. @param instance the instance whose imports must be updated @param variablePrefixToImports the new imports (can be null)
[ "Updates", "the", "imports", "of", "an", "instance", "with", "new", "values", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/ImportHelpers.java#L162-L166
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/ImportHelpers.java
ImportHelpers.findImportByExportingInstance
public static Import findImportByExportingInstance( Collection<Import> imports, String exportingInstancePath ) { Import result = null; if( imports != null && exportingInstancePath != null ) { for( Import imp : imports ) { if( exportingInstancePath.equals( imp.getInstancePath())) { result = imp; break; } } } return result; }
java
public static Import findImportByExportingInstance( Collection<Import> imports, String exportingInstancePath ) { Import result = null; if( imports != null && exportingInstancePath != null ) { for( Import imp : imports ) { if( exportingInstancePath.equals( imp.getInstancePath())) { result = imp; break; } } } return result; }
[ "public", "static", "Import", "findImportByExportingInstance", "(", "Collection", "<", "Import", ">", "imports", ",", "String", "exportingInstancePath", ")", "{", "Import", "result", "=", "null", ";", "if", "(", "imports", "!=", "null", "&&", "exportingInstancePat...
Finds a specific import from the path of the instance that exports it. @param imports a collection of imports (that can be null) @param exportingInstancePath the path of the exporting instance @return an import, or null if none was found
[ "Finds", "a", "specific", "import", "from", "the", "path", "of", "the", "instance", "that", "exports", "it", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/ImportHelpers.java#L175-L188
train
roboconf/roboconf-platform
core/roboconf-messaging-http/src/main/java/net/roboconf/messaging/http/internal/HttpUtils.java
HttpUtils.httpMessagingConfiguration
public static Map<String,String> httpMessagingConfiguration( String ip, int port ) { final Map<String,String> result = new LinkedHashMap<>(); result.put( MessagingConstants.MESSAGING_TYPE_PROPERTY, HttpConstants.FACTORY_HTTP ); result.put( HttpConstants.HTTP_SERVER_IP, ip == null ? HttpConstants.DEFAULT_IP : ip ); result.put( HttpConstants.HTTP_SERVER_PORT, "" + (port <= 0 ? HttpConstants.DEFAULT_PORT : port)); return result; }
java
public static Map<String,String> httpMessagingConfiguration( String ip, int port ) { final Map<String,String> result = new LinkedHashMap<>(); result.put( MessagingConstants.MESSAGING_TYPE_PROPERTY, HttpConstants.FACTORY_HTTP ); result.put( HttpConstants.HTTP_SERVER_IP, ip == null ? HttpConstants.DEFAULT_IP : ip ); result.put( HttpConstants.HTTP_SERVER_PORT, "" + (port <= 0 ? HttpConstants.DEFAULT_PORT : port)); return result; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "httpMessagingConfiguration", "(", "String", "ip", ",", "int", "port", ")", "{", "final", "Map", "<", "String", ",", "String", ">", "result", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", ...
Return a HTTP messaging configuration for the given parameters. @param agentPort the HTTP server port of the agent.. May be {@code null}. @return the messaging configuration for the given parameters.
[ "Return", "a", "HTTP", "messaging", "configuration", "for", "the", "given", "parameters", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-messaging-http/src/main/java/net/roboconf/messaging/http/internal/HttpUtils.java#L63-L71
train
roboconf/roboconf-platform
miscellaneous/roboconf-dm-rest-client/src/main/java/net/roboconf/dm/rest/client/delegates/PreferencesWsDelegate.java
PreferencesWsDelegate.listPreferences
public List<Preference> listPreferences() { this.logger.finer( "Getting all the preferences." ); WebResource path = this.resource.path( UrlConstants.PREFERENCES ); List<Preference> result = this.wsClient.createBuilder( path ) .accept( MediaType.APPLICATION_JSON ) .get( new GenericType<List<Preference>> () {}); if( result != null ) this.logger.finer( result.size() + " preferences were found on the DM." ); else this.logger.finer( "No preference was found on the DM." ); return result != null ? result : new ArrayList<Preference> (); }
java
public List<Preference> listPreferences() { this.logger.finer( "Getting all the preferences." ); WebResource path = this.resource.path( UrlConstants.PREFERENCES ); List<Preference> result = this.wsClient.createBuilder( path ) .accept( MediaType.APPLICATION_JSON ) .get( new GenericType<List<Preference>> () {}); if( result != null ) this.logger.finer( result.size() + " preferences were found on the DM." ); else this.logger.finer( "No preference was found on the DM." ); return result != null ? result : new ArrayList<Preference> (); }
[ "public", "List", "<", "Preference", ">", "listPreferences", "(", ")", "{", "this", ".", "logger", ".", "finer", "(", "\"Getting all the preferences.\"", ")", ";", "WebResource", "path", "=", "this", ".", "resource", ".", "path", "(", "UrlConstants", ".", "P...
Lists all the preferences.
[ "Lists", "all", "the", "preferences", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-dm-rest-client/src/main/java/net/roboconf/dm/rest/client/delegates/PreferencesWsDelegate.java#L66-L81
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/errors/i18n/TranslationBundle.java
TranslationBundle.resolve
public static String resolve( String lang ) { String result; if( ! LANGUAGES.contains( lang )) result = EN; else result = lang; return result; }
java
public static String resolve( String lang ) { String result; if( ! LANGUAGES.contains( lang )) result = EN; else result = lang; return result; }
[ "public", "static", "String", "resolve", "(", "String", "lang", ")", "{", "String", "result", ";", "if", "(", "!", "LANGUAGES", ".", "contains", "(", "lang", ")", ")", "result", "=", "EN", ";", "else", "result", "=", "lang", ";", "return", "result", ...
Resolves a language to a supported translation. @param lang a string (e.g. "en_EN") @return a supported language
[ "Resolves", "a", "language", "to", "a", "supported", "translation", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/errors/i18n/TranslationBundle.java#L101-L110
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/errors/i18n/TranslationBundle.java
TranslationBundle.loadContent
static Map<String,String> loadContent( String lang ) { Map<String,String> result = new LinkedHashMap<> (); try { InputStream in = TranslationBundle.class.getResourceAsStream( "/" + lang + ".json" ); ByteArrayOutputStream os = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, os ); String content = os.toString( "UTF-8" ); Matcher m = Pattern.compile( ROW_PATTERN ).matcher( content ); while( m.find()) { // Get the value String s = m.group( 2 ); // Replace i18n parameters here (when it makes sense) try { ErrorCode ec = ErrorCode.valueOf( m.group( 1 )); for( int i=0; i<ec.getI18nProperties().length; i++ ) { s = s.replace( "{" + i + "}", ec.getI18nProperties()[ i ]); } } catch( IllegalArgumentException e ) { // nothing } result.put( m.group( 1 ), s ); } } catch( Exception e ) { final Logger logger = Logger.getLogger( TranslationBundle.class.getName()); Utils.logException( logger, e ); } return result; }
java
static Map<String,String> loadContent( String lang ) { Map<String,String> result = new LinkedHashMap<> (); try { InputStream in = TranslationBundle.class.getResourceAsStream( "/" + lang + ".json" ); ByteArrayOutputStream os = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, os ); String content = os.toString( "UTF-8" ); Matcher m = Pattern.compile( ROW_PATTERN ).matcher( content ); while( m.find()) { // Get the value String s = m.group( 2 ); // Replace i18n parameters here (when it makes sense) try { ErrorCode ec = ErrorCode.valueOf( m.group( 1 )); for( int i=0; i<ec.getI18nProperties().length; i++ ) { s = s.replace( "{" + i + "}", ec.getI18nProperties()[ i ]); } } catch( IllegalArgumentException e ) { // nothing } result.put( m.group( 1 ), s ); } } catch( Exception e ) { final Logger logger = Logger.getLogger( TranslationBundle.class.getName()); Utils.logException( logger, e ); } return result; }
[ "static", "Map", "<", "String", ",", "String", ">", "loadContent", "(", "String", "lang", ")", "{", "Map", "<", "String", ",", "String", ">", "result", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "try", "{", "InputStream", "in", "=", "Translation...
Loads content from JSon files. @param lang the language to use @return a non-null map
[ "Loads", "content", "from", "JSon", "files", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/errors/i18n/TranslationBundle.java#L118-L153
train
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2IaasHandler.java
Ec2IaasHandler.parseProperties
static void parseProperties( Map<String, String> targetProperties ) throws TargetException { // Quick check String[] properties = { Ec2Constants.EC2_ENDPOINT, Ec2Constants.EC2_ACCESS_KEY, Ec2Constants.EC2_SECRET_KEY, Ec2Constants.AMI_VM_NODE, Ec2Constants.VM_INSTANCE_TYPE, Ec2Constants.SSH_KEY_NAME, Ec2Constants.SECURITY_GROUP_NAME }; for( String property : properties ) { if( StringUtils.isBlank( targetProperties.get( property ))) throw new TargetException( "The value for " + property + " cannot be null or empty." ); } }
java
static void parseProperties( Map<String, String> targetProperties ) throws TargetException { // Quick check String[] properties = { Ec2Constants.EC2_ENDPOINT, Ec2Constants.EC2_ACCESS_KEY, Ec2Constants.EC2_SECRET_KEY, Ec2Constants.AMI_VM_NODE, Ec2Constants.VM_INSTANCE_TYPE, Ec2Constants.SSH_KEY_NAME, Ec2Constants.SECURITY_GROUP_NAME }; for( String property : properties ) { if( StringUtils.isBlank( targetProperties.get( property ))) throw new TargetException( "The value for " + property + " cannot be null or empty." ); } }
[ "static", "void", "parseProperties", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ")", "throws", "TargetException", "{", "// Quick check", "String", "[", "]", "properties", "=", "{", "Ec2Constants", ".", "EC2_ENDPOINT", ",", "Ec2Constants", ...
Parses the properties and saves them in a Java bean. @param targetProperties the IaaS properties @throws TargetException
[ "Parses", "the", "properties", "and", "saves", "them", "in", "a", "Java", "bean", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2IaasHandler.java#L242-L259
train
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2IaasHandler.java
Ec2IaasHandler.createEc2Client
public static AmazonEC2 createEc2Client( Map<String,String> targetProperties ) throws TargetException { parseProperties( targetProperties ); // Configure the IaaS client AWSCredentials credentials = new BasicAWSCredentials( targetProperties.get(Ec2Constants.EC2_ACCESS_KEY), targetProperties.get(Ec2Constants.EC2_SECRET_KEY)); AmazonEC2 ec2 = new AmazonEC2Client( credentials ); ec2.setEndpoint( targetProperties.get(Ec2Constants.EC2_ENDPOINT )); return ec2; }
java
public static AmazonEC2 createEc2Client( Map<String,String> targetProperties ) throws TargetException { parseProperties( targetProperties ); // Configure the IaaS client AWSCredentials credentials = new BasicAWSCredentials( targetProperties.get(Ec2Constants.EC2_ACCESS_KEY), targetProperties.get(Ec2Constants.EC2_SECRET_KEY)); AmazonEC2 ec2 = new AmazonEC2Client( credentials ); ec2.setEndpoint( targetProperties.get(Ec2Constants.EC2_ENDPOINT )); return ec2; }
[ "public", "static", "AmazonEC2", "createEc2Client", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ")", "throws", "TargetException", "{", "parseProperties", "(", "targetProperties", ")", ";", "// Configure the IaaS client", "AWSCredentials", "credent...
Creates a client for EC2. @param targetProperties the target properties (not null) @return a non-null client @throws TargetException if properties are invalid
[ "Creates", "a", "client", "for", "EC2", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2IaasHandler.java#L268-L281
train
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2IaasHandler.java
Ec2IaasHandler.prepareEC2RequestNode
private RunInstancesRequest prepareEC2RequestNode( Map<String,String> targetProperties, String userData ) throws UnsupportedEncodingException { RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); String flavor = targetProperties.get(Ec2Constants.VM_INSTANCE_TYPE); if( Utils.isEmptyOrWhitespaces( flavor )) flavor = "t1.micro"; runInstancesRequest.setInstanceType( flavor ); runInstancesRequest.setImageId( targetProperties.get( Ec2Constants.AMI_VM_NODE )); runInstancesRequest.setMinCount( 1 ); runInstancesRequest.setMaxCount( 1 ); runInstancesRequest.setKeyName( targetProperties.get(Ec2Constants.SSH_KEY_NAME)); String secGroup = targetProperties.get(Ec2Constants.SECURITY_GROUP_NAME); if( Utils.isEmptyOrWhitespaces(secGroup)) secGroup = "default"; runInstancesRequest.setSecurityGroups(Collections.singletonList(secGroup)); String availabilityZone = targetProperties.get(Ec2Constants.AVAILABILITY_ZONE); if(! Utils.isEmptyOrWhitespaces(availabilityZone)) runInstancesRequest.setPlacement(new Placement(availabilityZone)); // The following part enables to transmit data to the VM. // When the VM is up, it will be able to read this data. String encodedUserData = new String( Base64.encodeBase64( userData.getBytes( StandardCharsets.UTF_8 )), "UTF-8" ); runInstancesRequest.setUserData( encodedUserData ); return runInstancesRequest; }
java
private RunInstancesRequest prepareEC2RequestNode( Map<String,String> targetProperties, String userData ) throws UnsupportedEncodingException { RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); String flavor = targetProperties.get(Ec2Constants.VM_INSTANCE_TYPE); if( Utils.isEmptyOrWhitespaces( flavor )) flavor = "t1.micro"; runInstancesRequest.setInstanceType( flavor ); runInstancesRequest.setImageId( targetProperties.get( Ec2Constants.AMI_VM_NODE )); runInstancesRequest.setMinCount( 1 ); runInstancesRequest.setMaxCount( 1 ); runInstancesRequest.setKeyName( targetProperties.get(Ec2Constants.SSH_KEY_NAME)); String secGroup = targetProperties.get(Ec2Constants.SECURITY_GROUP_NAME); if( Utils.isEmptyOrWhitespaces(secGroup)) secGroup = "default"; runInstancesRequest.setSecurityGroups(Collections.singletonList(secGroup)); String availabilityZone = targetProperties.get(Ec2Constants.AVAILABILITY_ZONE); if(! Utils.isEmptyOrWhitespaces(availabilityZone)) runInstancesRequest.setPlacement(new Placement(availabilityZone)); // The following part enables to transmit data to the VM. // When the VM is up, it will be able to read this data. String encodedUserData = new String( Base64.encodeBase64( userData.getBytes( StandardCharsets.UTF_8 )), "UTF-8" ); runInstancesRequest.setUserData( encodedUserData ); return runInstancesRequest; }
[ "private", "RunInstancesRequest", "prepareEC2RequestNode", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ",", "String", "userData", ")", "throws", "UnsupportedEncodingException", "{", "RunInstancesRequest", "runInstancesRequest", "=", "new", "RunInsta...
Prepares the request. @param targetProperties the target properties @param userData the user data to pass @return a request @throws UnsupportedEncodingException
[ "Prepares", "the", "request", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2IaasHandler.java#L291-L322
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/ApplicationTemplateMngrImpl.java
ApplicationTemplateMngrImpl.registerTargets
private Set<String> registerTargets( ApplicationTemplate tpl ) throws IOException, UnauthorizedActionException { // Find all the properties files and register them IOException conflictException = null; Set<String> newTargetIds = new HashSet<> (); Map<Component,Set<String>> componentToTargetIds = new HashMap<> (); componentLoop: for( Map.Entry<Component,File> entry : ResourceUtils.findScopedInstancesDirectories( tpl ).entrySet()) { // Register the targets String defaultTargetId = null; Set<String> targetIds = new HashSet<> (); componentToTargetIds.put( entry.getKey(), targetIds ); for( File f : Utils.listDirectFiles( entry.getValue(), Constants.FILE_EXT_PROPERTIES )) { this.logger.fine( "Registering target " + f.getName() + " from component " + entry.getKey() + " in application template " + tpl ); String targetId; try { targetId = this.targetsMngr.createTarget( f, tpl ); } catch( IOException e ) { conflictException = e; break componentLoop; } this.targetsMngr.addHint( targetId, tpl ); targetIds.add( targetId ); newTargetIds.add( targetId ); if( Constants.TARGET_PROPERTIES_FILE_NAME.equalsIgnoreCase( f.getName())) defaultTargetId = targetId; } // If there is a "target.properties" file, forget the other properties. // They were registered but we will not use them by default. if( defaultTargetId != null ) { targetIds.clear(); targetIds.add( defaultTargetId ); } } // Handle conflicts during registration if( conflictException != null ) { this.logger.fine( "A conflict was found while registering " ); unregisterTargets( newTargetIds ); throw conflictException; } // Associate them with components. for( Map.Entry<Component,Set<String>> entry : componentToTargetIds.entrySet()) { String key = "@" + entry.getKey().getName(); // More than one target for a component? // => Do not register anything. if( entry.getValue().size() == 1 ) this.targetsMngr.associateTargetWith( entry.getValue().iterator().next(), tpl, key ); } return newTargetIds; }
java
private Set<String> registerTargets( ApplicationTemplate tpl ) throws IOException, UnauthorizedActionException { // Find all the properties files and register them IOException conflictException = null; Set<String> newTargetIds = new HashSet<> (); Map<Component,Set<String>> componentToTargetIds = new HashMap<> (); componentLoop: for( Map.Entry<Component,File> entry : ResourceUtils.findScopedInstancesDirectories( tpl ).entrySet()) { // Register the targets String defaultTargetId = null; Set<String> targetIds = new HashSet<> (); componentToTargetIds.put( entry.getKey(), targetIds ); for( File f : Utils.listDirectFiles( entry.getValue(), Constants.FILE_EXT_PROPERTIES )) { this.logger.fine( "Registering target " + f.getName() + " from component " + entry.getKey() + " in application template " + tpl ); String targetId; try { targetId = this.targetsMngr.createTarget( f, tpl ); } catch( IOException e ) { conflictException = e; break componentLoop; } this.targetsMngr.addHint( targetId, tpl ); targetIds.add( targetId ); newTargetIds.add( targetId ); if( Constants.TARGET_PROPERTIES_FILE_NAME.equalsIgnoreCase( f.getName())) defaultTargetId = targetId; } // If there is a "target.properties" file, forget the other properties. // They were registered but we will not use them by default. if( defaultTargetId != null ) { targetIds.clear(); targetIds.add( defaultTargetId ); } } // Handle conflicts during registration if( conflictException != null ) { this.logger.fine( "A conflict was found while registering " ); unregisterTargets( newTargetIds ); throw conflictException; } // Associate them with components. for( Map.Entry<Component,Set<String>> entry : componentToTargetIds.entrySet()) { String key = "@" + entry.getKey().getName(); // More than one target for a component? // => Do not register anything. if( entry.getValue().size() == 1 ) this.targetsMngr.associateTargetWith( entry.getValue().iterator().next(), tpl, key ); } return newTargetIds; }
[ "private", "Set", "<", "String", ">", "registerTargets", "(", "ApplicationTemplate", "tpl", ")", "throws", "IOException", ",", "UnauthorizedActionException", "{", "// Find all the properties files and register them", "IOException", "conflictException", "=", "null", ";", "Se...
Registers the targets available in this template. @param tpl a template @return a set of target IDs, created from this template @throws IOException @throws UnauthorizedActionException
[ "Registers", "the", "targets", "available", "in", "this", "template", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/ApplicationTemplateMngrImpl.java#L250-L310
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/ApplicationTemplateMngrImpl.java
ApplicationTemplateMngrImpl.unregisterTargets
private void unregisterTargets( Set<String> newTargetIds ) { for( String targetId : newTargetIds ) { try { this.targetsMngr.deleteTarget( targetId ); } catch( Exception e ) { this.logger.severe( "A target ID that has just been registered could not be created. That's weird." ); Utils.logException( this.logger, e ); } } }
java
private void unregisterTargets( Set<String> newTargetIds ) { for( String targetId : newTargetIds ) { try { this.targetsMngr.deleteTarget( targetId ); } catch( Exception e ) { this.logger.severe( "A target ID that has just been registered could not be created. That's weird." ); Utils.logException( this.logger, e ); } } }
[ "private", "void", "unregisterTargets", "(", "Set", "<", "String", ">", "newTargetIds", ")", "{", "for", "(", "String", "targetId", ":", "newTargetIds", ")", "{", "try", "{", "this", ".", "targetsMngr", ".", "deleteTarget", "(", "targetId", ")", ";", "}", ...
Unregisters targets. @param newTargetIds a non-null set of target IDs
[ "Unregisters", "targets", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/ApplicationTemplateMngrImpl.java#L317-L328
train
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/beans/InstanceContext.java
InstanceContext.parse
public static InstanceContext parse( String s ) { String name = null, qualifier = null, instancePathOrComponentName = null; if( s != null ) { Matcher m = Pattern.compile( "(.*)::(.*)::(.*)" ).matcher( s ); if( m.matches()) { name = m.group( 1 ).equals( "null" ) ? null : m.group( 1 ); qualifier = m.group( 2 ).equals( "null" ) ? null : m.group( 2 ); instancePathOrComponentName = m.group( 3 ).equals( "null" ) ? null : m.group( 3 ); } } return new InstanceContext( name, qualifier, instancePathOrComponentName ); }
java
public static InstanceContext parse( String s ) { String name = null, qualifier = null, instancePathOrComponentName = null; if( s != null ) { Matcher m = Pattern.compile( "(.*)::(.*)::(.*)" ).matcher( s ); if( m.matches()) { name = m.group( 1 ).equals( "null" ) ? null : m.group( 1 ); qualifier = m.group( 2 ).equals( "null" ) ? null : m.group( 2 ); instancePathOrComponentName = m.group( 3 ).equals( "null" ) ? null : m.group( 3 ); } } return new InstanceContext( name, qualifier, instancePathOrComponentName ); }
[ "public", "static", "InstanceContext", "parse", "(", "String", "s", ")", "{", "String", "name", "=", "null", ",", "qualifier", "=", "null", ",", "instancePathOrComponentName", "=", "null", ";", "if", "(", "s", "!=", "null", ")", "{", "Matcher", "m", "=",...
Parses a string to resolve a target mapping key. @param s a string (can be null) @return a target mapping key (never null)
[ "Parses", "a", "string", "to", "resolve", "a", "target", "mapping", "key", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/api/impl/beans/InstanceContext.java#L104-L117
train
roboconf/roboconf-platform
core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/utils/MessagingUtils.java
MessagingUtils.buildTopicNameForAgent
public static String buildTopicNameForAgent( Instance instance ) { Instance scopedInstance = InstanceHelpers.findScopedInstance( instance ); return buildTopicNameForAgent( InstanceHelpers.computeInstancePath( scopedInstance )); }
java
public static String buildTopicNameForAgent( Instance instance ) { Instance scopedInstance = InstanceHelpers.findScopedInstance( instance ); return buildTopicNameForAgent( InstanceHelpers.computeInstancePath( scopedInstance )); }
[ "public", "static", "String", "buildTopicNameForAgent", "(", "Instance", "instance", ")", "{", "Instance", "scopedInstance", "=", "InstanceHelpers", ".", "findScopedInstance", "(", "instance", ")", ";", "return", "buildTopicNameForAgent", "(", "InstanceHelpers", ".", ...
Builds the default topic name for an agent. @param instance an instance managed by the agent @return a non-null string
[ "Builds", "the", "default", "topic", "name", "for", "an", "agent", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/utils/MessagingUtils.java#L51-L54
train
roboconf/roboconf-platform
core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/utils/MessagingUtils.java
MessagingUtils.escapeInstancePath
public static String escapeInstancePath( String instancePath ) { String result; if( Utils.isEmptyOrWhitespaces( instancePath )) result = ""; else result = instancePath.replaceFirst( "^/*", "" ).replaceFirst( "/*$", "" ).replaceAll( "/+", "." ); return result; }
java
public static String escapeInstancePath( String instancePath ) { String result; if( Utils.isEmptyOrWhitespaces( instancePath )) result = ""; else result = instancePath.replaceFirst( "^/*", "" ).replaceFirst( "/*$", "" ).replaceAll( "/+", "." ); return result; }
[ "public", "static", "String", "escapeInstancePath", "(", "String", "instancePath", ")", "{", "String", "result", ";", "if", "(", "Utils", ".", "isEmptyOrWhitespaces", "(", "instancePath", ")", ")", "result", "=", "\"\"", ";", "else", "result", "=", "instancePa...
Removes unnecessary slashes and transforms the others into dots. @param instancePath an instance path @return a non-null string
[ "Removes", "unnecessary", "slashes", "and", "transforms", "the", "others", "into", "dots", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/utils/MessagingUtils.java#L72-L81
train
roboconf/roboconf-platform
core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/utils/MessagingUtils.java
MessagingUtils.buildId
public static String buildId( RecipientKind ownerKind, String domain, String applicationName, String scopedInstancePath ) { StringBuilder sb = new StringBuilder(); sb.append( "[ " ); sb.append( domain ); sb.append( " ] " ); if( ownerKind == RecipientKind.DM ) { sb.append( "DM" ); } else { sb.append( scopedInstancePath ); sb.append( " @ " ); sb.append( applicationName ); } return sb.toString(); }
java
public static String buildId( RecipientKind ownerKind, String domain, String applicationName, String scopedInstancePath ) { StringBuilder sb = new StringBuilder(); sb.append( "[ " ); sb.append( domain ); sb.append( " ] " ); if( ownerKind == RecipientKind.DM ) { sb.append( "DM" ); } else { sb.append( scopedInstancePath ); sb.append( " @ " ); sb.append( applicationName ); } return sb.toString(); }
[ "public", "static", "String", "buildId", "(", "RecipientKind", "ownerKind", ",", "String", "domain", ",", "String", "applicationName", ",", "String", "scopedInstancePath", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", ...
Builds a string identifying a messaging client. @param ownerKind {@link RecipientKind#DM} or {@link RecipientKind#AGENTS} @param domain the domain @param applicationName the application name (only makes sense for agents) @param scopedInstancePath the scoped instance path (only makes sense for agents) @return a non-null string
[ "Builds", "a", "string", "identifying", "a", "messaging", "client", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-messaging-api/src/main/java/net/roboconf/messaging/api/utils/MessagingUtils.java#L92-L112
train
roboconf/roboconf-platform
core/roboconf-target-iaas-openstack/src/main/java/net/roboconf/target/openstack/internal/OpenstackMachineConfigurator.java
OpenstackMachineConfigurator.checkVmIsOnline
private boolean checkVmIsOnline() { String zoneName = OpenstackIaasHandler.findZoneName( this.novaApi, this.targetProperties ); Server server = this.novaApi.getServerApiForZone( zoneName ).get(this.machineId); return Status.ACTIVE.equals(server.getStatus()); }
java
private boolean checkVmIsOnline() { String zoneName = OpenstackIaasHandler.findZoneName( this.novaApi, this.targetProperties ); Server server = this.novaApi.getServerApiForZone( zoneName ).get(this.machineId); return Status.ACTIVE.equals(server.getStatus()); }
[ "private", "boolean", "checkVmIsOnline", "(", ")", "{", "String", "zoneName", "=", "OpenstackIaasHandler", ".", "findZoneName", "(", "this", ".", "novaApi", ",", "this", ".", "targetProperties", ")", ";", "Server", "server", "=", "this", ".", "novaApi", ".", ...
Checks whether a VM is created. @return true if it is online, false otherwise
[ "Checks", "whether", "a", "VM", "is", "created", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-openstack/src/main/java/net/roboconf/target/openstack/internal/OpenstackMachineConfigurator.java#L178-L183
train
roboconf/roboconf-platform
core/roboconf-target-iaas-openstack/src/main/java/net/roboconf/target/openstack/internal/OpenstackMachineConfigurator.java
OpenstackMachineConfigurator.prepareObjectStorage
public boolean prepareObjectStorage() throws TargetException { String domains = this.targetProperties.get( OBJ_STORAGE_DOMAINS ); if( ! Utils.isEmptyOrWhitespaces( domains )) { // Get the Swift API String zoneName = OpenstackIaasHandler.findZoneName( this.novaApi, this.targetProperties ); SwiftApi swiftApi = OpenstackIaasHandler.swiftApi( this.targetProperties ); try { // List domains List<String> existingDomainNames = new ArrayList<> (); for( Container container : swiftApi.getContainerApi( zoneName ).list()) { existingDomainNames.add( container.getName()); } // Create missing domains List<String> domainsToCreate = Utils.splitNicely( domains, "," ); domainsToCreate.removeAll( existingDomainNames ); for( String domainName : domainsToCreate ) { this.logger.info( "Creating container " + domainName + " (object storage)..." ); swiftApi.getContainerApi( zoneName ).create( domainName ); } } catch( Exception e ) { throw new TargetException( e ); } finally { // Release the API try { swiftApi.close(); } catch( IOException e ) { throw new TargetException( e ); } } } return true; }
java
public boolean prepareObjectStorage() throws TargetException { String domains = this.targetProperties.get( OBJ_STORAGE_DOMAINS ); if( ! Utils.isEmptyOrWhitespaces( domains )) { // Get the Swift API String zoneName = OpenstackIaasHandler.findZoneName( this.novaApi, this.targetProperties ); SwiftApi swiftApi = OpenstackIaasHandler.swiftApi( this.targetProperties ); try { // List domains List<String> existingDomainNames = new ArrayList<> (); for( Container container : swiftApi.getContainerApi( zoneName ).list()) { existingDomainNames.add( container.getName()); } // Create missing domains List<String> domainsToCreate = Utils.splitNicely( domains, "," ); domainsToCreate.removeAll( existingDomainNames ); for( String domainName : domainsToCreate ) { this.logger.info( "Creating container " + domainName + " (object storage)..." ); swiftApi.getContainerApi( zoneName ).create( domainName ); } } catch( Exception e ) { throw new TargetException( e ); } finally { // Release the API try { swiftApi.close(); } catch( IOException e ) { throw new TargetException( e ); } } } return true; }
[ "public", "boolean", "prepareObjectStorage", "(", ")", "throws", "TargetException", "{", "String", "domains", "=", "this", ".", "targetProperties", ".", "get", "(", "OBJ_STORAGE_DOMAINS", ")", ";", "if", "(", "!", "Utils", ".", "isEmptyOrWhitespaces", "(", "doma...
Configures the object storage. @return true if the configuration is over @throws TargetException
[ "Configures", "the", "object", "storage", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-openstack/src/main/java/net/roboconf/target/openstack/internal/OpenstackMachineConfigurator.java#L244-L283
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/internal/dsl/parsing/FileDefinitionParser.java
FileDefinitionParser.splitFromInlineComment
String[] splitFromInlineComment( String line ) { String[] result = new String[] { line, "" }; int index = line.indexOf( ParsingConstants.COMMENT_DELIMITER ); if( index >= 0 ) { result[ 0 ] = line.substring( 0, index ); if( ! this.ignoreComments ) { // Find extra spaces before the in-line comment and put them in the comment Matcher m = Pattern.compile( "(\\s+)$" ).matcher( result[ 0 ]); String prefix = ""; if( m.find()) prefix = m.group( 1 ); result[ 1 ] = prefix + line.substring( index ); } result[ 0 ] = result[ 0 ].trim(); } return result; }
java
String[] splitFromInlineComment( String line ) { String[] result = new String[] { line, "" }; int index = line.indexOf( ParsingConstants.COMMENT_DELIMITER ); if( index >= 0 ) { result[ 0 ] = line.substring( 0, index ); if( ! this.ignoreComments ) { // Find extra spaces before the in-line comment and put them in the comment Matcher m = Pattern.compile( "(\\s+)$" ).matcher( result[ 0 ]); String prefix = ""; if( m.find()) prefix = m.group( 1 ); result[ 1 ] = prefix + line.substring( index ); } result[ 0 ] = result[ 0 ].trim(); } return result; }
[ "String", "[", "]", "splitFromInlineComment", "(", "String", "line", ")", "{", "String", "[", "]", "result", "=", "new", "String", "[", "]", "{", "line", ",", "\"\"", "}", ";", "int", "index", "=", "line", ".", "indexOf", "(", "ParsingConstants", ".", ...
Splits the line from the comment delimiter. @param line a string (not null) @return an array of 2 strings <p> Index 0: the line without the in-line comment. Never null.<br> Index 1: the in-line comment (if not null, it starts with a '#' symbol). </p>
[ "Splits", "the", "line", "from", "the", "comment", "delimiter", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/internal/dsl/parsing/FileDefinitionParser.java#L334-L354
train
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/internal/dsl/parsing/FileDefinitionParser.java
FileDefinitionParser.fillIn
private void fillIn() throws IOException { BufferedReader br = null; InputStream in = null; try { in = new FileInputStream( this.definitionFile.getEditedFile()); br = new BufferedReader( new InputStreamReader( in, StandardCharsets.UTF_8 )); String line; while(( line = nextLine( br )) != null ) { int code = recognizeBlankLine( line, this.definitionFile.getBlocks()); if( code == P_CODE_YES ) continue; code = recognizeComment( line, this.definitionFile.getBlocks()); if( code == P_CODE_YES ) continue; code = recognizeImport( line ); if( code == P_CODE_CANCEL ) break; else if( code == P_CODE_YES ) continue; code = recognizeFacet( line, br ); if( code == P_CODE_CANCEL ) break; else if( code == P_CODE_YES ) continue; code = recognizeInstanceOf( line, br, null ); if( code == P_CODE_CANCEL ) break; else if( code == P_CODE_YES ) continue; // "recognizeComponent" is the last attempt to identify the line. code = recognizeComponent( line, br ); // So, eventually, we add the line as an unknown block. if( code != P_CODE_YES ) this.definitionFile.getBlocks().add( new BlockUnknown( this.definitionFile, line )); // Deal with the error codes. // Cancel: break the loop. // No: try to process the next line. if( code == P_CODE_CANCEL ) break; if( code == P_CODE_NO ) addModelError( ErrorCode.P_UNRECOGNIZED_BLOCK ); } if( line == null && this.lastLineEndedWithLineBreak ) this.definitionFile.getBlocks().add( new BlockBlank( this.definitionFile, "" )); } finally { Utils.closeQuietly( br ); Utils.closeQuietly( in ); } }
java
private void fillIn() throws IOException { BufferedReader br = null; InputStream in = null; try { in = new FileInputStream( this.definitionFile.getEditedFile()); br = new BufferedReader( new InputStreamReader( in, StandardCharsets.UTF_8 )); String line; while(( line = nextLine( br )) != null ) { int code = recognizeBlankLine( line, this.definitionFile.getBlocks()); if( code == P_CODE_YES ) continue; code = recognizeComment( line, this.definitionFile.getBlocks()); if( code == P_CODE_YES ) continue; code = recognizeImport( line ); if( code == P_CODE_CANCEL ) break; else if( code == P_CODE_YES ) continue; code = recognizeFacet( line, br ); if( code == P_CODE_CANCEL ) break; else if( code == P_CODE_YES ) continue; code = recognizeInstanceOf( line, br, null ); if( code == P_CODE_CANCEL ) break; else if( code == P_CODE_YES ) continue; // "recognizeComponent" is the last attempt to identify the line. code = recognizeComponent( line, br ); // So, eventually, we add the line as an unknown block. if( code != P_CODE_YES ) this.definitionFile.getBlocks().add( new BlockUnknown( this.definitionFile, line )); // Deal with the error codes. // Cancel: break the loop. // No: try to process the next line. if( code == P_CODE_CANCEL ) break; if( code == P_CODE_NO ) addModelError( ErrorCode.P_UNRECOGNIZED_BLOCK ); } if( line == null && this.lastLineEndedWithLineBreak ) this.definitionFile.getBlocks().add( new BlockBlank( this.definitionFile, "" )); } finally { Utils.closeQuietly( br ); Utils.closeQuietly( in ); } }
[ "private", "void", "fillIn", "(", ")", "throws", "IOException", "{", "BufferedReader", "br", "=", "null", ";", "InputStream", "in", "=", "null", ";", "try", "{", "in", "=", "new", "FileInputStream", "(", "this", ".", "definitionFile", ".", "getEditedFile", ...
Parses the file and fills-in the resulting structure. @throws IOException
[ "Parses", "the", "file", "and", "fills", "-", "in", "the", "resulting", "structure", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/internal/dsl/parsing/FileDefinitionParser.java#L574-L636
train
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/textactions/CommentAction.java
CommentAction.commentLine
public static String commentLine( String line ) { String result = line; if( ! Utils.isEmptyOrWhitespaces( line ) && ! line.trim().startsWith( ParsingConstants.COMMENT_DELIMITER )) result = ParsingConstants.COMMENT_DELIMITER + line; return result; }
java
public static String commentLine( String line ) { String result = line; if( ! Utils.isEmptyOrWhitespaces( line ) && ! line.trim().startsWith( ParsingConstants.COMMENT_DELIMITER )) result = ParsingConstants.COMMENT_DELIMITER + line; return result; }
[ "public", "static", "String", "commentLine", "(", "String", "line", ")", "{", "String", "result", "=", "line", ";", "if", "(", "!", "Utils", ".", "isEmptyOrWhitespaces", "(", "line", ")", "&&", "!", "line", ".", "trim", "(", ")", ".", "startsWith", "("...
Comments a line. @param line a non-null line @return a non-null line
[ "Comments", "a", "line", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/textactions/CommentAction.java#L47-L55
train
roboconf/roboconf-platform
core/roboconf-dm-rest-services/src/main/java/net/roboconf/dm/rest/services/internal/filters/AuthenticationFilter.java
AuthenticationFilter.cleanPath
static String cleanPath( String path ) { return path .replaceFirst( "^" + ServletRegistrationComponent.REST_CONTEXT + "/", "/" ) .replaceFirst( "^" + ServletRegistrationComponent.WEBSOCKET_CONTEXT + "/", "/" ) .replaceFirst( "\\?.*", "" ); }
java
static String cleanPath( String path ) { return path .replaceFirst( "^" + ServletRegistrationComponent.REST_CONTEXT + "/", "/" ) .replaceFirst( "^" + ServletRegistrationComponent.WEBSOCKET_CONTEXT + "/", "/" ) .replaceFirst( "\\?.*", "" ); }
[ "static", "String", "cleanPath", "(", "String", "path", ")", "{", "return", "path", ".", "replaceFirst", "(", "\"^\"", "+", "ServletRegistrationComponent", ".", "REST_CONTEXT", "+", "\"/\"", ",", "\"/\"", ")", ".", "replaceFirst", "(", "\"^\"", "+", "ServletRe...
Cleans the path by removing the servlet paths and URL parameters. @param path a non-null path @return a non-null path
[ "Cleans", "the", "path", "by", "removing", "the", "servlet", "paths", "and", "URL", "parameters", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-rest-services/src/main/java/net/roboconf/dm/rest/services/internal/filters/AuthenticationFilter.java#L260-L266
train
roboconf/roboconf-platform
core/roboconf-agent/src/main/java/net/roboconf/agent/internal/PluginProxy.java
PluginProxy.resetAllCounters
public static synchronized void resetAllCounters() { initializeCount.set(0); deployCount.set(0); undeployCount.set(0); startCount.set(0); stopCount.set(0); updateCount.set(0); errorCount.set( 0 ); }
java
public static synchronized void resetAllCounters() { initializeCount.set(0); deployCount.set(0); undeployCount.set(0); startCount.set(0); stopCount.set(0); updateCount.set(0); errorCount.set( 0 ); }
[ "public", "static", "synchronized", "void", "resetAllCounters", "(", ")", "{", "initializeCount", ".", "set", "(", "0", ")", ";", "deployCount", ".", "set", "(", "0", ")", ";", "undeployCount", ".", "set", "(", "0", ")", ";", "startCount", ".", "set", ...
Resets all counters.
[ "Resets", "all", "counters", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-agent/src/main/java/net/roboconf/agent/internal/PluginProxy.java#L63-L71
train
roboconf/roboconf-platform
core/roboconf-agent-monitoring/src/main/java/net/roboconf/agent/monitoring/internal/nagios/LiveStatusClient.java
LiveStatusClient.queryLivestatus
public String queryLivestatus( String nagiosQuery ) throws UnknownHostException, IOException { Socket liveStatusSocket = null; try { this.logger.fine( "About to open a connection through Live Status..." ); liveStatusSocket = new Socket( this.host, this.port ); this.logger.fine( "A connection was established through Live Status." ); Writer osw = new OutputStreamWriter( liveStatusSocket.getOutputStream(), StandardCharsets.UTF_8 ); PrintWriter printer = new PrintWriter( osw, false ); printer.print( nagiosQuery ); printer.flush(); liveStatusSocket.shutdownOutput(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Utils.copyStreamSafely( liveStatusSocket.getInputStream(), os ); String result = os.toString( "UTF-8" ); result = format( nagiosQuery, result ); return result; } finally { if( liveStatusSocket != null ) liveStatusSocket.close(); this.logger.fine( "The Live Status connection was closed." ); } }
java
public String queryLivestatus( String nagiosQuery ) throws UnknownHostException, IOException { Socket liveStatusSocket = null; try { this.logger.fine( "About to open a connection through Live Status..." ); liveStatusSocket = new Socket( this.host, this.port ); this.logger.fine( "A connection was established through Live Status." ); Writer osw = new OutputStreamWriter( liveStatusSocket.getOutputStream(), StandardCharsets.UTF_8 ); PrintWriter printer = new PrintWriter( osw, false ); printer.print( nagiosQuery ); printer.flush(); liveStatusSocket.shutdownOutput(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Utils.copyStreamSafely( liveStatusSocket.getInputStream(), os ); String result = os.toString( "UTF-8" ); result = format( nagiosQuery, result ); return result; } finally { if( liveStatusSocket != null ) liveStatusSocket.close(); this.logger.fine( "The Live Status connection was closed." ); } }
[ "public", "String", "queryLivestatus", "(", "String", "nagiosQuery", ")", "throws", "UnknownHostException", ",", "IOException", "{", "Socket", "liveStatusSocket", "=", "null", ";", "try", "{", "this", ".", "logger", ".", "fine", "(", "\"About to open a connection th...
Queries a live status server. @param nagiosQuery the query to pass through a socket (not null) @return the response @throws UnknownHostException @throws IOException
[ "Queries", "a", "live", "status", "server", "." ]
add54eead479effb138d0ff53a2d637902b82702
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-agent-monitoring/src/main/java/net/roboconf/agent/monitoring/internal/nagios/LiveStatusClient.java#L73-L101
train