index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/DockerTransitionParameters.java
package ai.lucidtech.las.sdk; import java.util.Map; import org.json.JSONObject; public class DockerTransitionParameters extends TransitionParameters { private String imageUrl; private String secretId; private Integer memory; private Integer cpu; private String[] environmentSecrets; private Map<String, String> environment; public DockerTransitionParameters setImageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public DockerTransitionParameters setSecretId(String secretId) { this.secretId = secretId; return this; } public DockerTransitionParameters setMemory(Integer memory) { this.memory = memory; return this; } public DockerTransitionParameters setCpu(Integer cpu) { this.cpu = cpu; return this; } public DockerTransitionParameters setEnvironmentSecrets(String[] environmentSecrets) { this.environmentSecrets = environmentSecrets; return this; } public DockerTransitionParameters setEnvironment(Map<String, String> environment) { this.environment = environment; return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "imageUrl", this.imageUrl); this.addOption(body, "secretId", this.secretId); this.addOption(body, "memory", this.memory); this.addOption(body, "cpu", this.cpu); this.addOption(body, "environmentSecrets", this.environmentSecrets); this.addOption(body, "environment", this.environment); return body; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/Field.java
package ai.lucidtech.las.sdk; import java.util.ArrayList; import java.util.Map; import org.json.JSONObject; public class Field extends Options { public String name; private FieldType fieldType; private Integer maxLength; private NullableString description = new NullableString(); public Field(String name, FieldType fieldType, Integer maxLength) { this.name = name; this.fieldType = fieldType; this.maxLength = maxLength; } public Field setName(String name) { this.name = name; return this; } public Field setFieldType(FieldType fieldType) { this.fieldType = fieldType; return this; } public Field setMaxLength(Integer maxLength) { this.maxLength = maxLength; return this; } public Field setDescription(String description) { this.description.setValue(description); return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "type", this.fieldType.value); this.addOption(body, "maxLength", this.maxLength); this.addOption(body, "description", this.description); return body; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/FieldConfig.java
package ai.lucidtech.las.sdk; import java.util.ArrayList; import org.json.JSONObject; public class FieldConfig extends Options { private ArrayList<Field> fields = new ArrayList<Field>(); public FieldConfig addField(Field field) { this.fields.add(field); return this; } public JSONObject addOptions(JSONObject body) { for (Field field : this.fields) { this.addOption(body, field.name, field); } return body; } public JSONObject toJson() { JSONObject body = new JSONObject(); for (Field field : this.fields) { this.addOption(body, field.name, field); } return body; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/FieldType.java
package ai.lucidtech.las.sdk; public enum FieldType { DATE("date"), AMOUNT("amount"), NUMBER("number"), LETTER("letter"), PHONE("phone"), ALPHANUM("alphanum"), ALPHANUMEXT("alphanumext"), ALL("all"); public final String value; FieldType(String value) { this.value = value; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ImageQuality.java
package ai.lucidtech.las.sdk; public enum ImageQuality { LOW("LOW"), HIGH("HIGH"); public final String value; ImageQuality(String value) { this.value = value; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListAppClientsOptions.java
package ai.lucidtech.las.sdk; public class ListAppClientsOptions extends ListResourcesOptions<ListAppClientsOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListAssetsOptions.java
package ai.lucidtech.las.sdk; public class ListAssetsOptions extends ListResourcesOptions<ListAssetsOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListDocumentsOptions.java
package ai.lucidtech.las.sdk; import org.apache.http.NameValuePair; import java.util.ArrayList; import java.util.List; public class ListDocumentsOptions extends ListResourcesOptions<ListDocumentsOptions> { private String datasetId; private String consentId; public ListDocumentsOptions setConsentId(String consentId) { this.consentId = consentId; return this; } public ListDocumentsOptions setDatasetId(String datasetId) { this.datasetId = datasetId; return this; } public List<NameValuePair> addOptions(List<NameValuePair> parameters) { this.addOption(parameters, "datasetId", this.datasetId); this.addOption(parameters, "consentId", this.consentId); return super.addOptions(parameters); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListLogsOptions.java
package ai.lucidtech.las.sdk; import org.apache.http.NameValuePair; import java.util.ArrayList; import java.util.List; public class ListLogsOptions extends ListResourcesOptions<ListLogsOptions> { private String transitionId; private String transitionExecutionId; private String workflowId; private String workflowExecutionId; public ListLogsOptions setTransitionId(String transitionId) { this.transitionId = transitionId; return this; } public ListLogsOptions setTransitionExecutionId(String transitionExecutionId) { this.transitionExecutionId = transitionExecutionId; return this; } public ListLogsOptions setWorkflowId(String workflowId) { this.workflowId = workflowId; return this; } public ListLogsOptions setWorkflowExecutionId(String workflowExecutionId) { this.workflowExecutionId = workflowExecutionId; return this; } public List<NameValuePair> addOptions(List<NameValuePair> parameters) { this.addOption(parameters, "transitionId", this.transitionId); this.addOption(parameters, "transitionExecutionId", this.transitionExecutionId); this.addOption(parameters, "workflowId", this.workflowId); this.addOption(parameters, "workflowExecutionId", this.workflowExecutionId); return super.addOptions(parameters); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListModelsOptions.java
package ai.lucidtech.las.sdk; public class ListModelsOptions extends ListResourcesOptions<ListModelsOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListPredictionsOptions.java
package ai.lucidtech.las.sdk; public class ListPredictionsOptions extends ListResourcesOptions<ListPredictionsOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListResourcesOptions.java
package ai.lucidtech.las.sdk; import org.apache.http.message.BasicNameValuePair; import org.apache.http.NameValuePair; import java.util.ArrayList; import java.util.List; public class ListResourcesOptions<T> { private Integer maxResults; private String nextToken; public T setMaxResults(int maxResults) { this.maxResults = maxResults; return (T) this; } public T setNextToken(String nextToken) { this.nextToken = nextToken; return (T) this; } protected void addOption(List<NameValuePair> parameters, String key, String value) { if (value != null) { parameters.add(new BasicNameValuePair(key, value)); } } protected void addOption(List<NameValuePair> parameters, String key, String[] value) { if (value != null) { for (String v : value) { parameters.add(new BasicNameValuePair(key, v)); } } } protected void addOption(List<NameValuePair> parameters, String key, List<String> value) { if (value != null) { for (String v : value) { parameters.add(new BasicNameValuePair(key, v)); } } } protected void addOption(List<NameValuePair> parameters, String key, Integer value) { if (value != null) { parameters.add(new BasicNameValuePair(key, Integer.toString(value))); } } public List<NameValuePair> addOptions(List<NameValuePair> parameters) { this.addOption(parameters, "maxResults", this.maxResults); this.addOption(parameters, "nextToken", this.nextToken); return parameters; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListSecretsOptions.java
package ai.lucidtech.las.sdk; public class ListSecretsOptions extends ListResourcesOptions<ListSecretsOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListSortablesOptions.java
package ai.lucidtech.las.sdk; import org.apache.http.NameValuePair; import java.util.ArrayList; import java.util.List; public class ListSortablesOptions<T> extends ListResourcesOptions<T> { protected String sortBy; protected Order order; public T setSortBy(String sortBy) { this.sortBy = sortBy; return (T) this; } public T setOrder(Order order) { this.order = order; return (T) this; } public List<NameValuePair> addOptions(List<NameValuePair> parameters) { this.addOption(parameters, "sortBy", this.sortBy); if (this.order != null) { this.addOption(parameters, "order", this.order.value); } return super.addOptions(parameters); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListTransitionExecutionsOptions.java
package ai.lucidtech.las.sdk; import org.apache.http.NameValuePair; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ListTransitionExecutionsOptions extends ListSortablesOptions<ListTransitionExecutionsOptions> { private List<String> executionId; private List<TransitionExecutionStatus> status; public ListTransitionExecutionsOptions setExecutionId(List<String> executionId) { this.executionId = executionId; return this; } public ListTransitionExecutionsOptions setExecutionId(String executionId) { this.executionId = Arrays.asList(executionId); return this; } public ListTransitionExecutionsOptions setStatus(List<TransitionExecutionStatus> status) { this.status = status; return this; } public ListTransitionExecutionsOptions setStatus(TransitionExecutionStatus status) { this.status = Arrays.asList(status); return this; } public List<NameValuePair> addOptions(List<NameValuePair> parameters) { this.addOption(parameters, "executionId", this.executionId); if (this.status != null) { List<String> statusList = this.status.stream().map(s -> s.value).collect(Collectors.toList()); this.addOption(parameters, "status", statusList); } return super.addOptions(parameters); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListTransitionsOptions.java
package ai.lucidtech.las.sdk; import org.apache.http.NameValuePair; import java.util.ArrayList; import java.util.List; public class ListTransitionsOptions extends ListResourcesOptions<ListTransitionsOptions> { private TransitionType transitionType; public ListTransitionsOptions setTransitionType(TransitionType transitionType) { this.transitionType = transitionType; return this; } public List<NameValuePair> addOptions(List<NameValuePair> parameters) { if (this.transitionType != null) { this.addOption(parameters, "transitionType", this.transitionType.value); } return super.addOptions(parameters); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListUsersOptions.java
package ai.lucidtech.las.sdk; public class ListUsersOptions extends ListResourcesOptions<ListUsersOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListWorkflowExecutionsOptions.java
package ai.lucidtech.las.sdk; import org.apache.http.NameValuePair; import java.util.ArrayList; import java.util.List; import java.util.Arrays; import java.util.stream.Collectors; public class ListWorkflowExecutionsOptions extends ListSortablesOptions<ListWorkflowExecutionsOptions> { private List<WorkflowExecutionStatus> status; public ListWorkflowExecutionsOptions setStatus(List<WorkflowExecutionStatus> status) { this.status = status; return this; } public ListWorkflowExecutionsOptions setStatus(WorkflowExecutionStatus status) { this.status = Arrays.asList(status); return this; } public List<NameValuePair> addOptions(List<NameValuePair> parameters) { if (this.status != null) { List<String> statusList = this.status.stream().map(s -> s.value).collect(Collectors.toList()); this.addOption(parameters, "status", statusList); } return super.addOptions(parameters); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ListWorkflowsOptions.java
package ai.lucidtech.las.sdk; public class ListWorkflowsOptions extends ListResourcesOptions<ListWorkflowsOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ManualTransitionParameters.java
package ai.lucidtech.las.sdk; import java.util.Map; import org.json.JSONObject; public class ManualTransitionParameters extends TransitionParameters { private Map<String, String> assets; public ManualTransitionParameters setAssets(Map<String, String> assets) { this.assets = assets; return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "assets", this.assets); return body; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/MissingAccessTokenException.java
package ai.lucidtech.las.sdk; public class MissingAccessTokenException extends Exception {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/MissingCredentialsException.java
package ai.lucidtech.las.sdk; public class MissingCredentialsException extends Exception {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/ModelStatus.java
package ai.lucidtech.las.sdk; public enum ModelStatus { INACTIVE("inactive"), ACTIVE("active"), TRAINING("training"); public final String value; ModelStatus(String value) { this.value = value; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/NameAndDescriptionOptions.java
package ai.lucidtech.las.sdk; import org.json.JSONObject; public class NameAndDescriptionOptions<T> extends Options { private NullableString name = new NullableString(); private NullableString description = new NullableString(); public T setName(String name) { this.name.setValue(name); return (T) this; } public T setDescription(String description) { this.description.setValue(description); return (T) this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "name", this.name); this.addOption(body, "description", this.description); return body; } public JSONObject toJson() { JSONObject body = new JSONObject(); return this.addOptions(body); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/NullableString.java
package ai.lucidtech.las.sdk; class NullableString { public Boolean hasEditedValue; private String value; public NullableString() { this.hasEditedValue = false; this.value = null; } public void setValue(String value) { this.value = value; this.hasEditedValue = true; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/Options.java
package ai.lucidtech.las.sdk; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; public abstract class Options { protected void addOption(JSONObject body, String key, NullableString value) { if (value != null && value.hasEditedValue) { body.put(key, value); } } protected void addOption(JSONObject body, String key, String value) { if (value != null) { body.put(key, value); } } protected void addOption(JSONObject body, String key, String[] value) { if (value != null) { body.put(key, value); } } protected void addOption(JSONObject body, String key, Map<String, String> value) { if (value != null) { JSONObject mapBody = new JSONObject(); for (Map.Entry<String, String> entry: value.entrySet()) { mapBody.put(entry.getKey(), entry.getValue()); } body.put(key, mapBody); } } protected void addOption(JSONObject body, String key, Boolean value) { if (value != null) { body.put(key, value); } } protected void addOption(JSONObject body, String key, Integer value) { if (value != null) { body.put(key, value); } } protected void addOption(JSONObject body, String key, JSONArray value) { if (value != null) { body.put(key, value); } } protected void addOption(JSONObject body, String key, JSONObject value) { if (value != null) { body.put(key, value); } } protected void addOption(JSONObject body, String key, Options value) { if (value != null) { JSONObject options = new JSONObject(); body.put(key, value.addOptions(options)); } } abstract public JSONObject addOptions(JSONObject body); }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/Order.java
package ai.lucidtech.las.sdk; public enum Order { ASCENDING("ascending"), DESCENDING("descending"); public final String value; Order(String value) { this.value = value; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/PreprocessConfig.java
package ai.lucidtech.las.sdk; import java.util.ArrayList; import java.util.Map; import org.json.JSONObject; public class PreprocessConfig extends Options { private ImageQuality imageQuality; private Boolean autoRotate; private Integer maxPages; public PreprocessConfig setImageQuality(ImageQuality imageQuality) { this.imageQuality = imageQuality; return this; } public PreprocessConfig setAutoRotate(Boolean autoRotate) { this.autoRotate = autoRotate; return this; } public PreprocessConfig setMaxPages(Integer maxPages) { this.maxPages = maxPages; return this; } public JSONObject addOptions(JSONObject body) { if (this.imageQuality != null) { this.addOption(body, "imageQuality", this.imageQuality.value); } this.addOption(body, "autoRotate", this.autoRotate); this.addOption(body, "maxPages", this.maxPages); return body; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/TransitionExecutionStatus.java
package ai.lucidtech.las.sdk; public enum TransitionExecutionStatus { SUCCEEDED("succeeded"), FAILED("failed"), REJECTED("rejected"); public final String value; TransitionExecutionStatus(String value) { this.value = value; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/TransitionParameters.java
package ai.lucidtech.las.sdk; import org.json.JSONObject; public abstract class TransitionParameters extends Options { abstract public JSONObject addOptions(JSONObject body); }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/TransitionType.java
package ai.lucidtech.las.sdk; public enum TransitionType { MANUAL("manual"), DOCKER("docker"); public final String value; TransitionType(String value) { this.value = value; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateAppClientOptions.java
package ai.lucidtech.las.sdk; public class UpdateAppClientOptions extends NameAndDescriptionOptions<UpdateAppClientOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateAssetOptions.java
package ai.lucidtech.las.sdk; import org.apache.commons.io.IOUtils; import org.json.JSONObject; import java.io.InputStream; import java.io.IOException; import java.util.Base64; public class UpdateAssetOptions extends NameAndDescriptionOptions<UpdateAssetOptions> { private String content; public UpdateAssetOptions setContent(byte[] content) { this.content = Base64.getEncoder().encodeToString(content); return this; } public UpdateAssetOptions setContent(InputStream content) throws IOException { this.content = Base64.getEncoder().encodeToString(IOUtils.toByteArray(content)); return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "content", this.content); return super.addOptions(body); } public JSONObject toJson() { JSONObject body = new JSONObject(); return this.addOptions(body); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateDocumentOptions.java
package ai.lucidtech.las.sdk; import org.json.JSONArray; import org.json.JSONObject; public class UpdateDocumentOptions extends Options { private String datasetId; private JSONArray groundTruth; private Integer retentionInDays; public UpdateDocumentOptions setDatasetId(String datasetId) { this.datasetId = datasetId; return this; } public UpdateDocumentOptions setGroundTruth(JSONArray groundTruth) { this.groundTruth = groundTruth; return this; } public UpdateDocumentOptions setRetentionInDays(Integer retentionInDays) { this.retentionInDays = retentionInDays; return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "datasetId", this.datasetId); this.addOption(body, "groundTruth", this.groundTruth); this.addOption(body, "retentionInDays", this.retentionInDays); return body; } public JSONObject toJson() { JSONObject body = new JSONObject(); return this.addOptions(body); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateModelOptions.java
package ai.lucidtech.las.sdk; import org.apache.commons.io.IOUtils; import org.json.JSONObject; import java.io.InputStream; import java.io.IOException; import java.util.Base64; public class UpdateModelOptions extends NameAndDescriptionOptions<UpdateModelOptions> { private Integer width; private Integer height; private FieldConfig fieldConfig; private ModelStatus modelStatus; private PreprocessConfig preprocessConfig; public UpdateModelOptions setWidth(Integer width) { this.width = width; return this; } public UpdateModelOptions setHeight(Integer height) { this.height = height; return this; } public UpdateModelOptions setFieldConfig(FieldConfig fieldConfig) { this.fieldConfig = fieldConfig; return this; } public UpdateModelOptions setModelStatus(ModelStatus modelStatus) { this.modelStatus = modelStatus; return this; } public UpdateModelOptions setPreprocessConfig(PreprocessConfig preprocessConfig) { this.preprocessConfig = preprocessConfig; return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "width", this.width); this.addOption(body, "height", this.height); this.addOption(body, "fieldConfig", this.fieldConfig); if (this.modelStatus != null) { this.addOption(body, "status", this.modelStatus.value); } this.addOption(body, "preprocessConfig", this.preprocessConfig); return super.addOptions(body); } public JSONObject toJson() { JSONObject body = new JSONObject(); return this.addOptions(body); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateSecretOptions.java
package ai.lucidtech.las.sdk; import java.util.Map; import org.json.JSONObject; public class UpdateSecretOptions extends NameAndDescriptionOptions<UpdateSecretOptions> { private JSONObject data; public UpdateSecretOptions setData(JSONObject data) { this.data = data; return this; } public UpdateSecretOptions setData(Map<String, String> data) { this.data = new JSONObject(data); return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "data", this.data); return super.addOptions(body); } public JSONObject toJson() { JSONObject body = new JSONObject(); return this.addOptions(body); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateTransitionExecutionOptions.java
package ai.lucidtech.las.sdk; import java.time.format.DateTimeFormatter; import java.time.ZonedDateTime; import org.json.JSONObject; public class UpdateTransitionExecutionOptions extends Options { private JSONObject output; private JSONObject error; private String startTime; public UpdateTransitionExecutionOptions setOutput(JSONObject error) { this.output = output; return this; } public UpdateTransitionExecutionOptions setError(JSONObject output) { this.error = error; return this; } public UpdateTransitionExecutionOptions setStartTime(String startTime) { this.startTime = startTime; return this; } public UpdateTransitionExecutionOptions setStartTime(ZonedDateTime startTime) { this.startTime = startTime.format(DateTimeFormatter.ISO_INSTANT); return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "output", this.output); this.addOption(body, "error", this.error); this.addOption(body, "startTime", this.startTime); return body; } public JSONObject toJson() { JSONObject body = new JSONObject(); return this.addOptions(body); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateTransitionOptions.java
package ai.lucidtech.las.sdk; import org.json.JSONObject; public class UpdateTransitionOptions extends NameAndDescriptionOptions<UpdateTransitionOptions> { private JSONObject inputJsonSchema; private JSONObject outputJsonSchema; public UpdateTransitionOptions setInputJsonSchema(JSONObject schema) { this.inputJsonSchema = schema; return this; } public UpdateTransitionOptions setOutputJsonSchema(JSONObject schema) { this.outputJsonSchema = schema; return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "inputJsonSchema", this.inputJsonSchema); this.addOption(body, "outputJsonSchema", this.outputJsonSchema); return super.addOptions(body); } public JSONObject toJson() { JSONObject body = new JSONObject(); return this.addOptions(body); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateUserOptions.java
package ai.lucidtech.las.sdk; public class UpdateUserOptions extends UserOptions<UpdateUserOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UpdateWorkflowOptions.java
package ai.lucidtech.las.sdk; public class UpdateWorkflowOptions extends NameAndDescriptionOptions<UpdateWorkflowOptions> {}
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/UserOptions.java
package ai.lucidtech.las.sdk; import org.json.JSONObject; import java.util.Base64; public class UserOptions<T> extends Options { private String name; private String avatar; public T setName(String name) { this.name = name; return (T) this; } public T setAvatar(String avatar) { this.avatar = avatar; return (T) this; } public T setAvatar(byte[] avatar) { this.avatar = Base64.getEncoder().encodeToString(avatar); return (T) this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "name", this.name); this.addOption(body, "avatar", this.avatar); return body; } public JSONObject toJson() { JSONObject body = new JSONObject(); return this.addOptions(body); } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/WorkflowCompletedConfig.java
package ai.lucidtech.las.sdk; import java.util.Map; import org.json.JSONObject; public class WorkflowCompletedConfig extends Options { private String imageUrl; private String secretId; private String[] environmentSecrets; private Map<String, String> environment; public WorkflowCompletedConfig setImageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public WorkflowCompletedConfig setSecretId(String secretId) { this.secretId = secretId; return this; } public WorkflowCompletedConfig setEnvironmentSecrets(String[] environmentSecrets) { this.environmentSecrets = environmentSecrets; return this; } public WorkflowCompletedConfig setEnvironment(Map<String, String> environment) { this.environment = environment; return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "imageUrl", this.imageUrl); this.addOption(body, "secretId", this.secretId); this.addOption(body, "environmentSecrets", this.environmentSecrets); this.addOption(body, "environment", this.environment); return body; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/WorkflowErrorConfig.java
package ai.lucidtech.las.sdk; import org.json.JSONObject; public class WorkflowErrorConfig extends Options { private String email; private Boolean manualRetry; public WorkflowErrorConfig setEmail(String email) { this.email = email; return this; } public WorkflowErrorConfig setManualRetry(Boolean manualRetry) { this.manualRetry = manualRetry; return this; } public JSONObject addOptions(JSONObject body) { this.addOption(body, "email", this.email); this.addOption(body, "manualRetry", this.manualRetry); return body; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/WorkflowExecutionStatus.java
package ai.lucidtech.las.sdk; public enum WorkflowExecutionStatus { SUCCEEDED("succeeded"), FAILED("failed"), REJECTED("rejected"); public final String value; WorkflowExecutionStatus(String value) { this.value = value; } }
0
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las
java-sources/ai/lucidtech/las-sdk-java/4.0.0/ai/lucidtech/las/sdk/package-info.java
package ai.lucidtech.las.sdk;
0
java-sources/ai/madara/madara/3.2.3/ai
java-sources/ai/madara/madara/3.2.3/ai/madara/MadaraJNI.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara; /** * Abstract class that insures loading of libMADARA.so and holds the C pointer */ public abstract class MadaraJNI { static { System.loadLibrary("MADARA"); } /** * C pointer to an object */ private long cptr = 0; /** * Set the C pointer to the object * * @param cptr * C Pointer */ protected void setCPtr(long cptr) { this.cptr = cptr; } /** * @return The C pointer of this object for passing to JNI functions */ public long getCPtr() { return cptr; } /** * @return &lt;ClassName&gt;[&lt;C Pointer&gt;] * @see java.lang.Object#toString () */ public String toString() { return getClass().getName() + "[" + cptr + "]"; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/exceptions/MadaraDeadObjectException.java
package ai.madara.exceptions; public class MadaraDeadObjectException extends Exception { /** * version */ private static final long serialVersionUID = 1L; /** * Constructor */ public MadaraDeadObjectException() { } /** * Constructor with message * @param message information to embed in the exception */ public MadaraDeadObjectException(String message) { super(message); } /** * Constructor with cause * @param cause source of the exception */ public MadaraDeadObjectException(Throwable cause) { super(cause); } /** * Constructor with cause and message * @param message information to embed in the exception * @param cause source of the exception */ public MadaraDeadObjectException(String message, Throwable cause) { super(message, cause); } /** * Constructor with cause and message and suppression * @param message information to embed in the exception * @param cause source of the exception * @param enableSuppression if true, suppress the throw * @param writableStackTrace if true, write stack trace */ public MadaraDeadObjectException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/filters/BufferFilter.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.filters; import ai.madara.exceptions.MadaraDeadObjectException; public interface BufferFilter { /** * Encodes a buffer * @param buffer a map of all variable names to values * @param size the initial size of the buffer * @param maxSize the maximum size of the buffer * @return the new size of the buffer contents **/ public long encode(byte[] buffer, long size, long maxSize) throws MadaraDeadObjectException; /** * Decodes a buffer * @param buffer a map of all variable names to values * @param size the initial size of the buffer * @param maxSize the maximum size of the buffer * @return the new size of the buffer contents **/ public long decode(byte[] buffer, long size, long maxSize) throws MadaraDeadObjectException; }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/filters/CounterFilter.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.filters; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.transport.QoSTransportSettings; /** * A facade for the C++ Counter_Filter aggregate filter **/ public class CounterFilter extends MadaraJNI { private native long jni_CounterFilter(); private native double jni_getThroughput(long cptr); private native void jni_addReceiveFilterTo(long cptr, long qosCptr); private native void jni_addSendFilterTo(long cptr, long qosCptr); private native void jni_addRebroadcastFilterTo(long cptr, long qosCptr); private native long jni_getCount(long cptr); private native long jni_getElapsed(long cptr); private static native void jni_freeCounterFilter(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public CounterFilter() { setCPtr(jni_CounterFilter()); } /** * Converts the value to a double * * @return current double value */ public double getThroughput() throws MadaraDeadObjectException { return jni_getThroughput(getCPtr()); } /** * Returns the number of packets filtered * * @return the number of packets filtered */ public long getCount() throws MadaraDeadObjectException { return jni_getCount(getCPtr()); } /** * Returns the number of packets filtered * * @return the number of packets filtered */ public long getElapsed() throws MadaraDeadObjectException { return jni_getElapsed(getCPtr()); } /** * Adds the filter as a receive filter to transport settings * @param settings the QoS Transport settings to add the filter to */ public void addReceiveFilterTo(QoSTransportSettings settings) throws MadaraDeadObjectException { jni_addReceiveFilterTo(getCPtr(), settings.getCPtr()); } /** * Adds the filter as a receive filter to transport settings * @param settings the QoS Transport settings to add the filter to */ public void addSendFilterTo(QoSTransportSettings settings) throws MadaraDeadObjectException { jni_addSendFilterTo(getCPtr(), settings.getCPtr()); } /** * Adds the filter as a receive filter to transport settings * @param settings the QoS Transport settings to add the filter to */ public void addRebroadcastFilterTo(QoSTransportSettings settings) throws MadaraDeadObjectException { jni_addRebroadcastFilterTo(getCPtr(), settings.getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeCounterFilter(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/filters/EndpointClear.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.filters; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.transport.QoSTransportSettings; /** * A facade for the C++ Counter_Filter aggregate filter **/ public class EndpointClear extends MadaraJNI { private native long jni_EndpointClear(); private native void jni_addReceiveFilterTo(long cptr, long qosCptr); private native void jni_addSendFilterTo(long cptr, long qosCptr); private native void jni_addRebroadcastFilterTo(long cptr, long qosCptr); private native void jni_setPrefix(long cptr, String prefix); private static native void jni_freeEndpointClear(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public EndpointClear() { setCPtr(jni_EndpointClear()); } /** * Sets prefix where domain members are kept * @param prefix the new variable prefix */ void setPrefix(String prefix) throws MadaraDeadObjectException { jni_setPrefix(getCPtr(), prefix); } /** * Adds the filter as a receive filter to transport settings * @param settings the QoS Transport settings to add the filter to */ public void addReceiveFilterTo(QoSTransportSettings settings) throws MadaraDeadObjectException { jni_addReceiveFilterTo(getCPtr(), settings.getCPtr()); } /** * Adds the filter as a receive filter to transport settings * @param settings the QoS Transport settings to add the filter to */ public void addSendFilterTo(QoSTransportSettings settings) throws MadaraDeadObjectException { jni_addSendFilterTo(getCPtr(), settings.getCPtr()); } /** * Adds the filter as a receive filter to transport settings * @param settings the QoS Transport settings to add the filter to */ public void addRebroadcastFilterTo(QoSTransportSettings settings) throws MadaraDeadObjectException { jni_addRebroadcastFilterTo(getCPtr(), settings.getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeEndpointClear(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/filters
java-sources/ai/madara/madara/3.2.3/ai/madara/filters/ssl/AesBufferFilter.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.filters.ssl; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.filters.BufferFilter; public class AesBufferFilter extends MadaraJNI implements BufferFilter { private native long jni_AesBufferFilter(); private native long jni_AesBufferFilter(long cptr); private static native void jni_freeAesBufferFilter(long cptr); private native long jni_encode(long cptr, byte[] buffer, long size, long maxSize); private native long jni_decode(long cptr, byte[] buffer, long size, long maxSize); private native int jni_generateKey(long cptr, java.lang.String password); /** * Let the transport layer manage this */ private boolean manageMemory = false; /** * Default constructor **/ public AesBufferFilter() { setCPtr(jni_AesBufferFilter()); } /** * Copy constructor * @param input instance to copy **/ public AesBufferFilter(AesBufferFilter input) { setCPtr(jni_AesBufferFilter(input.getCPtr())); } /** * Encodes a buffer * @param buffer a map of all variable names to values * @param size the initial size of the buffer * @param maxSize the maximum size of the buffer * @return the new size of the buffer contents **/ @Override public long encode(byte[] buffer, long size, long maxSize) throws MadaraDeadObjectException { return jni_encode(getCPtr(), buffer, size, maxSize); } /** * Decodes a buffer * @param buffer a map of all variable names to values * @param size the initial size of the buffer * @param maxSize the maximum size of the buffer * @return the new size of the buffer contents **/ @Override public long decode(byte[] buffer, long size, long maxSize) throws MadaraDeadObjectException { return jni_decode(getCPtr(), buffer, size, maxSize); } /** * Generates a 256 bit AES key from a password * @param password a password to use * @return 0 if successful, non zero otherwise **/ public int generateKey(java.lang.String password) throws MadaraDeadObjectException { return jni_generateKey(getCPtr(), password); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeAesBufferFilter(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/EvalSettings.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; /** * Encapsulates settings for an evaluation statement. */ public class EvalSettings extends MadaraJNI { //Constructors private static native long jni_evalSettings(); private static native long jni_evalSettings(long oldPtr); //Getters/Setters private static native void jni_setDelaySendingModifieds(long cptr, boolean delaySendingModifieds); private static native boolean jni_getDelaySendingModifieds(long cptr); private static native void jni_setPrePrintStatement(long cptr, String prePrintStatement); private static native String jni_getPrePrintStatement(long cptr); private static native void jni_setPostPrintStatement(long cptr, String prePrintStatement); private static native String jni_getPostPrintStatement(long cptr); private static native void jni_setAlwaysOverwrite(long cptr, boolean alwaysOverwrite); private static native boolean jni_getAlwaysOverwrite(long cptr); private static native void jni_setTreatGlobalsAsLocals(long cptr, boolean treatGlobalsAsLocals); private static native boolean jni_getTreatGlobalsAsLocals(long cptr); private static native void jni_setClockIncrement(long cptr, long defaultClockIncrement); private static native long jni_getClockIncrement(long cptr); private static native void jni_freeEvalSettings(long cptr); public static final EvalSettings DEFAULT_EVAL_SETTINGS = new EvalSettings(jni_evalSettings()); /** * Default constructor */ public EvalSettings() { setCPtr(jni_evalSettings()); } /** * Copy constructor * * @param input the settings to copy from */ public EvalSettings(EvalSettings input) { setCPtr(jni_evalSettings(input.getCPtr())); } /** * Constructor to create constants * * @param cptr Pointer to C++ object */ protected EvalSettings(long cptr) { setCPtr(cptr); } /** * @param delaySendingModifieds Toggle for sending modifieds in a single update event after each evaluation. */ public void setDelaySendingModifieds(boolean delaySendingModifieds) throws MadaraDeadObjectException { jni_setDelaySendingModifieds(getCPtr(), delaySendingModifieds); } /** * @return current value of delaySendingModifieds */ public boolean getDelaySendingModifieds() throws MadaraDeadObjectException { return jni_getDelaySendingModifieds(getCPtr()); } /** * @param prePrintStatement Statement to print before evaluations. */ public void setPrePrintStatement(String prePrintStatement) throws MadaraDeadObjectException { jni_setPrePrintStatement(getCPtr(), prePrintStatement); } /** * @return current value of prePrintStatement */ public String getPrePrintStatement() throws MadaraDeadObjectException { return jni_getPrePrintStatement(getCPtr()); } /** * @param postPrintStatement Statement to print after evaluations. */ public void setPostPrintStatement(String postPrintStatement) throws MadaraDeadObjectException { jni_setPostPrintStatement(getCPtr(), postPrintStatement); } /** * @return current value of getPostPrintStatement */ public String getPostPrintStatement() throws MadaraDeadObjectException { return jni_getPostPrintStatement(getCPtr()); } /** * @param alwaysOverwrite Toggle for always overwriting records, regardless of quality, clock values, etc. */ public void setAlwaysOverwrite(boolean alwaysOverwrite) throws MadaraDeadObjectException { jni_setAlwaysOverwrite(getCPtr(), alwaysOverwrite); } /** * @return current value of alwaysOverwrite */ public boolean getAlwaysOverwrite() throws MadaraDeadObjectException { return jni_getAlwaysOverwrite(getCPtr()); } /** * @param treatGlobalsAsLocals Toggle whether updates to global variables are * treated as local variables and not marked as modified to the transport. */ public void setTreatGlobalsAsLocals(boolean treatGlobalsAsLocals) throws MadaraDeadObjectException { jni_setTreatGlobalsAsLocals(getCPtr(), treatGlobalsAsLocals); } /** * @return current value of treatGlobalsAsLocals */ public boolean getTreatGlobalsAsLocals() throws MadaraDeadObjectException { return jni_getTreatGlobalsAsLocals(getCPtr()); } /** * @param defaultClockIncrement Default clock increment. */ public void setDefaultClockIncrement(long defaultClockIncrement) throws MadaraDeadObjectException { jni_setClockIncrement(getCPtr(), defaultClockIncrement); } /** * @return get the default clock increment */ public long getDefaultClockIncrement() throws MadaraDeadObjectException { return jni_getClockIncrement(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of EvalSettings gets garbage collected */ public void free() { jni_freeEvalSettings(getCPtr()); setCPtr(0); } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/KnowledgeBase.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.logger.GlobalLogger; import ai.madara.logger.LogLevels; import ai.madara.logger.Logger; import ai.madara.transport.TransportSettings; import ai.madara.transport.TransportType; /** * This class provides a distributed knowledge base to users **/ public class KnowledgeBase extends MadaraJNI { //Native Methods private native long jni_KnowledgeBase(); private native long jni_KnowledgeBase(String host, int transport, String domain); private native long jni_KnowledgeBase(String host, long config); private native long jni_KnowledgeBase(long original); private native String jni_getID(long cptr); private native String jni_debugModifieds(long cptr); private native void jni_closeTransports(long cptr); private native void jni_attachLogger(long cptr, long logger); private native void jni_attachTransport(long cptr, String id, long settings); private native long jni_getLogger(long cptr); private native long jni_evaluate(long cptr, String expression, long evalSettings); private native long jni_evaluate(long cptr, long expression, long evalSettings); private native void jni_evaluateNoReturn(long cptr, String expression, long evalSettings); private native void jni_evaluateNoReturn(long cptr, long expression, long evalSettings); private native long jni_compile(long cptr, String expression); private native void jni_defineFunction(long cptr, String name, MadaraFunction function); private native void jni_defineFunction(long cptr, String name, String expression); private native void jni_print(long cptr, String statement); private native void jni_print(long cptr); private native void jni_clear(long cptr); private native boolean jni_exists(long cptr, String statement); private native void jni_sendModifieds(long cptr); private native void jni_sendModifieds(long cptr, long evalSettings); private native void jni_clearModifieds(long cptr); private native long jni_get(long cptr, String name); private static native void jni_setInteger(long cptr, String name, long value); private static native void jni_setDouble(long cptr, String name, double value); private static native void jni_setString(long cptr, String name, String value); private static native void jni_setIntegerArray(long cptr, String name, long[] value); private static native void jni_setDoubleArray(long cptr, String name, double[] value); private static native void jni_setFile(long cptr, String name, byte[] value); private static native void jni_setImage(long cptr, String name, byte[] value); private static native void jni_setIntegerSettings(long cptr, String name, long value, long settings); private static native void jni_setDoubleSettings(long cptr, String name, double value, long settings); private static native void jni_setStringSettings(long cptr, String name, String value, long settings); private static native void jni_setIntegerArraySettings(long cptr, String name, long[] value, long settings); private static native void jni_setDoubleArraySettings(long cptr, String name, double[] value, long settings); private static native void jni_setFileSettings(long cptr, String name, byte[] value, long settings); private static native void jni_setImageSettings(long cptr, String name, byte[] value, long settings); private native void jni_freeKnowledgeBase(long cptr); private native long jni_wait(long cptr, String expression, long waitSettings); private native long jni_wait(long cptr, long expression, long waitSettings); private native void jni_waitNoReturn(long cptr, String expression, long waitSettings); private native void jni_waitNoReturn(long cptr, long expression, long waitSettings); private native long[] jni_toKnowledgeList(long cptr, String subject, int start, int end); private native void jni_toKnowledgeMap(long cptr, String expression, MapReturn ret); private native void jni_toMap(long cptr, String prefix, String suffix, MapReturn ret); private native long jni_saveContext(long cptr, String filename); private native long jni_saveAsKarl(long cptr, String filename); private native long jni_saveCheckpoint(long cptr, String filename, boolean resetModifieds); private native java.lang.String jni_toString(long cptr, java.lang.String arrayDelimiter, java.lang.String recordDelimiter, java.lang.String keyvalDelimiter); private native long jni_loadContext(long cptr, String filename, boolean useId, long settings); private boolean manageMemory = true; /** * Creates a KnowledgeBase with default settings **/ public KnowledgeBase() { setCPtr(jni_KnowledgeBase()); } /** * Creates a KnowledgeBase * * @param host hostname/ip of this machine * @param transport to use for knowledge dissemination * @param domain knowledge domain we want to join **/ public KnowledgeBase(String host, TransportType transport, String domain) { setCPtr(jni_KnowledgeBase(host, transport.value(), domain)); } /** * Creates a KnowledgeBase * * @param host hostname/ip of this machine * @param config transport settings to use for dissemination **/ public KnowledgeBase(String host, TransportSettings config) { setCPtr(jni_KnowledgeBase(host, config.getCPtr())); } /** * Copy constructor * * @param original knowledge base to copy from **/ public KnowledgeBase(KnowledgeBase original) { setCPtr(jni_KnowledgeBase(original.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer **/ public static KnowledgeBase fromPointer(long cptr) { KnowledgeBase ret = new KnowledgeBase(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer **/ public static KnowledgeBase fromPointer(long cptr, boolean shouldManage) { KnowledgeBase ret = new KnowledgeBase(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Get KnowledgeBase ID * * @return KnowledgeBase ID **/ public String getID () throws MadaraDeadObjectException { return jni_getID (getCPtr ()); } /** * Evaluates an expression. * <br>The returned KnowledgeRecord <b>must</b> be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) * at some point. If it is to be ignored, consider using {@link #evaluateNoReturn (String)} * * @param expression KaRL expression to evaluate * @return value of expression * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord evaluate(String expression) throws MadaraDeadObjectException { return evaluate(expression, EvalSettings.DEFAULT_EVAL_SETTINGS); } /** * Evaluates an expression. * * @param expression KaRL expression to evaluate * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void evaluateNoReturn(String expression) throws MadaraDeadObjectException { evaluateNoReturn(expression, EvalSettings.DEFAULT_EVAL_SETTINGS); } /** * Evaluates an expression. * The returned KnowledgeRecord <b>must</b> be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) at some point. If * it is to be ignored, consider using {@link #evaluateNoReturn (String,EvalSettings)} * * @param expression KaRL expression to evaluate * @param evalSettings Settings for evaluating and printing * @return value of expression * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord evaluate(String expression, EvalSettings evalSettings) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_evaluate(getCPtr(), expression, evalSettings.getCPtr())); } /** * Evaluates an expression. * * @param expression KaRL expression to evaluate * @param evalSettings evalSettings Settings for evaluating and printing * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void evaluateNoReturn(String expression, EvalSettings evalSettings) throws MadaraDeadObjectException { jni_evaluateNoReturn(getCPtr(), expression, evalSettings.getCPtr()); } /** * Evaluates an expression. * The returned KnowledgeRecord <b>must</b> be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) at some point. If * it is to be ignored, consider using {@link #evaluateNoReturn (CompiledExpression)} * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @return value of expression * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord evaluate(CompiledExpression expression) throws MadaraDeadObjectException { return evaluate(expression, EvalSettings.DEFAULT_EVAL_SETTINGS); } /** * Evaluates an expression. * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void evaluateNoReturn(CompiledExpression expression) throws MadaraDeadObjectException { evaluateNoReturn(expression, EvalSettings.DEFAULT_EVAL_SETTINGS); } /** * Evaluates an expression. * The returned KnowledgeRecord <b>must</b> be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) at some point. If * it is to be ignored, consider using {@link #evaluateNoReturn (CompiledExpression,EvalSettings)} * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @param evalSettings Settings for evaluating and printing * @return value of expression * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord evaluate(CompiledExpression expression, EvalSettings evalSettings) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_evaluate(getCPtr(), expression.getCPtr(), evalSettings.getCPtr())); } /** * Evaluates an expression. * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @param evalSettings Settings for evaluating and printing * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void evaluateNoReturn(CompiledExpression expression, EvalSettings evalSettings) throws MadaraDeadObjectException { jni_evaluateNoReturn(getCPtr(), expression.getCPtr(), evalSettings.getCPtr()); } /** * Compiles a KaRL expression into an expression tree. * * @param expression expression to compile * @return {@link ai.madara.knowledge.KnowledgeBase.CompiledExpression CompiledExpression}: compiled, optimized expression tree * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public CompiledExpression compile(String expression) throws MadaraDeadObjectException { return new CompiledExpression(jni_compile(getCPtr(), expression)); } /** * <b>Currently unsupported</b><br> * Defines a function. * * @param name name of the function * @param function Implementation of MadaraFunction * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void defineFunction(String name, MadaraFunction function) throws MadaraDeadObjectException { jni_defineFunction(getCPtr(), name, function); } /** * Attaches a logger that will manage all output from the KnowledgeBase * * @param logger a logger to use for managing information and debugging **/ public void attachLogger(Logger logger) throws MadaraDeadObjectException { jni_attachLogger(getCPtr(), logger.getCPtr()); } /** * Attaches a new transport to the Knowledge Base * * @param id unique identifier for this agent * @param settings settings for the new transport **/ public void attachTransport(String id, ai.madara.transport.TransportSettings settings) throws MadaraDeadObjectException { jni_attachTransport(getCPtr(), id, settings.getCPtr()); } /** * Returns the logger that manages all output from the KnowledgeBase * * @return the logger being used for managing information and debugging **/ public Logger getLogger() throws MadaraDeadObjectException { return Logger.fromPointer(jni_getLogger(getCPtr()), false); } /** * Retrieves a stringified list of all modified variables that are ready * to send over transport on next send_modifieds call * * @return stringified list of the modified knowledge records */ public String debugModifieds() throws MadaraDeadObjectException { return jni_debugModifieds(getCPtr()); } /** * Closes any transports attached to the Knowledge Base */ public void closeTransports() throws MadaraDeadObjectException { jni_closeTransports(getCPtr()); } /** * Defines a MADARA KaRL function. * * @param name name of the function * @param expression KaRL function body * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void defineFunction(String name, String expression) throws MadaraDeadObjectException { jni_defineFunction(getCPtr(), name, expression); } /** * Clears the knowledge base. * * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void clear() throws MadaraDeadObjectException { jni_clear(getCPtr()); } /** * Checks to see if record exists * @param name name of record to check * @return true if the record exists, false otherwise **/ public boolean exists(String name) throws MadaraDeadObjectException { return jni_exists(getCPtr(), name); } /** * Retrieves a knowledge value. * * @param name knowledge name * @return value of knowledge * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord get(String name) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_get(getCPtr(), name)); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, long value) throws MadaraDeadObjectException { jni_setInteger(getCPtr(), name, value); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, double value) throws MadaraDeadObjectException { jni_setDouble(getCPtr(), name, value); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, String value) throws MadaraDeadObjectException { jni_setString(getCPtr(), name, value); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, double[] value) throws MadaraDeadObjectException { jni_setDoubleArray(getCPtr(), name, value); } /** * Sets a knowledge variable to a specified long array. * * @param name knowledge name * @param value value to set * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, long[] value) throws MadaraDeadObjectException { jni_setIntegerArray(getCPtr(), name, value); } /** * Sets a knowledge variable to a specified byte array. * * @param name knowledge name * @param value value to set * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void setFile(String name, byte[] value) throws MadaraDeadObjectException { jni_setFile(getCPtr(), name, value); } /** * Sets a knowledge variable to a specified byte array. * * @param name knowledge name * @param value value to set * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void setImage(String name, byte[] value) throws MadaraDeadObjectException { jni_setImage(getCPtr(), name, value); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @param settings settings for evaluating the set command * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, long value, EvalSettings settings) throws MadaraDeadObjectException { jni_setIntegerSettings(getCPtr(), name, value, settings.getCPtr()); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @param settings settings for evaluating the set command * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, double value, EvalSettings settings) throws MadaraDeadObjectException { jni_setDoubleSettings(getCPtr(), name, value, settings.getCPtr()); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @param settings settings for evaluating the set command * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, String value, EvalSettings settings) throws MadaraDeadObjectException { jni_setStringSettings(getCPtr(), name, value, settings.getCPtr()); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @param settings settings for evaluating the set command * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, double[] value, EvalSettings settings) throws MadaraDeadObjectException { jni_setDoubleArraySettings(getCPtr(), name, value, settings.getCPtr()); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @param settings settings for evaluating the set command * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void set(String name, long[] value, EvalSettings settings) throws MadaraDeadObjectException { jni_setIntegerArraySettings(getCPtr(), name, value, settings.getCPtr()); } /** * Sets a knowledge variable to a specified file byte array. * * @param name knowledge name * @param value value to set * @param settings settings for evaluating the set command * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void setFile(String name, byte[] value, EvalSettings settings) throws MadaraDeadObjectException { jni_setFileSettings(getCPtr(), name, value, settings.getCPtr()); } /** * Sets a knowledge variable to a specified image byte array. * * @param name knowledge name * @param value value to set * @param settings settings for evaluating the set command * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void setImage(String name, byte[] value, EvalSettings settings) throws MadaraDeadObjectException { jni_setImageSettings(getCPtr(), name, value, settings.getCPtr()); } /** * Sends all modifications to global variables since last send modifieds, * eval, wait, or set statement. **/ public void sendModifieds () throws MadaraDeadObjectException { jni_sendModifieds(getCPtr()); } /** * Clears all modified variables that were going to be sent with next call * to sendModifieds (also a part of eval, set, wait and similar functions) **/ public void clearModifieds () throws MadaraDeadObjectException { jni_clearModifieds(getCPtr()); } /** * Sends all modifications to global variables since last send modifieds, * eval, wait, or set statement. * @param settings settings to use for considering records to send **/ public void sendModifieds (EvalSettings settings) throws MadaraDeadObjectException { jni_sendModifieds(getCPtr(), settings.getCPtr()); } /** * Prints a statement with variable expansion * * @param statement The statement to print **/ public void print(String statement) throws MadaraDeadObjectException { jni_print(getCPtr(), statement); } /** * Prints all knowledge in knowledge base **/ public void print() throws MadaraDeadObjectException { jni_print(getCPtr()); } /** * Deletes the C++ instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of KnowledgeBase gets garbage collected * * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void free() { if (manageMemory) { jni_freeKnowledgeBase(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } /** * Waits for an expression to be non-zero. * <br><br>The returned KnowledgeRecord <b>must</b> be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) * at some point. If it is to be ignored, consider using {@link #waitNoReturn (String)} * * @param expression KaRL expression to evaluate * @return value of expression * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord wait(String expression) { return wait(expression, WaitSettings.DEFAULT_WAIT_SETTINGS); } /** * Waits for an expression to be non-zero. * <br><br>The returned KnowledgeRecord <b>must</b> be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) * at some point. If it is to be ignored, consider using {@link #waitNoReturn (CompiledExpression)} * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @return value of expression * @throws MadaraDeadObjectException * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord wait(CompiledExpression expression) throws MadaraDeadObjectException { return wait(expression, WaitSettings.DEFAULT_WAIT_SETTINGS); } /** * Waits for an expression to be non-zero. * <br>Provides additional settings for fine-tuning the time to wait and atomic print statements. * <br><br>The returned KnowledgeRecord <b>must</b> be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) * at some point. If it is to be ignored, consider using {@link #waitNoReturn (String,WaitSettings)} * * @param expression KaRL expression to evaluate * @param settings Settings for waiting * @return value of expression * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord wait(String expression, WaitSettings settings) { return KnowledgeRecord.fromPointer(jni_wait(getCPtr(), expression, settings.getCPtr())); } /** * Waits for an expression to be non-zero. * <br>Provides additional settings for fine-tuning the time to wait and atomic print statements. * <br><br>The returned KnowledgeRecord <b>must</b> be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) * at some point. If it is to be ignored, consider using {@link #waitNoReturn (CompiledExpression,WaitSettings)} * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @param settings Settings for waiting * @return value of expression * @throws MadaraDeadObjectException * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeRecord wait(CompiledExpression expression, WaitSettings settings) throws MadaraDeadObjectException { return new KnowledgeRecord(jni_wait(getCPtr(), expression.getCPtr(), settings.getCPtr())); } /** * Waits for an expression to be non-zero. * * @param expression KaRL expression to evaluate * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void waitNoReturn(String expression) { waitNoReturn(expression, WaitSettings.DEFAULT_WAIT_SETTINGS); } /** * Waits for an expression to be non-zero. * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void waitNoReturn(CompiledExpression expression) { waitNoReturn(expression, WaitSettings.DEFAULT_WAIT_SETTINGS); } /** * Waits for an expression to be non-zero. * * @param expression KaRL expression to evaluate * @param settings Settings for waiting * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void waitNoReturn(String expression, WaitSettings settings) { jni_waitNoReturn(getCPtr(), expression, settings.getCPtr()); } /** * Waits for an expression to be non-zero. * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @param settings Settings for waiting * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public void waitNoReturn(CompiledExpression expression, WaitSettings settings) { jni_waitNoReturn(getCPtr(), expression.getCPtr(), settings.getCPtr()); } /** * Fills a {@link ai.madara.knowledge.KnowledgeList KnowledgeList} with * {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecords} that begin with * a common subject and have a finite range of integer values. * <br><br>The returned {@link ai.madara.knowledge.KnowledgeList KnowledgeList} * <b>must</b> be freed using {@link ai.madara.knowledge.KnowledgeList#free KnowledgeList.free ()} * before the object goes out of scope. * * @param subject The common subject of the variable names. For instance, * if we are looking for a range of vars like "var0", "var1", * "var2", then the common subject would be "var". * @param start An inclusive start index * @param end An inclusive end index * @return {@link ai.madara.knowledge.KnowledgeList KnowledgeList} containing the * requested {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecords} * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeList toKnowledgeList(String subject, int start, int end) { return new KnowledgeList(jni_toKnowledgeList(getCPtr(), subject, start, end)); } /** * Saves the knowledge base to a file * @param filename the file to save the knowledge base to * @return the number of bytes written to the file **/ public long saveContext(String filename) { return jni_saveContext(getCPtr(), filename); } /** * Saves the knowledge base to a file in a human-readable format * that can be read in with evaluate or wait statements. * @param filename the file to save the knowledge base to * @return the number of bytes written to the file **/ public long saveAsKarl(String filename) { return jni_saveAsKarl(getCPtr(), filename); } /** * Loads the knowledge base from a file * @param filename the file to load the knowledge base from * @param useId if true, read the unique ID from the file. If false, do not * use the unique ID from the file. * @param settings the settings for updating values in the context from file * @return the number of bytes read **/ public long loadContext(String filename, boolean useId, EvalSettings settings) { return jni_loadContext(getCPtr(), filename, useId, settings.getCPtr()); } /** * Saves a snapshot of changes to the context since the last saveContext, * saveCheckpoint, or sendModifieds. This is an incremental snapshot from * last time the modification list was cleared and can be much faster than * a saveContext. * @param filename the file to save the knowledge base changes to * @param resetModifieds if true, clear the modification list (this is a * bad idea if you should be sending modifications over a transport * as well as saving them to a file. * @return the number of bytes written to the file **/ public long saveCheckpoint(String filename, boolean resetModifieds) { return jni_saveCheckpoint(getCPtr(), filename, resetModifieds); } /** * Fills a {@link ai.madara.knowledge.KnowledgeMap KnowledgeMap} with * {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecords} that match an expression. * <br><br>The returned {@link ai.madara.knowledge.KnowledgeMap KnowledgeMap} * <b>must</b> be freed using {@link ai.madara.knowledge.KnowledgeMap#free KnowledgeMap.free ()} * before the object goes out of scope. * * @param expression An expression that matches the variable names that * are of interest. Wildcards may only be at the end * @return {@link ai.madara.knowledge.KnowledgeMap KnowledgeMap} containing the * requested {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecords} * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeMap toKnowledgeMap(String expression) { MapReturn jniRet = new MapReturn(); jni_toKnowledgeMap(getCPtr(), expression, jniRet); return new KnowledgeMap(jniRet.keys, jniRet.vals); } /** * Fills a {@link ai.madara.knowledge.KnowledgeMap KnowledgeMap} with * {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecords} that match a prefix and * suffix. * <br><br>The returned {@link ai.madara.knowledge.KnowledgeMap KnowledgeMap} * <b>must</b> be freed using {@link ai.madara.knowledge.KnowledgeMap#free KnowledgeMap.free ()} * before the object goes out of scope. * * @param prefix the prefix of the variables (e.g., in "{prefix}*{suffix}") * @param suffix the suffix of the variables (e.g., in "{prefix}*{suffix}") * @return {@link ai.madara.knowledge.KnowledgeMap KnowledgeMap} containing the * requested {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecords} * @throws KnowledgeBaseLockedException If called from a MadaraFunction **/ public KnowledgeMap toKnowledgeMap(String prefix, String suffix) { MapReturn jniRet = new MapReturn(); jni_toMap(getCPtr(), prefix, suffix, jniRet); return new KnowledgeMap(jniRet.keys, jniRet.vals); } /** * Prints the knowledge base to a string for debugging purposes * * @return string representation of the knowledge base **/ @Override public java.lang.String toString() { return jni_toString(getCPtr(), ", ", ";\n", "="); } /** * Prints the knowledge base to a string for debugging purposes * * @param arrayDelimiter delimiter to use between array elements * @param recordDelimiter delimiter to use in between records * @param keyvalDelimiter delimiter to use in between keys and values * @return string representation of the knowledge base **/ public java.lang.String toString(java.lang.String arrayDelimiter, java.lang.String recordDelimiter, java.lang.String keyvalDelimiter) { return jni_toString(getCPtr(), arrayDelimiter, recordDelimiter, keyvalDelimiter); } /** * Sets the log level to dictate the detail of MADARA logging. * * @param logLevel The log level to set **/ public static void setLogLevel(LogLevels logLevel) { GlobalLogger.setLevel(logLevel.value ()); } /** * Compiled, optimized KaRL logic. **/ public static class CompiledExpression extends MadaraJNI { private native void jni_freeCompiledExpression(long cptr); /** * Create a Java representation of a compiled expression * * @param cptr pointer to a C++ instance of CompiledExpression **/ public CompiledExpression(long cptr) { setCPtr(cptr); } /** * Deletes the C++ instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of KnowledgeBase gets garbage collected **/ public void free() { jni_freeCompiledExpression(getCPtr()); setCPtr(0); } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } } /** * KnowledgeBaseLockedException will be thrown if methods are called from inside a MadaraFunction **/ public class KnowledgeBaseLockedException extends RuntimeException { private static final long serialVersionUID = 2818595961365992639L; private KnowledgeBaseLockedException() { super(KnowledgeBase.this + " is currently locked. Are you invoking it from inside a MadaraFunction?"); } } static class MapReturn { public String[] keys; public long[] vals; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/KnowledgeList.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; import java.util.AbstractList; /** * KnowledgeList provides a read-only interface for KnowledgeRecords */ public class KnowledgeList extends AbstractList<KnowledgeRecord> { private native void jni_freeKnowledgeList(long[] records, int length); private long[] knowledgeRecords; public KnowledgeList() { knowledgeRecords = null; } public KnowledgeList(long[] records) { knowledgeRecords = records; } public KnowledgeList(KnowledgeRecord [] records) { knowledgeRecords = new long[records.length]; for (int i = 0; i < records.length; ++i) { knowledgeRecords[i] = records[i].getCPtr(); } } /** * @see java.util.AbstractList#get (int) */ @Override public KnowledgeRecord get(int index) { return KnowledgeRecord.fromPointer(knowledgeRecords[index], false); } /** * @see java.util.AbstractCollection#size () */ @Override public int size() { return knowledgeRecords == null ? 0 : knowledgeRecords.length; } /** * Returns the underlying C++ pointer array (useful for JNI) * @return the C++ pointer array underneath this instance **/ public long[] toPointerArray () { return knowledgeRecords; } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of {@link ai.madara.knowledge.KnowledgeList KnowledgeList} gets garbage collected */ public void free() { if (knowledgeRecords == null) return; jni_freeKnowledgeList(knowledgeRecords, knowledgeRecords.length); knowledgeRecords = null; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/KnowledgeMap.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; import java.util.AbstractMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class KnowledgeMap extends AbstractMap<String, KnowledgeRecord> { private native void jni_freeKnowledgeMap(long[] ptrs, int length); private Set<Map.Entry<String, KnowledgeRecord>> mySet; private final boolean freeable; public KnowledgeMap(String[] keys, long[] vals) { this(keys, vals, true); } public KnowledgeMap(String[] keys, long[] vals, boolean freeable) { this.freeable = freeable; if (keys == null || vals == null || keys.length != vals.length) return; mySet = new HashSet<Map.Entry<String, KnowledgeRecord>>(); for (int x = 0; x < keys.length; x++) { mySet.add(new KnowledgeMapEntry(keys[x], vals[x], freeable)); } } /** * @see java.util.AbstractMap#entrySet () */ @Override public Set<Map.Entry<String, KnowledgeRecord>> entrySet() { return mySet; } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of {@link ai.madara.knowledge.KnowledgeMap KnowledgeMap} gets garbage collected */ public void free() { if (!freeable) return; long[] ptrs = new long[mySet == null ? 0 : mySet.size()]; int pos = 0; for (Map.Entry<String, KnowledgeRecord> entry : mySet) { ptrs[pos++] = entry.getValue().getCPtr(); } jni_freeKnowledgeMap(ptrs, ptrs.length); mySet = null; } private static class KnowledgeMapEntry implements Map.Entry<String, KnowledgeRecord> { private String key; private KnowledgeRecord record; private KnowledgeMapEntry(String key, long val, boolean isNew) { this.key = key; record = KnowledgeRecord.fromPointer(val, isNew); } /** * @see java.util.Map.Entry#getKey () */ public String getKey() { return key; } /** * @see java.util.Map.Entry#getValue () */ public KnowledgeRecord getValue() { return record; } /** * @see java.util.Map.Entry#setValue (java.lang.Object) */ public KnowledgeRecord setValue(KnowledgeRecord value) { throw new UnsupportedOperationException("This map does not allow modification"); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/KnowledgeRecord.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; /** * This class encapsulates an entry in a KnowledgeBase. */ public class KnowledgeRecord extends MadaraJNI { //Constructors private native long jni_KnowledgeRecord(); private native long jni_KnowledgeRecordDeep(long ptr); private native long jni_KnowledgeRecord(String str); private native long jni_KnowledgeRecord(double str); private native long jni_KnowledgeRecord(long str); private static native long jni_KnowledgeRecord(double[] dbls); private static native long jni_KnowledgeRecord(long[] longs); //Getters private native long jni_toLongValue(long cptr); private native String jni_toStringValue(long cptr); private native double jni_toDoubleValue(long cptr); private static native double[] jni_toDoubleArray(long cptr); private static native long[] jni_toLongArray(long cptr); private native int jni_getType(long cptr); //Checks private native boolean jni_isValid(long cptr); //Free private native void jni_freeKnowledgeRecord(long cptr); private final boolean isNew; /** * No reason to ever create this without a pointer */ private KnowledgeRecord(boolean isNew) { this.isNew = isNew; } /** * Default constructor **/ public KnowledgeRecord() { isNew = true; setCPtr(jni_KnowledgeRecord()); } /** * Constructor for long/integer values * * @param lng value to set */ public KnowledgeRecord(long lng) throws MadaraDeadObjectException { isNew = true; setCPtr(jni_KnowledgeRecord(lng)); } /** * Constructor for string values * * @param str value to set */ public KnowledgeRecord(String str) throws MadaraDeadObjectException { isNew = true; setCPtr(jni_KnowledgeRecord(str)); } /** * Constructor for double values * * @param dbl value to set */ public KnowledgeRecord(double dbl) throws MadaraDeadObjectException { isNew = true; setCPtr(jni_KnowledgeRecord(dbl)); } /** * Constructor for double[] values * * @param dbls value to set */ public KnowledgeRecord(double[] dbls) throws MadaraDeadObjectException { isNew = true; setCPtr(jni_KnowledgeRecord(dbls)); } /** * Constructor for long[] values * * @param longs value to set */ public KnowledgeRecord(long[] longs) throws MadaraDeadObjectException { isNew = true; setCPtr(jni_KnowledgeRecord(longs)); } /** * Checks if the record is valid or uncreated * * @return true if record has a value, false otherwise. */ public boolean isValid() throws MadaraDeadObjectException { return jni_isValid(getCPtr()); } /** * Converts the value to a long * * @return current long value */ public long toLong() throws MadaraDeadObjectException { return jni_toLongValue(getCPtr()); } /** * Converts the value to a float/double * * @return current double value */ public double toDouble() throws MadaraDeadObjectException { return jni_toDoubleValue(getCPtr()); } /** * Converts the value to a double array * * @return current array values */ public double[] toDoubleArray() throws MadaraDeadObjectException { return jni_toDoubleArray(getCPtr()); } /** * Converts the value to a long array * * @return current array values */ public long[] toLongArray() throws MadaraDeadObjectException { return jni_toLongArray(getCPtr()); } /** * Converts the value to a String * * @return current string value */ public String toString() { return jni_toStringValue(getCPtr()); } /** * @return the {@link ai.madara.knowledge.KnowledgeType KnowledgeType} of the value */ public KnowledgeType getType() throws MadaraDeadObjectException { return KnowledgeType.getType(jni_getType(getCPtr())); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of KnowledgeRecord gets garbage collected */ public void free() throws MadaraDeadObjectException { jni_freeKnowledgeRecord(getCPtr()); setCPtr(0); } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } /** * Creates a {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecord} from a pointer * * @param cptr C pointer to a KnowledgeRecord object * @return new KnowledgeRecord */ public static KnowledgeRecord fromPointer(long cptr) { return fromPointer(cptr, true); } /** * Creates a {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecord} from a pointer * * @param cptr C pointer to a KnowledgeRecord object * @param isNew indicates if the record is meant to be managed * @return new KnowledgeRecord */ public static KnowledgeRecord fromPointer(long cptr, boolean isNew) { KnowledgeRecord ret = new KnowledgeRecord(isNew); ret.setCPtr(cptr); return ret; } /** * Will return true if this object was malloced * @return true if the object must manage itself, false if not */ public boolean isNew() { return isNew; } public KnowledgeRecord clone() { KnowledgeRecord ret = new KnowledgeRecord(true); ret.setCPtr(jni_KnowledgeRecordDeep(this.getCPtr())); return ret; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/KnowledgeType.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; /** * Type of {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecord} */ public enum KnowledgeType { //These are defined in Knowledge_Record.h UNINITIALIZED(0), INTEGER(1), STRING(2), DOUBLE(4), FLOAT(4), UNKNOWN_FILE_TYPE(8), XML(16), TEXT_FILE(32), INTEGER_ARRAY(64), DOUBLE_ARRAY(128), IMAGE_JPEG(256), ALL_PRIMITIVE_TYPES(INTEGER.num | STRING.num | DOUBLE.num | INTEGER_ARRAY.num | DOUBLE_ARRAY.num), ALL_FILE_TYPES(UNKNOWN_FILE_TYPE.num | XML.num | TEXT_FILE.num | IMAGE_JPEG.num), ALL_TYPES(ALL_PRIMITIVE_TYPES.num | ALL_FILE_TYPES.num); private int num; private KnowledgeType(int num) { this.num = num; } /** * @return int value of this {@link ai.madara.knowledge.KnowledgeType KnowledgeType} */ public int value() { return num; } /** * Converts an int to a {@link ai.madara.knowledge.KnowledgeType KnowledgeType} * * @param val value to convert * @return {@link ai.madara.knowledge.KnowledgeType KnowledgeType} or null if the int is invalid */ public static KnowledgeType getType(int val) { for (KnowledgeType t : values()) { if (t.value() == val) return t; } return null; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/MadaraFunction.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; /** * Interface for defining a Java method to be executed by MADARA */ public interface MadaraFunction { /** * Java implementation of a MADARA function. <b>DO NOT</b> invoke methods on an instance of * {@link ai.madara.knowledge.KnowledgeBase KnowledgeBase} in this method * * @param args {@link java.util.List List&lt;KnowledgeRecord&gt;} of arguments passed to the function * @param variables Local access to evaluate and compile methods * @return A {@link ai.madara.knowledge.KnowledgeRecord KnowledgeRecord} containing the result of the function */ public KnowledgeRecord execute(KnowledgeList args, Variables variables); }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/UpdateSettings.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; /** * Encapsulates settings for updating the knowledge base. */ public class UpdateSettings extends MadaraJNI { //Constructors private static native long jni_updateSettings(); private static native long jni_updateSettings(long oldPtr); //Getters/Setters private static native void jni_setAlwaysOverwrite(long cptr, boolean alwaysOverwrite); private static native boolean jni_getAlwaysOverwrite(long cptr); private static native void jni_setTreatGlobalsAsLocals(long cptr, boolean treatGlobalsAsLocals); private static native boolean jni_getTreatGlobalsAsLocals(long cptr); private static native void jni_setClockIncrement(long cptr, long defaultClockIncrement); private static native long jni_getClockIncrement(long cptr); private static native void jni_freeUpdateSettings(long cptr); /** * Default constructor */ public UpdateSettings() { setCPtr(jni_updateSettings()); } /** * Copy constructor * * @param input the settings to copy from */ public UpdateSettings(UpdateSettings input) { setCPtr(jni_updateSettings(input.getCPtr())); } /** * Constructor to create constants * * @param cptr Pointer to C++ object */ protected UpdateSettings(long cptr) { setCPtr(cptr); } /** * @param treatGlobalsAsLocals Toggle whether updates to global variables are * treated as local variables and not marked as modified to the transport. */ public void setTreatGlobalsAsLocals(boolean treatGlobalsAsLocals) throws MadaraDeadObjectException { jni_setTreatGlobalsAsLocals(getCPtr(), treatGlobalsAsLocals); } /** * @return current value of treatGlobalsAsLocals */ public boolean getTreatGlobalsAsLocals() throws MadaraDeadObjectException { return jni_getTreatGlobalsAsLocals(getCPtr()); } /** * @param defaultClockIncrement Default clock increment. */ public void setDefaultClockIncrement(long defaultClockIncrement) throws MadaraDeadObjectException { jni_setClockIncrement(getCPtr(), defaultClockIncrement); } /** * @return get the default clock increment */ public long getDefaultClockIncrement() throws MadaraDeadObjectException { return jni_getClockIncrement(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of UpdateSettings gets garbage collected */ public void free() { jni_freeUpdateSettings(getCPtr()); setCPtr(0); } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/Variables.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase.CompiledExpression; /** * Provides an interface for external functions into the MADARA KaRL variable settings. */ public class Variables extends MadaraJNI { private native long jni_evaluate(long cptr, long expression, long evalSettings); private native long jni_compile(long cptr, String expression); private native long jni_get(long cptr, String name); private native void jni_set(long cptr, String name, long record); /** * {@link ai.madara.knowledge.Variables Variables} should only be created from a pointer */ private Variables() { } /** * Creates a {@link ai.madara.knowledge.Variables Variables} from a pointer * * @param cptr C pointer to a Variables object * @return new {@link ai.madara.knowledge.Variables Variables} */ public static Variables fromPointer(long cptr) { Variables ret = new Variables(); ret.setCPtr(cptr); return ret; } /** * Evaluates an expression. * The returned KnowledgeRecord should either be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) or returned * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @return value of expression */ public KnowledgeRecord evaluate(CompiledExpression expression) { return evaluate(expression, EvalSettings.DEFAULT_EVAL_SETTINGS); } /** * Evaluates an expression. * The returned KnowledgeRecord should either be freed ({@link ai.madara.knowledge.KnowledgeRecord#free () KnowledgeRecord.free ()}) or returned * * @param expression KaRL expression to evaluate (result of {@link #compile (String)}) * @param evalSettings Settings for evaluating and printing * @return value of expression */ public KnowledgeRecord evaluate(CompiledExpression expression, EvalSettings evalSettings) { return KnowledgeRecord.fromPointer(jni_evaluate(getCPtr(), expression.getCPtr(), evalSettings.getCPtr())); } /** * Compiles a KaRL expression into an expression tree. * * @param expression expression to compile * @return {@link ai.madara.knowledge.KnowledgeBase.CompiledExpression CompiledExpression}: compiled, optimized expression tree */ public CompiledExpression compile(String expression) { return new CompiledExpression(jni_compile(getCPtr(), expression)); } /** * Retrieves a knowledge value. * * @param name knowledge name * @return value of knowledge */ public KnowledgeRecord get(String name) { return KnowledgeRecord.fromPointer(jni_get(getCPtr(), name)); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param record value to set */ public void set(String name, KnowledgeRecord record) { jni_set(getCPtr(), name, record.getCPtr()); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @throws MadaraDeadObjectException */ public void set(String name, long value) throws MadaraDeadObjectException { KnowledgeRecord kr = new KnowledgeRecord(value); set(name, kr); kr.free(); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @throws MadaraDeadObjectException */ public void set(String name, double value) throws MadaraDeadObjectException { KnowledgeRecord kr = new KnowledgeRecord(value); set(name, kr); kr.free(); } /** * Sets a knowledge value to a specified value. * * @param name knowledge name * @param value value to set * @throws MadaraDeadObjectException */ public void set(String name, String value) throws MadaraDeadObjectException { KnowledgeRecord kr = new KnowledgeRecord(value); set(name, kr); kr.free(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/WaitSettings.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge; import ai.madara.exceptions.MadaraDeadObjectException; /** * Encapsulates settings for a wait statement. */ public class WaitSettings extends EvalSettings { //Constructors private static native long jni_waitSettings(); private static native long jni_waitSettings(long oldPtr); //Setters/Getters private static native void jni_setPollFrequency(long cptr, double freq); private static native double jni_getPollFrequency(long cptr); private static native void jni_setMaxWaitTime(long cptr, double maxWaitTime); private static native double jni_getMaxWaitTime(long cptr); private static native void jni_freeWaitSettings(long cptr); public static WaitSettings DEFAULT_WAIT_SETTINGS = new WaitSettings(jni_waitSettings()); /** * Default constructor */ public WaitSettings() { setCPtr(jni_waitSettings()); } /** * Copy constructor * * @param waitSettings settings to be copied */ public WaitSettings(WaitSettings waitSettings) { setCPtr(jni_waitSettings(waitSettings.getCPtr())); } /** * C pointer constructor * * @param cptr the C ptr to be inherited */ protected WaitSettings(long cptr) { super(cptr); } /** * @param freq Frequency to poll an expression for truth. */ public void setPollFrequency(double freq) throws MadaraDeadObjectException { jni_setPollFrequency(getCPtr(), freq); } /** * @return current poll frequency */ public double getPollFrequency() throws MadaraDeadObjectException { return jni_getPollFrequency(getCPtr()); } /** * @param maxWaitTime Maximum time to wait for an expression to become true. */ public void setMaxWaitTime(double maxWaitTime) throws MadaraDeadObjectException { jni_setMaxWaitTime(getCPtr(), maxWaitTime); } /** * @return current max wait time */ public double getMaxWaitTime() throws MadaraDeadObjectException { return jni_getMaxWaitTime(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of WaitSettings gets garbage collected */ public void free() { jni_freeWaitSettings(getCPtr()); setCPtr(0); } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/Barrier.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a distributed barrier within a knowledge base **/ public class Barrier extends BaseContainer { private native long jni_Barrier(); private native long jni_Barrier(long cptr); private static native void jni_freeBarrier(long cptr); private native void jni_set(long cptr, long value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name, int id, int participants); private native java.lang.String jni_toString(long cptr); private native double jni_toDouble(long cptr); private native long jni_toLong(long cptr); private native long jni_next(long cptr); private native boolean jni_isDone(long cptr); private native void jni_modify(long cptr); private native void jni_resize(long cptr, int id, int participants); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public Barrier() { setCPtr(jni_Barrier()); } /** * Copy constructor * @param input instance to copy **/ public Barrier(Barrier input) { setCPtr(jni_Barrier(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Barrier fromPointer(long cptr) { Barrier ret = new Barrier(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Barrier fromPointer(long cptr, boolean shouldManage) { Barrier ret = new Barrier(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value * * @return current value */ public long get() throws MadaraDeadObjectException { return jni_toLong(getCPtr()); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Moves to the next barrier */ public void next() throws MadaraDeadObjectException { jni_next(getCPtr()); } /** * Checks to see if the barrier round is done * @return new value of the container */ public boolean isDone() throws MadaraDeadObjectException { return jni_isDone(getCPtr()); } /** * Mark the value as modified. The Barrier retains the same value * but will resend its value as if it had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Resizes the barrier, usually when number of participants change * @param id the id of this barrier in the barrier ring * @param participants the number of participants in barrier ring **/ public void resize(int id, int participants) throws MadaraDeadObjectException { jni_resize(getCPtr(), id, participants); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name * @param id the id of the barrier in the barrier ring * @param participants the number of participants in the barrier ring */ public void setName(KnowledgeBase kb, java.lang.String name, int id, int participants) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name, id, participants); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name * @param id the id of the barrier in the barrier ring * @param participants the number of participants in the barrier ring */ public void setName(Variables vars, java.lang.String name, int id, int participants) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name, id, participants); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Converts the value to a double * * @return current double value */ public double toDouble() throws MadaraDeadObjectException { return jni_toDouble(getCPtr()); } /** * Converts the value to a long * * @return current long value */ public long toLong() throws MadaraDeadObjectException { return jni_toLong(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Converts the value to a string * * @return current string value */ @Override public java.lang.String toString() { return jni_toString(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeBarrier(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/BaseContainer.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; /** * A base class for all containers **/ public abstract class BaseContainer extends MadaraJNI { private native boolean jni_modifyIfTrue(long cptr, long container); private native boolean jni_modifyIfFalse(long cptr, long container); /** * Marks the container as modified if the container ends up being true * @param container the container that might evaluate to true * @return true if the container evaluated to true **/ public boolean modifyIfTrue(BaseContainer container) throws MadaraDeadObjectException { return jni_modifyIfTrue(getCPtr(), container.getCPtr()); } /** * Marks the container as modified if the container ends up being true * @param container the container that might evaluate to true * @return true if the container evaluated to false **/ public boolean modifyIfFalse(BaseContainer container) throws MadaraDeadObjectException { return jni_modifyIfFalse(getCPtr(), container.getCPtr()); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/Collection.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.UpdateSettings; /** * A facade for a collection of knowledge base containers **/ public class Collection extends BaseContainer { private native long jni_Collection(); private native long jni_Collection(long cptr); private static native void jni_freeCollection(long cptr); private native java.lang.String jni_getDebugInfo(long cptr); private native void jni_modify(long cptr); private native void jni_setSettings(long cptr, long settings); private native void jni_addBarrier(long cptr, long container); private native void jni_addCounter(long cptr, long container); private native void jni_addDouble(long cptr, long container); private native void jni_addDoubleVector(long cptr, long container); private native void jni_addFlexMap(long cptr, long container); private native void jni_addInteger(long cptr, long container); private native void jni_addIntegerVector(long cptr, long container); private native void jni_addMap(long cptr, long container); private native void jni_addNativeDoubleVector(long cptr, long container); private native void jni_addNativeIntegerVector(long cptr, long container); private native void jni_addString(long cptr, long container); private native void jni_addStringVector(long cptr, long container); private native void jni_addVector(long cptr, long container); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public Collection() { setCPtr(jni_Collection()); } /** * Copy constructor * @param input instance to copy **/ public Collection(Collection input) { setCPtr(jni_Collection(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Collection fromPointer(long cptr) { Collection ret = new Collection(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Collection fromPointer(long cptr, boolean shouldManage) { Collection ret = new Collection(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Mark the value as modified. The Collection retains the same value * but will resend its value as if it had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Reads all debug info for the collection into a string * * @return aggregate debug information for the collection */ @Override public java.lang.String toString() { return jni_getDebugInfo(getCPtr()); } /** * Adds a Barrier container to the collection * @param container the container to add to the collection */ public void add(Barrier container) throws MadaraDeadObjectException { jni_addBarrier(getCPtr(), container.getCPtr()); } /** * Adds a Counter container to the collection * @param container the container to add to the collection */ public void add(Counter container) throws MadaraDeadObjectException { jni_addCounter(getCPtr(), container.getCPtr()); } /** * Adds a Double container to the collection * @param container the container to add to the collection */ public void add(Double container) throws MadaraDeadObjectException { jni_addDouble(getCPtr(), container.getCPtr()); } /** * Adds a DoubleVector container to the collection * @param container the container to add to the collection */ public void add(DoubleVector container) throws MadaraDeadObjectException { jni_addDoubleVector(getCPtr(), container.getCPtr()); } /** * Adds a FlexMap container to the collection * @param container the container to add to the collection */ public void add(FlexMap container) throws MadaraDeadObjectException { jni_addFlexMap(getCPtr(), container.getCPtr()); } /** * Adds a Integer container to the collection * @param container the container to add to the collection */ public void add(Integer container) throws MadaraDeadObjectException { jni_addInteger(getCPtr(), container.getCPtr()); } /** * Adds a IntegerVector container to the collection * @param container the container to add to the collection */ public void add(IntegerVector container) throws MadaraDeadObjectException { jni_addIntegerVector(getCPtr(), container.getCPtr()); } /** * Adds a Map container to the collection * @param container the container to add to the collection */ public void add(Map container) throws MadaraDeadObjectException { jni_addMap(getCPtr(), container.getCPtr()); } /** * Adds a NativeDoubleVector container to the collection * @param container the container to add to the collection */ public void add(NativeDoubleVector container) throws MadaraDeadObjectException { jni_addNativeDoubleVector(getCPtr(), container.getCPtr()); } /** * Adds a NativeIntegerVector container to the collection * @param container the container to add to the collection */ public void add(NativeIntegerVector container) throws MadaraDeadObjectException { jni_addNativeIntegerVector(getCPtr(), container.getCPtr()); } /** * Adds a String container to the collection * @param container the container to add to the collection */ public void add(String container) throws MadaraDeadObjectException { jni_addString(getCPtr(), container.getCPtr()); } /** * Adds a StringVector container to the collection * @param container the container to add to the collection */ public void add(StringVector container) throws MadaraDeadObjectException { jni_addStringVector(getCPtr(), container.getCPtr()); } /** * Adds a Vector container to the collection * @param container the container to add to the collection */ public void add(Vector container) throws MadaraDeadObjectException { jni_addVector(getCPtr(), container.getCPtr()); } /** * Reads all debug info for the collection into a string * * @return aggregate debug information for the collection */ public java.lang.String getDebugInfo() throws MadaraDeadObjectException { return jni_getDebugInfo(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeCollection(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/Counter.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for distributed adder within a knowledge base **/ public class Counter extends BaseContainer { private native long jni_Counter(); private native long jni_Counter(long cptr); private static native void jni_freeCounter(long cptr); private native void jni_set(long cptr, long value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native java.lang.String jni_toString(long cptr); private native double jni_toDouble(long cptr); private native long jni_toLong(long cptr); private native void jni_inc(long cptr); private native void jni_dec(long cptr); private native void jni_incValue(long cptr, long value); private native void jni_decValue(long cptr, long value); private native void jni_modify(long cptr); private native void jni_resize(long cptr, int id, int counters); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public Counter() { setCPtr(jni_Counter()); } /** * Copy constructor * @param input instance to copy **/ public Counter(Counter input) { setCPtr(jni_Counter(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Counter fromPointer(long cptr) { Counter ret = new Counter(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Counter fromPointer(long cptr, boolean shouldManage) { Counter ret = new Counter(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value * * @return current value */ public long get() throws MadaraDeadObjectException { return jni_toLong(getCPtr()); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Increments the container */ public void inc() throws MadaraDeadObjectException { jni_inc(getCPtr()); } /** * Increments by a value * * @param value value to increment by */ public void inc(long value) throws MadaraDeadObjectException { jni_incValue(getCPtr(), value); } /** * Decrements the container */ public void dec() throws MadaraDeadObjectException { jni_dec(getCPtr()); } /** * Decrements by a value * * @param value value to increment by */ public void dec(long value) throws MadaraDeadObjectException { jni_decValue(getCPtr(), value); } /** * Sets the value * * @param value new value */ public void set(long value) throws MadaraDeadObjectException { jni_set(getCPtr(), value); } /** * Mark the value as modified. The Counter retains the same value * but will resend its value as if it had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Resizes the counter, usually when number of counters change * @param id the id of this counter in the counter ring * @param counters the number of counters in counter ring **/ public void resize(int id, int counters) throws MadaraDeadObjectException { jni_resize(getCPtr(), id, counters); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Converts the value to a double * * @return current double value */ public double toDouble() throws MadaraDeadObjectException { return jni_toDouble(getCPtr()); } /** * Converts the value to a long * * @return current long value */ public long toLong() throws MadaraDeadObjectException { return jni_toLong(getCPtr()); } /** * Converts the value to a string * * @return current string value */ @Override public java.lang.String toString() { return jni_toString(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeCounter(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/Double.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a double value within a knowledge base **/ public class Double extends BaseContainer { private native long jni_Double(); private native long jni_Double(long cptr); private static native void jni_freeDouble(long cptr); private native void jni_set(long cptr, double value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native java.lang.String jni_toString(long cptr); private native double jni_toDouble(long cptr); private native long jni_toLong(long cptr); private native void jni_modify(long cptr); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public Double() { setCPtr(jni_Double()); } /** * Copy constructor * @param input instance to copy **/ public Double(Double input) { setCPtr(jni_Double(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Double fromPointer(long cptr) { Double ret = new Double(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Double fromPointer(long cptr, boolean shouldManage) { Double ret = new Double(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value * * @return current value */ public double get() throws MadaraDeadObjectException { return jni_toDouble(getCPtr()); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Sets the value * * @param value new value */ public void set(double value) throws MadaraDeadObjectException { jni_set(getCPtr(), value); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Mark the value as modified. The Double retains the same value * but will resend its value as if it had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Converts the value to a double * * @return current double value */ public double toDouble() throws MadaraDeadObjectException { return jni_toDouble(getCPtr()); } /** * Converts the value to a long * * @return current long value */ public long toLong() throws MadaraDeadObjectException { return jni_toLong(getCPtr()); } /** * Converts the value to a string * * @return current string value */ @Override public java.lang.String toString() { return jni_toString(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeDouble(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/DoubleVector.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a vector of doubles within a knowledge base. Changing * elements of a DoubleVector only sends updates on that subset of changed * values, rather than the entire vector. If you are wanting all elements of * a vector to be sent atomically, you are probably wanting to use * NativeDoubleVector, which operates on a single knowledge record * location within the knowledge base. **/ public class DoubleVector extends BaseContainer { private native long jni_DoubleVector(); private native long jni_DoubleVector(long cptr); private static native void jni_freeDoubleVector(long cptr); private native void jni_set(long cptr, int index, double value); private native void jni_pushback(long cptr, double value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native double jni_get(long cptr, int index); private native long jni_toRecord(long cptr, int index); private native long jni_toRecord(long cptr); private native Object[] jni_toArray(long cptr); private native long jni_size(long cptr); private native void jni_resize(long cptr, long length); private native void jni_modify(long cptr); private native void jni_modifyIndex(long cptr, int index); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public DoubleVector() { setCPtr(jni_DoubleVector()); } /** * Copy constructor * @param input instance to copy **/ public DoubleVector(DoubleVector input) { setCPtr(jni_DoubleVector(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static DoubleVector fromPointer(long cptr) { DoubleVector ret = new DoubleVector(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static DoubleVector fromPointer(long cptr, boolean shouldManage) { DoubleVector ret = new DoubleVector(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value at the specified index * @param index index of the record to retrieve * @return current value */ public double get(int index) throws MadaraDeadObjectException { return jni_get(getCPtr(), index); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Mark the vector as modified. The vector retains the same values * but will resend all values as if they had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Mark an element as modified. The element retains the same value * but will resend the value as if it had been modified. * @param index the element index **/ public void modify(int index) throws MadaraDeadObjectException { jni_modifyIndex(getCPtr(), index); } /** * Resizes the vector. A negative number (e.g. -1) can be * provided to automatically resize the vector to whatever * size is indicated in the knowledge base. * * @param length new number of elements of the vector */ public void resize (long length) throws MadaraDeadObjectException { jni_resize(getCPtr(), length); } /** * Sets the value of an element of the vector * @param index index to set the value at * @param value new value */ public void set(int index, double value) throws MadaraDeadObjectException { jni_set(getCPtr(), index, value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(double value) throws MadaraDeadObjectException { jni_pushback(getCPtr(), value); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns the size of the vector * * @return the number of elements in the vector */ public long size () throws MadaraDeadObjectException { return jni_size(getCPtr()); } /** * Returns a value at the specified index * * @return the vector as an array of records */ public KnowledgeRecord[] toArray() throws MadaraDeadObjectException { Object[] objs = jni_toArray(getCPtr()); KnowledgeRecord[] records = new KnowledgeRecord[objs.length]; for (int i = 0; i < objs.length; ++i) { records[i] = (KnowledgeRecord)objs[i]; } return records; } /** * Returns a value at the specified index * * @param index the index * @return the value at the index as a knowledge record */ public KnowledgeRecord toRecord(int index) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), index)); } /** * Returns all of the values as a knowledge record * * @return knowledge record that contains all indices */ public KnowledgeRecord toRecord() throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr())); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeDoubleVector(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/FlexMap.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a map of variable names to values within a knowledge base **/ public class FlexMap extends BaseContainer { private native long jni_FlexMap(); private native long jni_FlexMap(long cptr); private static native void jni_freeFlexMap(long cptr); private native void jni_clear(long cptr); private native void jni_erase(long cptr, java.lang.String key); private native java.lang.String jni_getDelimiter(long cptr); private native void jni_setDelimiter(long cptr, java.lang.String delimiter); private native void jni_setString(long cptr, java.lang.String value); private native void jni_setDouble(long cptr, double value); private native void jni_set(long cptr, long type, long value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native java.lang.String[] jni_keys(long cptr, boolean firstLevel); private native long jni_get(long cptr, java.lang.String key); private native long jni_getIndex(long cptr, int index); private native long jni_toRecord(long cptr); private native void jni_modify(long cptr); private native long jni_toMapContainer(long cptr); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public FlexMap() { setCPtr(jni_FlexMap()); } /** * Copy constructor * @param input instance to copy **/ public FlexMap(FlexMap input) { setCPtr(jni_FlexMap(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static FlexMap fromPointer(long cptr) { FlexMap ret = new FlexMap(); ret.setCPtr(cptr); ret.manageMemory = true; return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static FlexMap fromPointer(long cptr, boolean shouldManage) { FlexMap ret = new FlexMap(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets all keys in the map * * @return all keys in the map */ public java.lang.String[] keys() throws MadaraDeadObjectException { return jni_keys(getCPtr(),false); } /** * Gets keys in the map, with option to get only first level keys * * @param firstLevel if true, only return the immediate subkeys and not * full key names * @return the keys in the map */ public java.lang.String[] keys(boolean firstLevel) throws MadaraDeadObjectException { return jni_keys(getCPtr(),firstLevel); } /** * Creates a FlexMap at the keyed location * * @param key the next level of the FlexMap * @return FlexMap pointing to the keyed location */ public FlexMap get(java.lang.String key) throws MadaraDeadObjectException { return FlexMap.fromPointer(jni_get(getCPtr(), key)); } /** * Creates a FlexMap at the indexed location * * @param index an index into the FlexMap * @return FlexMap pointing to the indexed location */ public FlexMap get(int index) throws MadaraDeadObjectException { return FlexMap.fromPointer(jni_getIndex(getCPtr(), index)); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Gets the delimiter that separates the name of the map with its elements * * @return the delimiter that separates map name with elements */ public java.lang.String getDelimiter() throws MadaraDeadObjectException { return jni_getDelimiter(getCPtr()); } /** * Sets the delimiter that separates the name of the map with its elements * * @param delimiter the separator between the map and elements */ public void setDelimiter(java.lang.String delimiter) throws MadaraDeadObjectException { jni_setDelimiter(getCPtr(), delimiter); } /** * Mark the map as modified. The maps retains the same values * but will resend all values as if they had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Clears the variables in the map **/ public void clear() throws MadaraDeadObjectException { jni_clear(getCPtr()); } /** * Erases a variable located at key in the map. This also deletes the variable * from the knowledge base. * @param key the element key **/ public void erase(java.lang.String key) throws MadaraDeadObjectException { jni_erase(getCPtr(), key); } /** * Sets the location to a string * * @param value new value */ public void set(java.lang.String value) throws MadaraDeadObjectException { jni_setString(getCPtr(), value); } /** * Sets the location to a double * * @param value new value */ public void set(double value) throws MadaraDeadObjectException { jni_setDouble(getCPtr(), value); } /** * Sets the location to an integer value * * @param value new value */ public void set(long value) throws MadaraDeadObjectException { jni_set(getCPtr(), 0, value); } /** * Sets the location to a KnowledgeRecord value * * @param key the location within the virtual map * @param value new value */ public void set(java.lang.String key, KnowledgeRecord value) throws MadaraDeadObjectException { jni_set(getCPtr(), 1, value.getCPtr ()); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns a value at the specified key * * @return the value at the index as a knowledge record */ public KnowledgeRecord toRecord() throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr())); } /** * Creates a Map container from the current location. Maps maintain lists * of keys and are more appropriate for frequent accesses of sub keys (i.e., * they are better performance, while FlexMap is more flexible). * * @return the value at the index as a knowledge record */ public Map toMapContainer() throws MadaraDeadObjectException { return Map.fromPointer(jni_toMapContainer(getCPtr())); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeFlexMap(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/Integer.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for an integer value within a knowledge base **/ public class Integer extends BaseContainer { private native long jni_Integer(); private native long jni_Integer(long cptr); private static native void jni_freeInteger(long cptr); private native void jni_set(long cptr, long value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native java.lang.String jni_toString(long cptr); private native double jni_toDouble(long cptr); private native long jni_toLong(long cptr); private native long jni_inc(long cptr); private native long jni_dec(long cptr); private native long jni_incValue(long cptr, long value); private native long jni_decValue(long cptr, long value); private native void jni_modify(long cptr); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public Integer() { setCPtr(jni_Integer()); } /** * Copy constructor * @param input instance to copy **/ public Integer(Integer input) { setCPtr(jni_Integer(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Integer fromPointer(long cptr) { Integer ret = new Integer(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Integer fromPointer(long cptr, boolean shouldManage) { Integer ret = new Integer(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value * * @return current value */ public long get() throws MadaraDeadObjectException { return jni_toLong(getCPtr()); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Increments the container * * @return new value of the container */ public long inc() throws MadaraDeadObjectException { return jni_inc(getCPtr()); } /** * Increments by a value * * @param value value to increment by * @return new value of the container */ public long inc(long value) throws MadaraDeadObjectException { return jni_incValue(getCPtr(), value); } /** * Decrements the container * * @return new value of the container */ public long dec() throws MadaraDeadObjectException { return jni_dec(getCPtr()); } /** * Decrements by a value * * @param value value to increment by * @return new value of the container */ public long dec(long value) throws MadaraDeadObjectException { return jni_decValue(getCPtr(), value); } /** * Sets the value * * @param value new value */ public void set(long value) throws MadaraDeadObjectException { jni_set(getCPtr(), value); } /** * Mark the value as modified. The Integer retains the same value * but will resend its value as if it had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Converts the value to a double * * @return current double value */ public double toDouble() throws MadaraDeadObjectException { return jni_toDouble(getCPtr()); } /** * Converts the value to a long * * @return current long value */ public long toLong() throws MadaraDeadObjectException { return jni_toLong(getCPtr()); } /** * Converts the value to a string * * @return current string value */ @Override public java.lang.String toString() { return jni_toString(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeInteger(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/IntegerVector.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a vector of integers within a knowledge base. Changing * elements of a IntegerVector only sends updates on that subset of changed * values, rather than the entire vector. If you are wanting all elements of * a vector to be sent atomically, you are probably wanting to use * NativeIntegerVector, which operates on a single knowledge record * location within the knowledge base. **/ public class IntegerVector extends BaseContainer { private native long jni_IntegerVector(); private native long jni_IntegerVector(long cptr); private static native void jni_freeIntegerVector(long cptr); private native void jni_set(long cptr, int index, long value); private native void jni_pushback(long cptr, long value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native long jni_get(long cptr, int index); private native long jni_toRecord(long cptr, int index); private native long jni_toRecord(long cptr); private native Object[] jni_toArray(long cptr); private native long jni_size(long cptr); private native void jni_resize(long cptr, long length); private native void jni_modify(long cptr); private native void jni_modifyIndex(long cptr, int index); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public IntegerVector() { setCPtr(jni_IntegerVector()); } /** * Copy constructor * @param input instance to copy **/ public IntegerVector(IntegerVector input) { setCPtr(jni_IntegerVector(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static IntegerVector fromPointer(long cptr) { IntegerVector ret = new IntegerVector(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static IntegerVector fromPointer(long cptr, boolean shouldManage) { IntegerVector ret = new IntegerVector(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value at a specified index * @param index location of the element to retrieve * @return current value */ public long get(int index) throws MadaraDeadObjectException { return jni_get(getCPtr(), index); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Resizes the vector. A negative number (e.g. -1) can be * provided to automatically resize the vector to whatever * size is indicated in the knowledge base. * * @param length new number of elements of the vector */ public void resize (long length) throws MadaraDeadObjectException { jni_resize(getCPtr(), length); } /** * Sets the value at an index * @param index index to set a value at * @param value new value */ public void set(int index, long value) throws MadaraDeadObjectException { jni_set(getCPtr(), index, value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(long value) throws MadaraDeadObjectException { jni_pushback(getCPtr(), value); } /** * Mark the vector as modified. The vector retains the same values * but will resend all values as if they had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Mark an element as modified. The element retains the same value * but will resend the value as if it had been modified. * @param index the element index **/ public void modify(int index) throws MadaraDeadObjectException { jni_modifyIndex(getCPtr(), index); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns the size of the vector * * @return the number of elements in the vector */ public long size () throws MadaraDeadObjectException { return jni_size(getCPtr()); } /** * Returns a value at the specified index * * @param index the index * @return the value at the index as a knowledge record */ public KnowledgeRecord toRecord(int index) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), index)); } /** * Returns a value at the specified index * * @return the vector as an array of records */ public KnowledgeRecord[] toArray() throws MadaraDeadObjectException { Object[] objs = jni_toArray(getCPtr()); KnowledgeRecord[] records = new KnowledgeRecord[objs.length]; for (int i = 0; i < objs.length; ++i) { records[i] = (KnowledgeRecord)objs[i]; } return records; } /** * Returns all of the values as a knowledge record * * @return knowledge record that contains all indices */ public KnowledgeRecord toRecord() throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr())); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeIntegerVector(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/Map.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a map of variable names to values within a knowledge base **/ public class Map extends BaseContainer { private native long jni_Map(); private native long jni_Map(long cptr); private static native void jni_freeMap(long cptr); private native void jni_clear(long cptr, boolean erase_variables); private native void jni_erase(long cptr, java.lang.String key); private native void jni_setString(long cptr, java.lang.String key, java.lang.String value); private native void jni_setDouble(long cptr, java.lang.String key, double value); private native void jni_set(long cptr, java.lang.String key, long type, long value); private native java.lang.String jni_getDelimiter(long cptr); private native void jni_setDelimiter(long cptr, java.lang.String delimiter); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native long jni_get(long cptr, java.lang.String key); private native long jni_toRecord(long cptr, java.lang.String key); private native java.lang.String[] jni_keys(long cptr); private native void jni_sync(long cptr); private native void jni_modify(long cptr); private native void jni_modifyIndex(long cptr, java.lang.String index); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public Map() { setCPtr(jni_Map()); } /** * Copy constructor * @param input instance to copy **/ public Map(Map input) { setCPtr(jni_Map(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Map fromPointer(long cptr) { Map ret = new Map(); ret.setCPtr(cptr); ret.manageMemory = true; return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Map fromPointer(long cptr, boolean shouldManage) { Map ret = new Map(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value * * @param key the location in the map * @return current value */ public KnowledgeRecord get(java.lang.String key) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), key)); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Gets the delimiter that separates the name of the map with its elements * * @return the delimiter that separates map name with elements */ public java.lang.String getDelimiter() throws MadaraDeadObjectException { return jni_getDelimiter(getCPtr()); } /** * Sets the delimiter that separates the name of the map with its elements * * @param delimiter the separator between the map and elements */ public void setDelimiter(java.lang.String delimiter) throws MadaraDeadObjectException { jni_setDelimiter(getCPtr(), delimiter); } /** * Gets the current keys in the map * * @return name of the variable within the context */ public java.lang.String[] keys() throws MadaraDeadObjectException { return jni_keys(getCPtr()); } /** * Syncs the map to the underlying knowledge base. Call this method * if you believe the map's keys may have changed in the knowledge base. */ public void sync() throws MadaraDeadObjectException { jni_sync(getCPtr()); } /** * Mark the map as modified. The maps retains the same values * but will resend all values as if they had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Mark an element as modified. The element retains the same value * but will resend the value as if it had been modified. * @param key the element key **/ public void modify(java.lang.String key) throws MadaraDeadObjectException { jni_modifyIndex(getCPtr(), key); } /** * Clears the variables in the map * @param clear_variables if true, clear the variables from the knowledge * base as well as the map **/ public void clear(boolean clear_variables) throws MadaraDeadObjectException { jni_clear(getCPtr(), clear_variables); } /** * Erases a variable located at key in the map. This also deletes the variable * from the knowledge base. * @param key the element key **/ public void erase(java.lang.String key) throws MadaraDeadObjectException { jni_erase(getCPtr(), key); } /** * Sets the value * * @param key the location in the map * @param value new value */ public void set(java.lang.String key, java.lang.String value) throws MadaraDeadObjectException { jni_setString(getCPtr(), key, value); } /** * Sets the value * * @param key the location in the map * @param value new value */ public void set(java.lang.String key, double value) throws MadaraDeadObjectException { jni_setDouble(getCPtr(), key, value); } /** * Sets the value * * @param key the location in the map * @param value new value */ public void set(java.lang.String key, long value) throws MadaraDeadObjectException { jni_set(getCPtr(), key, 0, value); } /** * Sets the value * * @param key the location in the map * @param value new value */ public void set(java.lang.String key, KnowledgeRecord value) throws MadaraDeadObjectException { jni_set(getCPtr(), key, 1, value.getCPtr ()); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns a value at the specified key * * @param key the location in the map * @return the value at the index as a knowledge record */ public KnowledgeRecord toRecord(java.lang.String key) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), key)); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeMap(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/NativeDoubleVector.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for an array of doubles within a single knowledge record * within a knowledge base. Use this type of container if you want to * have an atomic array, such as position coordinates, where changing * one element of the array requres all array elements to be sent as * an update. **/ public class NativeDoubleVector extends BaseContainer { private native long jni_NativeDoubleVector(); private native long jni_NativeDoubleVector(long cptr); private static native void jni_freeNativeDoubleVector(long cptr); private native void jni_set(long cptr, int index, double value); private native void jni_pushback(long cptr, double value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native double jni_get(long cptr, int index); private native long jni_toRecord(long cptr, int index); private native long jni_toRecord(long cptr); private native Object[] jni_toArray(long cptr); private native long jni_size(long cptr); private native void jni_resize(long cptr, long length); private native void jni_modify(long cptr); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public NativeDoubleVector() { setCPtr(jni_NativeDoubleVector()); } /** * Copy constructor * @param input instance to copy **/ public NativeDoubleVector(NativeDoubleVector input) { setCPtr(jni_NativeDoubleVector(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static NativeDoubleVector fromPointer(long cptr) { NativeDoubleVector ret = new NativeDoubleVector(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static NativeDoubleVector fromPointer(long cptr, boolean shouldManage) { NativeDoubleVector ret = new NativeDoubleVector(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value at a specified index * @param index index of the element to retrieve * @return current value at the index */ public double get(int index) throws MadaraDeadObjectException { return jni_get(getCPtr(), index); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Resizes the vector * * @param length new number of elements of the vector */ public void resize (long length) throws MadaraDeadObjectException { jni_resize(getCPtr(), length); } /** * Mark the vector as modified. The vector retains the same values * but will resend all values as if they had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Sets the value at the index * @param index the index of the element to change * @param value new value */ public void set(int index, double value) throws MadaraDeadObjectException { jni_set(getCPtr(), index, value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(double value) throws MadaraDeadObjectException { jni_pushback(getCPtr(), value); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns the size of the vector * * @return the number of elements in the vector */ public long size () throws MadaraDeadObjectException { return jni_size(getCPtr()); } /** * Returns a value at the specified index * * @return the vector as an array of records */ public KnowledgeRecord[] toArray() throws MadaraDeadObjectException { Object[] objs = jni_toArray(getCPtr()); KnowledgeRecord[] records = new KnowledgeRecord[objs.length]; for (int i = 0; i < objs.length; ++i) { records[i] = (KnowledgeRecord)objs[i]; } return records; } /** * Returns a value at the specified index * * @param index the index * @return the value at the index as a knowledge record */ public KnowledgeRecord toRecord(int index) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), index)); } /** * Returns all of the values as a knowledge record * * @return knowledge record that contains all indices */ public KnowledgeRecord toRecord() throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr())); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeNativeDoubleVector(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/NativeIntegerVector.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for an array of integers within a single knowledge record * within a knowledge base. Use this type of container if you want to * have an atomic array, such as position coordinates, where changing * one element of the array requres all array elements to be sent as * an update. **/ public class NativeIntegerVector extends BaseContainer { private native long jni_NativeIntegerVector(); private native long jni_NativeIntegerVector(long cptr); private static native void jni_freeNativeIntegerVector(long cptr); private native void jni_set(long cptr, int index, long value); private native void jni_pushback(long cptr, long value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native long jni_get(long cptr, int index); private native long jni_toRecord(long cptr, int index); private native long jni_toRecord(long cptr); private native Object[] jni_toArray(long cptr); private native long jni_size(long cptr); private native void jni_resize(long cptr, long length); private native void jni_modify(long cptr); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; public NativeIntegerVector() { setCPtr(jni_NativeIntegerVector()); } public NativeIntegerVector(NativeIntegerVector input) { setCPtr(jni_NativeIntegerVector(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static NativeIntegerVector fromPointer(long cptr) { NativeIntegerVector ret = new NativeIntegerVector(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static NativeIntegerVector fromPointer(long cptr, boolean shouldManage) { NativeIntegerVector ret = new NativeIntegerVector(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value at the index * @param index the index of the element to retrieve * @return current value at the index */ public long get(int index) throws MadaraDeadObjectException { return jni_get(getCPtr(), index); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Resizes the vector * * @param length new number of elements of the vector */ public void resize (long length) throws MadaraDeadObjectException { jni_resize(getCPtr(), length); } /** * Sets the value at the specified index * @param index index of the element in the array to change * @param value new value */ public void set(int index, long value) throws MadaraDeadObjectException { jni_set(getCPtr(), index, value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(long value) throws MadaraDeadObjectException { jni_pushback(getCPtr(), value); } /** * Mark the vector as modified. The vector retains the same values * but will resend all values as if they had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns the size of the vector * * @return the number of elements in the vector */ public long size () throws MadaraDeadObjectException { return jni_size(getCPtr()); } /** * Returns a value at the specified index * * @param index the index * @return the value at the index as a knowledge record */ public KnowledgeRecord toRecord(int index) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), index)); } /** * Returns a value at the specified index * * @return the vector as an array of records */ public KnowledgeRecord[] toArray() throws MadaraDeadObjectException { Object[] objs = jni_toArray(getCPtr()); KnowledgeRecord[] records = new KnowledgeRecord[objs.length]; for (int i = 0; i < objs.length; ++i) { records[i] = (KnowledgeRecord)objs[i]; } return records; } /** * Returns all of the values as a knowledge record * * @return knowledge record that contains all indices */ public KnowledgeRecord toRecord() throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr())); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeNativeIntegerVector(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/Queue.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a dynamically typed vector within a knowledge base. **/ public class Queue extends MadaraJNI { private native long jni_Queue(); private native long jni_Queue(long cptr); private static native void jni_freeQueue(long cptr); private native boolean jni_enqueue(long cptr, long record); private native boolean jni_enqueueDouble(long cptr, double value); private native boolean jni_enqueueLong(long cptr, long value); private native boolean jni_enqueueString(long cptr, java.lang.String value); private native long jni_dequeue(long cptr, boolean waitForRecord); private native long jni_inspect(long cptr, int position); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native long jni_size(long cptr); private native long jni_count(long cptr); private native void jni_resize(long cptr, long length); private native void jni_clear(long cptr); private native void jni_setSettings(long cptr, long settings); private boolean manageMemory = true; /** * Default constructor **/ public Queue() { setCPtr(jni_Queue()); } /** * Copy constructor * @param input instance to copy **/ public Queue(Queue input) { setCPtr(jni_Queue(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Queue fromPointer(long cptr) { Queue ret = new Queue(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Queue fromPointer(long cptr, boolean shouldManage) { Queue ret = new Queue(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Inspects the record at the specified position * * @param position position in the queue to inspect * @return the record at the position (uncreated record if position is inaccessible) */ public KnowledgeRecord inspect(int position) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_inspect(getCPtr(), position)); } /** * Attempts to dequeue a record * @param waitForRecord if true, block on a record being added to queue * @return next record in the queue. An uncreated record if empty and * waitForRecord is false. */ public KnowledgeRecord dequeue(boolean waitForRecord) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_dequeue(getCPtr(), waitForRecord)); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Resizes the vector * * @param length new number of elements of the vector */ public void resize (long length) throws MadaraDeadObjectException { jni_resize(getCPtr(), length); } /** * Attempts to enqueue a record * * @param record the new record to place on the queue * @return true if the queue now contains the record. False is returned if * there was not enough room in the queue. * */ public boolean enqueue(KnowledgeRecord record) throws MadaraDeadObjectException { return jni_enqueue(getCPtr(), record.getCPtr()); } /** * Attempts to enqueue a double * * @param value the new value to place on the queue * @return true if the queue now contains the record. False is returned if * there was not enough room in the queue. * */ public boolean enqueue(double value) throws MadaraDeadObjectException { return jni_enqueueDouble(getCPtr(), value); } /** * Attempts to enqueue a long * * @param value the new value to place on the queue * @return true if the queue now contains the record. False is returned if * there was not enough room in the queue. * */ public boolean enqueue(long value) throws MadaraDeadObjectException { return jni_enqueueLong(getCPtr(), value); } /** * Attempts to enqueue a string * * @param value the new value to place on the queue * @return true if the queue now contains the record. False is returned if * there was not enough room in the queue. * */ public boolean enqueue(java.lang.String value) throws MadaraDeadObjectException { return jni_enqueueString(getCPtr(), value); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns the maximum size of the queue * * @return the maximum number of records in the queue */ public long size() throws MadaraDeadObjectException { return jni_size(getCPtr()); } /** * Returns the number of records currently in the queue * * @return the number of elements in the queue */ public long count() throws MadaraDeadObjectException { return jni_count(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeQueue(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/String.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a string value within a knowledge base **/ public class String extends BaseContainer { private native long jni_String(); private native long jni_String(long cptr); private static native void jni_freeString(long cptr); private native void jni_set(long cptr, java.lang.String value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native java.lang.String jni_toString(long cptr); private native double jni_toDouble(long cptr); private native long jni_toLong(long cptr); private native void jni_modify(long cptr); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public String() { setCPtr(jni_String()); } /** * Copy constructor * @param input instance to copy **/ public String(String input) { setCPtr(jni_String(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static String fromPointer(long cptr) { String ret = new String(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static String fromPointer(long cptr, boolean shouldManage) { String ret = new String(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value * * @return current value */ public java.lang.String get() throws MadaraDeadObjectException { return jni_toString(getCPtr()); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Mark the value as modified. The String retains the same value * but will resend its value as if it had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Sets the value * * @param value new value */ public void set(java.lang.String value) throws MadaraDeadObjectException { jni_set(getCPtr(), value); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Converts the value to a double * * @return current double value */ public double toDouble() throws MadaraDeadObjectException { return jni_toDouble(getCPtr()); } /** * Converts the value to a long * * @return current long value */ public long toLong() throws MadaraDeadObjectException { return jni_toLong(getCPtr()); } /** * Converts the value to a string * * @return current string value */ @Override public java.lang.String toString() { return jni_toString(getCPtr()); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeString(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/StringVector.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a vector of strings within a knowledge base. **/ public class StringVector extends BaseContainer { private native long jni_StringVector(); private native long jni_StringVector(long cptr); private static native void jni_freeStringVector(long cptr); private native void jni_set(long cptr, int index, java.lang.String value); private native void jni_pushback(long cptr, java.lang.String value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native java.lang.String jni_get(long cptr, int index); private native long jni_toRecord(long cptr, int index); private native Object[] jni_toArray(long cptr); private native long jni_size(long cptr); private native void jni_resize(long cptr, long length); private native void jni_modify(long cptr); private native void jni_modifyIndex(long cptr, int index); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public StringVector() { setCPtr(jni_StringVector()); } /** * Copy constructor * @param input instance to copy **/ public StringVector(StringVector input) { setCPtr(jni_StringVector(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static StringVector fromPointer(long cptr) { StringVector ret = new StringVector(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static StringVector fromPointer(long cptr, boolean shouldManage) { StringVector ret = new StringVector(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value at the specified index * @param index index of the element to retrieve * @return current value */ public java.lang.String get(int index) throws MadaraDeadObjectException { return jni_get(getCPtr(), index); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Resizes the vector. A negative number (e.g. -1) can be * provided to automatically resize the vector to whatever * size is indicated in the knowledge base. * * @param length new number of elements of the vector */ public void resize (long length) throws MadaraDeadObjectException { jni_resize(getCPtr(), length); } /** * Sets the value at the specified index * @param index the index of the element to change * @param value new value */ public void set(int index, java.lang.String value) throws MadaraDeadObjectException { jni_set(getCPtr(), index, value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(java.lang.String value) throws MadaraDeadObjectException { jni_pushback(getCPtr(), value); } /** * Mark the vector as modified. The vector retains the same values * but will resend all values as if they had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Mark an element as modified. The element retains the same value * but will resend the value as if it had been modified. * @param index the element index **/ public void modify(int index) throws MadaraDeadObjectException { jni_modifyIndex(getCPtr(), index); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns the size of the vector * * @return the number of elements in the vector */ public long size () throws MadaraDeadObjectException { return jni_size(getCPtr()); } /** * Returns a value at the specified index * * @return the vector as an array of records */ public KnowledgeRecord[] toArray() throws MadaraDeadObjectException { Object[] objs = jni_toArray(getCPtr()); KnowledgeRecord[] records = new KnowledgeRecord[objs.length]; for (int i = 0; i < objs.length; ++i) { records[i] = (KnowledgeRecord)objs[i]; } return records; } /** * Returns a value at the specified index * * @param index the index * @return the value at the index as a knowledge record */ public KnowledgeRecord toRecord(int index) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), index)); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeStringVector(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge
java-sources/ai/madara/madara/3.2.3/ai/madara/knowledge/containers/Vector.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.knowledge.containers; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.Variables; /** * A facade for a dynamically typed vector within a knowledge base. **/ public class Vector extends BaseContainer { private native long jni_Vector(); private native long jni_Vector(long cptr); private static native void jni_freeVector(long cptr); private native void jni_setString(long cptr, int index, java.lang.String value); private native void jni_setDouble(long cptr, int index, double value); private native void jni_set(long cptr, int index, long type, long value); private native void jni_pushbackLong(long cptr, long value); private native void jni_pushbackRecord(long cptr, long rptr); private native void jni_pushbackDouble(long cptr, double value); private native void jni_pushbackDoubleArray(long cptr, double [] value); private native void jni_pushbackLongArray(long cptr, long [] value); private native void jni_pushbackString(long cptr, java.lang.String value); private native java.lang.String jni_getName(long cptr); private native void jni_setName(long cptr, long type, long kb, java.lang.String name); private native long jni_get(long cptr, int index); private native long jni_toRecord(long cptr, int index); private native Object[] jni_toArray(long cptr); private native long jni_size(long cptr); private native void jni_resize(long cptr, long length); private native void jni_modify(long cptr); private native void jni_modifyIndex(long cptr, int index); private native void jni_setSettings(long cptr, long settings); private native boolean jni_isTrue(long cptr); private native boolean jni_isFalse(long cptr); private boolean manageMemory = true; /** * Default constructor **/ public Vector() { setCPtr(jni_Vector()); } /** * Copy constructor * @param input instance to copy **/ public Vector(Vector input) { setCPtr(jni_Vector(input.getCPtr())); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Vector fromPointer(long cptr) { Vector ret = new Vector(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Vector fromPointer(long cptr, boolean shouldManage) { Vector ret = new Vector(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the value * * @param index index for the new value * @return current value */ public KnowledgeRecord get(int index) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), index)); } /** * Gets the name of the variable * * @return name of the variable within the context */ public java.lang.String getName() throws MadaraDeadObjectException { return jni_getName(getCPtr()); } /** * Resizes the vector. A negative number (e.g. -1) can be * provided to automatically resize the vector to whatever * size is indicated in the knowledge base. * * @param length new number of elements of the vector */ public void resize (long length) throws MadaraDeadObjectException { jni_resize(getCPtr(), length); } /** * Sets the value * * @param index index for the new value * @param value new value */ public void set(int index, java.lang.String value) throws MadaraDeadObjectException { jni_setString(getCPtr(), index, value); } /** * Sets the value * * @param index index for the new value * @param value new value */ public void set(int index, double value) throws MadaraDeadObjectException { jni_setDouble(getCPtr(), index, value); } /** * Sets the value * * @param index index for the new value * @param value new value */ public void set(int index, long value) { jni_set(getCPtr(), index, 0, value); } /** * Sets the value * * @param index index for the new value * @param value new value */ public void set(int index, KnowledgeRecord value) { jni_set(getCPtr(), index, 1, value.getCPtr ()); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(KnowledgeRecord value) throws MadaraDeadObjectException { jni_pushbackRecord(getCPtr(), value.getCPtr()); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(java.lang.String value) throws MadaraDeadObjectException { jni_pushbackString(getCPtr(), value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(long value) throws MadaraDeadObjectException { jni_pushbackLong(getCPtr(), value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(long [] value) throws MadaraDeadObjectException { jni_pushbackLongArray(getCPtr(), value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(double value) throws MadaraDeadObjectException { jni_pushbackDouble(getCPtr(), value); } /** * Pushes a value to the end of the vector * @param value new value to add to vector */ public void pushback(double [] value) throws MadaraDeadObjectException { jni_pushbackDoubleArray(getCPtr(), value); } /** * Mark the vector as modified. The vector retains the same values * but will resend all values as if they had been modified. **/ public void modify() throws MadaraDeadObjectException { jni_modify(getCPtr()); } /** * Returns true if the container evaluates to true * @return true if container has all true values **/ public boolean isTrue() throws MadaraDeadObjectException { return jni_isTrue(getCPtr()); } /** * Returns true if the container evaluates to false * @return true if container has any false values or is uninitialized **/ public boolean isFalse() throws MadaraDeadObjectException { return jni_isFalse(getCPtr()); } /** * Mark an element as modified. The element retains the same value * but will resend the value as if it had been modified. * @param index the element index **/ public void modify(int index) throws MadaraDeadObjectException { jni_modifyIndex(getCPtr(), index); } /** * Sets the name and knowledge base being referred to * * @param kb the knowledge base that contains the name * @param name the variable name */ public void setName(KnowledgeBase kb, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 0, kb.getCPtr (), name); } /** * Sets the name and knowledge base being referred to * * @param vars the variables facade that contains the name * @param name the variable name */ public void setName(Variables vars, java.lang.String name) throws MadaraDeadObjectException { jni_setName(getCPtr(), 1, vars.getCPtr (), name); } /** * Sets the settings for updating variables in the Knowledge Base * * @param settings the settings to use for updating the Knowledge Base */ public void setSettings(UpdateSettings settings) throws MadaraDeadObjectException { jni_setSettings(getCPtr(), settings.getCPtr()); } /** * Returns the size of the vector * * @return the number of elements in the vector */ public long size () throws MadaraDeadObjectException { return jni_size(getCPtr()); } /** * Returns a value at the specified index * * @param index the index * @return the value at the index as a knowledge record */ public KnowledgeRecord toRecord(int index) throws MadaraDeadObjectException { return KnowledgeRecord.fromPointer(jni_toRecord(getCPtr(), index)); } /** * Returns a value at the specified index * * @return the vector as an array of records */ public ai.madara.knowledge.KnowledgeRecord[] toArray() throws MadaraDeadObjectException { Object[] objs = jni_toArray(getCPtr()); KnowledgeRecord[] records = new KnowledgeRecord[objs.length]; for (int i = 0; i < objs.length; ++i) { records[i] = (KnowledgeRecord)objs[i]; } return records; } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeVector(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/logger/GlobalLogger.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.logger; import ai.madara.MadaraJNI; /** * A facade for the global MADARA logging service (the default logger) **/ public class GlobalLogger extends MadaraJNI { private static native long jni_getCPtr(); private static native void jni_setLevel(int level); private static native int jni_getLevel(); private static native java.lang.String jni_getTag(); private static native void jni_setTag(java.lang.String tag); private static native void jni_addTerm(); private static native void jni_addSyslog(); private static native void jni_clear(); private static native void jni_addFile(java.lang.String filename); private static native void jni_log(int level, java.lang.String message); private static native void jni_setTimestampFormat(java.lang.String format); /** * Default constructor **/ public GlobalLogger() { setCPtr(jni_getCPtr()); } /** * Gets the tag used in system logging * * @return current tag for system logging */ public static java.lang.String getTag() { return jni_getTag(); } /** * Gets the logging level, e.g., where 0 is EMERGENCY and 6 is DETAILED * * @return the current logging level */ public static int getLevel() { return jni_getLevel(); } /** * Gets the logging level, e.g., where 0 is EMERGENCY and 6 is DETAILED * * @return the current logging level */ public static Logger toLogger() { return Logger.fromPointer(jni_getCPtr(), false); } /** * Sets the tag used for system logging * @param tag the tag to be used for system logging */ public static void setTag(java.lang.String tag) { jni_setTag(tag); } /** * Sets the logging level * * @param level level of message severity to print to log targets */ public static void setLevel(int level) { jni_setLevel(level); } /** * Clears all logging targets */ public static void clear() { jni_clear(); } /** * Adds the terminal to logging outputs (turned on by default) */ public static void addTerm() { jni_addTerm(); } /** * Adds the system logger to logging outputs */ public static void addSyslog() { jni_addSyslog(); } /** * Adds a file to logging outputs * @param filename the name of a file to add to logging targets */ public static void addFile(java.lang.String filename) { jni_addFile(filename); } /** * Logs a message at the specified level * @param level the logging severity level (0 is high) * @param message the message to send to all logging targets */ public static void log(int level, java.lang.String message) { jni_log(level, message); } /** * Sets timestamp format. Uses * <a href="http://www.cplusplus.com/reference/ctime/strftime/">strftime</a> * for formatting time. * @param format the format of the timestamp. See C++ * strftime definition for common usage. **/ public static void setTimestampFormat(java.lang.String format) { jni_setTimestampFormat(format); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/logger/LogLevels.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.logger; public enum LogLevels { LOG_NOTHING (-1), LOG_EMERGENCY (0), LOG_ALWAYS (0), LOG_ERROR (1), LOG_WARNING (2), LOG_MAJOR (3), LOG_MINOR (4), LOG_TRACE (5), LOG_DETAILED (6), LOG_MAX (6); private int num; private LogLevels(int num) { this.num = num; } /** * Get the integer value of this enum * * @return value of the enum */ public int value() { return num; } public static LogLevels getType(int val) { for (LogLevels t : values()) { if (t.value() == val) return t; } return null; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/logger/Logger.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.logger; import ai.madara.MadaraJNI; /** * An extensible logger used for printing to files, terminals and system logs **/ public class Logger extends MadaraJNI { private native long jni_Logger(); private static native void jni_freeLogger(long cptr); private native void jni_setLevel(long cptr, int level); private native int jni_getLevel(long cptr); private native java.lang.String jni_getTag(long cptr); private native void jni_setTag(long cptr, java.lang.String tag); private native void jni_addTerm(long cptr); private native void jni_addSyslog(long cptr); private native void jni_clear(long cptr); private native void jni_addFile(long cptr, java.lang.String filename); private native void jni_log(long cptr, int level, java.lang.String message); private native void jni_setTimestampFormat(long cptr, java.lang.String format); private boolean manageMemory = true; /** * Default constructor **/ public Logger() { setCPtr(jni_Logger()); } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @return a new java instance of the underlying pointer */ public static Logger fromPointer(long cptr) { Logger ret = new Logger(); ret.manageMemory = true; ret.setCPtr(cptr); return ret; } /** * Creates a java object instance from a C/C++ pointer * * @param cptr C pointer to the object * @param shouldManage if true, manage the pointer * @return a new java instance of the underlying pointer */ public static Logger fromPointer(long cptr, boolean shouldManage) { Logger ret = new Logger(); ret.manageMemory=shouldManage; ret.setCPtr(cptr); return ret; } /** * Gets the tag used in system logging * * @return current tag for system logging */ public java.lang.String getTag() { return jni_getTag(getCPtr()); } /** * Gets the logging level, e.g., where 0 is EMERGENCY and 6 is DETAILED * * @return the current logging level */ public int getLevel() { return jni_getLevel(getCPtr()); } /** * Sets the tag used for system logging * @param tag the tag to be used for system logging */ public void setTag(java.lang.String tag) { jni_setTag(getCPtr(), tag); } /** * Sets the logging level * * @param level level of message severity to print to log targets */ public void setLevel(int level) { jni_setLevel(getCPtr(), level); } /** * Clears all logging targets */ public void clear() { jni_clear(getCPtr()); } /** * Adds the terminal to logging outputs (turned on by default) */ public void addTerm() { jni_addTerm(getCPtr()); } /** * Adds the system logger to logging outputs */ public void addSyslog() { jni_addSyslog(getCPtr()); } /** * Adds a file to logging outputs * @param filename the name of a file to add to logging targets */ public void addFile(java.lang.String filename) { jni_addFile(getCPtr(), filename); } /** * Logs a message at the specified level * @param level the logging severity level (0 is high) * @param message the message to send to all logging targets */ public void log(int level, java.lang.String message) { jni_log(getCPtr(), level, message); } /** * Sets timestamp format. Uses * <a href="http://www.cplusplus.com/reference/ctime/strftime/">strftime</a> * for formatting time. * @param format the format of the timestamp. See C++ * strftime definition for common usage. **/ public void setTimestampFormat(java.lang.String format) { jni_setTimestampFormat(getCPtr(), format); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance gets garbage collected */ public void free() { if (manageMemory) { jni_freeLogger(getCPtr()); setCPtr(0); } } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/AesBufferFilterTest.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.filters.ssl.AesBufferFilter; /** * This class is a tester for the AesBufferFilter class */ public class AesBufferFilterTest { public static void testAesBufferFilter() throws MadaraDeadObjectException { AesBufferFilter filter = new AesBufferFilter (); byte [] buffer = new byte [500]; buffer[0] = 'H'; buffer[1] = 'e'; buffer[2] = 'l'; buffer[3] = 'l'; buffer[4] = 'o'; buffer[5] = ' '; buffer[6] = 'W'; buffer[7] = 'o'; buffer[8] = 'r'; buffer[9] = 'l'; buffer[10] = 'd'; buffer[11] = '!'; buffer[12] = 0; buffer[13] = 0; String plaintext = new String(buffer,0,(int)13); long size = filter.encode(buffer, 13, 500); String encoded = new String(buffer,0,(int)size); if (!plaintext.equals(encoded)) { System.out.println("Plaintext was not equal to encoded. SUCCESS"); } else { System.out.println("Plaintext was equal to encoded. FAIL"); } size = filter.decode(buffer, size, size); String decoded = new String(buffer,0,(int)size); if (!encoded.equals(decoded)) { System.out.println("Encoded was not equal to decoded. SUCCESS"); } else { System.out.println("Encoded was equal to decoded. FAIL"); } if (plaintext.equals(decoded)) { System.out.println("Plaintext was equal to decoded. SUCCESS"); } else { System.out.println("Plaintext was not equal to decoded. FAIL"); } /** * Normally we would not need to do this when passing this to a settings. * However, in this case, we should clean up. **/ filter.free(); } public static void main(String...args) throws Exception { testAesBufferFilter(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/ContainerTest.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.UpdateSettings; import ai.madara.knowledge.containers.Collection; import ai.madara.knowledge.containers.Double; import ai.madara.knowledge.containers.DoubleVector; import ai.madara.knowledge.containers.FlexMap; import ai.madara.knowledge.containers.Integer; import ai.madara.knowledge.containers.IntegerVector; import ai.madara.knowledge.containers.NativeDoubleVector; import ai.madara.knowledge.containers.Queue; import ai.madara.knowledge.containers.StringVector; import ai.madara.knowledge.containers.Vector; /** * This class is a tester for the ai.madara.knowledge.containers package */ public class ContainerTest { public static void testFlexMap() throws MadaraDeadObjectException { KnowledgeBase knowledge = new KnowledgeBase(); UpdateSettings settings = new UpdateSettings(); settings.setTreatGlobalsAsLocals(true); FlexMap map = new FlexMap(); map.setName(knowledge, ""); map.setSettings(settings); boolean error = false; System.out.println("Creating flex records for robert and cassie"); // create some flex maps within the knowledge base FlexMap records = map.get("records"); FlexMap robert = records.get("robert"); FlexMap cassie = records.get("cassie"); // FlexMap contains some garbage collection via finalize, but it may // never be called by the GC due to Java's own quirkiness. We create // some flexmaps here that will not be explicitly freed, and this is // technically ok, but in a real application, if you are done with one // you are better suited to keep a reference to them and free the C // resources. System.out.println("Setting attributes for Robert"); robert.get("age").set(49); robert.get("name").set("Robert Jenkins"); robert.get("salary").set(30500.00); System.out.println("Setting attributes for Cassie"); cassie.get("age").set(22); cassie.get("name").set("Cassandra Collins"); cassie.get("salary").set(57000.00); System.out.println("Checking results of FlexMap operations"); KnowledgeRecord robert_name = knowledge.get(".records.robert.name"); KnowledgeRecord robert_age = knowledge.get(".records.robert.age"); KnowledgeRecord robert_salary = knowledge.get(".records.robert.salary"); KnowledgeRecord cassie_name = knowledge.get(".records.cassie.name"); KnowledgeRecord cassie_age = knowledge.get(".records.cassie.age"); KnowledgeRecord cassie_salary = knowledge.get(".records.cassie.salary"); if(robert_name.toString().equals("Robert Jenkins") && robert_age.toLong() == 49 && robert_salary.toLong() == 30500 && cassie_name.toString().equals("Cassandra Collins") && cassie_age.toLong() == 22 && cassie_salary.toLong() == 57000) { System.out.println(" Retrieval of values: SUCCESS"); } else { System.out.println(" Retrieval of values: FAIL"); error = true; System.out.println (" Flex: Robert.name was " + robert_name.toString()); System.out.println (" Flex: Robert.age was " + robert_age.toLong()); System.out.println (" Flex: Robert.salary was " + robert_salary.toLong()); System.out.println (" Flex: Cassie.name was " + cassie_name.toString()); System.out.println (" Flex: Cassie.age was " + cassie_age.toLong()); System.out.println (" Flex: Cassie.salary was " + cassie_salary.toLong()); } System.out.println("Retrieving first level keys of FlexMap"); java.lang.String[] keys = robert.keys(true); if(keys[0].equals("age") && keys[1].equals("name") && keys[2].equals("salary")) { System.out.println(" Retrieval of first level keys: SUCCESS"); } else { System.out.println(" Retrieval of first level keys: FAIL"); error = true; for(int i = 0; i < keys.length; i++) { System.out.println(" keys[" + i + "] = " + keys[i]); } } System.out.println("Changing delimiter of FlexMap"); // change the map delimiter map.setDelimiter(";"); System.out.println("Retrieving first level keys of FlexMap"); keys = map.keys(true); if(keys.length == 0) { System.out.println(" Retrieval of first level keys: SUCCESS"); } else { System.out.println(" Retrieval of first level keys: FAIL"); error = true; for(int i = 0; i < keys.length; i++) { System.out.println(" keys[" + i + "] = " + keys[i]); } } System.out.println("Resetting delimiter of FlexMap"); // change the map delimiter map.setDelimiter("."); System.out.println("Retrieving first level keys of FlexMap"); keys = robert.keys(true); if(keys.length == 3) { System.out.println(" Retrieval of first level keys: SUCCESS"); } else { System.out.println(" Retrieval of first level keys: FAIL"); error = true; } if(error) { knowledge.print(); } // order doesn't really matter here cassie.free(); robert.free(); records.free(); settings.free(); } public static void testVector() throws MadaraDeadObjectException { KnowledgeBase knowledge = new KnowledgeBase(); Vector list = new Vector(); UpdateSettings settings = new UpdateSettings(); settings.setTreatGlobalsAsLocals(true); list.setSettings(settings); boolean error = false; System.out.println("Testing Vector"); list.setName(knowledge, "device.sensors"); list.resize(4); System.out.println(" Setting elements"); list.set(0, "first element"); list.set(1, "second element"); list.set(2, "third element"); list.set(3, "fourth element"); System.out.println("0: " + list.get(0).toString()); System.out.println("1: " + list.get(1).toString()); System.out.println("2: " + list.get(2).toString()); System.out.println("3: " + list.get(3).toString()); System.out.println(" Shipping elements to an array"); KnowledgeRecord[] my_array = list.toArray(); System.out.println(" Printing " + my_array.length + " array elements"); for(int i = 0; i < my_array.length; ++i) { String result = " "; result += i; result += ": "; result += my_array[i].toString(); System.out.println(result); } if(list.get(0).toString().equals("first element") && list.get(1).toString().equals("second element") && list.get(2).toString().equals("third element") && list.get(3).toString().equals("fourth element")) { System.out.println(" SUCCESS: Vector set method test"); } else { System.out.println(" FAIL: Vector set method test"); error = true; } if(my_array.length == 4 && my_array[0].toString().equals("first element") && my_array[1].toString().equals("second element") && my_array[2].toString().equals("third element") && my_array[3].toString().equals("fourth element")) { System.out.println(" SUCCESS: Vector toArray test"); } else { System.out.println(" FAIL: Vector toArray test"); error = true; } System.out.println(" Resizing vector to 0 elements"); list.resize (0); knowledge.print(); System.out.println(" Pushing a 10 and string on to vector"); list.pushback(10); list.pushback("second element"); knowledge.print(); if(error) knowledge.print(); } public static void testInteger() throws MadaraDeadObjectException { KnowledgeBase knowledge = new KnowledgeBase(); Integer counter = new Integer(); UpdateSettings settings = new UpdateSettings(); settings.setTreatGlobalsAsLocals(true); counter.setSettings(settings); boolean error = false; System.out.println("Testing Integer"); counter.setName(knowledge, "counter"); // 0 += 1 == 1 counter.inc(); // 1 += 10 == 11 counter.inc(10); // 11 -= 5 == 6 counter.dec(5); // --6 == 5 counter.dec(); if(counter.toLong() == 5) { System.out.println(" SUCCESS: Integer inc/dec test"); } else { System.out.println(" FAIL: Integer inc/dec test"); error = true; } if(error) knowledge.print(); } public static void testQueue() throws MadaraDeadObjectException { KnowledgeBase knowledge = new KnowledgeBase(); Queue queue = new Queue(); UpdateSettings settings = new UpdateSettings(); settings.setTreatGlobalsAsLocals(true); queue.setSettings(settings); boolean error = false; System.out.println("Testing Queue"); queue.setName(knowledge, "queue"); queue.resize(10); queue.enqueue(10); queue.enqueue(12.5); queue.enqueue("third"); if(queue.count() == 3 && queue.size() == 10) { System.out.println(" SUCCESS: Queue count and size test"); } else { System.out.println(" FAIL: Queue count and size test"); error = true; } KnowledgeRecord value1 = queue.dequeue(true); KnowledgeRecord value2 = queue.dequeue(true); KnowledgeRecord value3 = queue.dequeue(true); if(value1.toString().equals("10") && value2.toString().equals("12.5") && value3.toString().equals("third") && queue.count() == 0) { System.out.println(" SUCCESS: Queue dequeue test"); } else { System.out.println(" FAIL: Queue dequeue test"); error = true; } if(error) knowledge.print(); } public static void testDoubleVector() throws MadaraDeadObjectException { KnowledgeBase knowledge = new KnowledgeBase(); DoubleVector vector = new DoubleVector(); UpdateSettings settings = new UpdateSettings(); settings.setTreatGlobalsAsLocals(true); vector.setSettings(settings); boolean error = false; System.out.println("Testing Queue"); vector.setName(knowledge, "dblVector"); vector.resize(10); vector.set(0,10); vector.set(1, 12.5); vector.set(2, 14.234224214); vector.set(7, 341234.141222893); if(vector.size() == 10) { System.out.println(" SUCCESS: Vector size test"); } else { System.out.println(" FAIL: Vector size test"); error = true; } KnowledgeRecord value0 = vector.toRecord(0); KnowledgeRecord value1 = vector.toRecord(1); KnowledgeRecord value2 = vector.toRecord(2); KnowledgeRecord value7 = vector.toRecord(7); if(value0.toDouble() == 10 && value1.toDouble() == 12.5 && value2.toDouble() == 14.234224214 && value7.toDouble() == 341234.141222893) { System.out.println(" SUCCESS: value tests at 0, 1, 2, 7"); } else { System.out.println(" FAIL: value tests at 0, 1, 2, 7"); error = true; } if(value1.toString().equals("12.5") && value2.toString().equals("14.234224214") && value7.toString().equals("341234.141222893")) { System.out.println(" SUCCESS: default precision is enough for values"); } else { System.out.println(" FAIL: default precision is not enough for values"); error = true; } knowledge.evaluateNoReturn("#set_precision(9)"); if(value1.toString().equals("12.500000000") && value2.toString().equals("14.234224214") && value7.toString().equals("341234.141222893")) { System.out.println(" SUCCESS: setprecision(9) is enough for values"); } else { System.out.println(" FAIL: setprecision(9) is not enough for values"); error = true; } if(error) knowledge.print(); } public static void testCollection() throws MadaraDeadObjectException { System.out.println("Testing Collections"); KnowledgeBase knowledge = new KnowledgeBase(); System.out.println(" Creating containers"); ai.madara.knowledge.containers.String name = new ai.madara.knowledge.containers.String(); Integer age = new Integer(); NativeDoubleVector gps = new NativeDoubleVector(); Double craziness = new Double(); StringVector shoppingList = new StringVector(); IntegerVector shoppingListCompleted = new IntegerVector(); Collection profile = new Collection(); boolean ready = false; System.out.println(" Linking containers to knowledge records"); name.setName(knowledge, "name"); age.setName(knowledge, "age"); gps.setName(knowledge, "location"); craziness.setName(knowledge, "currentCraziness"); shoppingList.setName(knowledge, "shoppingList"); shoppingListCompleted.setName(knowledge, "shoppingListCompleted"); System.out.println(" Populating containers"); name.set("Bob Tompkins"); age.set(49); gps.resize(3); gps.set(0, 72); gps.set(1, 42); gps.set(2, 1500); craziness.set(0.7); shoppingList.resize(10); shoppingList.set(0, "Corn"); shoppingList.set(1, "Lettuce"); shoppingList.set(2, "Tomatoes"); shoppingList.set(3, "Teriyaki"); shoppingList.set(4, "Chicken Breast"); shoppingList.set(5, "Milk"); shoppingList.set(6, "Eggs"); shoppingList.set(7, "Bread"); shoppingList.set(8, "Bacon"); shoppingList.set(9, "Yogurt"); shoppingListCompleted.resize(10); shoppingListCompleted.set(0, 1); shoppingListCompleted.set(1, 1); shoppingListCompleted.set(2, 1); shoppingListCompleted.set(4, 1); shoppingListCompleted.set(5, 1); shoppingListCompleted.set(6, 1); shoppingListCompleted.set(7, 1); shoppingListCompleted.set(8, 1); System.out.println(" Adding containers to collection"); profile.add(name); profile.add(age); profile.add(gps); profile.add(craziness); profile.add(shoppingList); System.out.println(" Printing current modifieds"); System.out.println(knowledge.debugModifieds()); System.out.println(" Clearing modified variables"); knowledge.clearModifieds(); System.out.println(" Printing current modifieds"); System.out.println(knowledge.debugModifieds()); System.out.println(" Trying modifyIfTrue with incomplete shopping list"); ready = profile.modifyIfTrue(shoppingListCompleted); if(ready == true) { System.out.println(" FAIL. Modification happened even though false"); } else { System.out.println(" SUCCESS. Modification did not occur"); } System.out.println(" Printing current modifieds"); System.out.println(knowledge.debugModifieds()); System.out.println(" Modifying shopping list to be complete"); shoppingListCompleted.set(3, 1); shoppingListCompleted.set(9, 1); System.out.println(" Trying modifyIfTrue with complete shopping list"); ready = profile.modifyIfTrue(shoppingListCompleted); if(ready == false) { System.out.println(" FAIL. Modification did not occur"); } else { System.out.println(" SUCCESS. Modification occurred"); } System.out.println(" Printing current modifieds"); System.out.println(knowledge.debugModifieds()); } public static void main(String...args) throws Exception { testInteger(); testVector(); testQueue(); testDoubleVector(); testFlexMap(); testCollection(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/CounterFilterTest.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import java.util.ArrayList; import java.util.List; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.filters.CounterFilter; import ai.madara.knowledge.KnowledgeBase; import ai.madara.logger.GlobalLogger; import ai.madara.threads.BaseThread; import ai.madara.threads.Threader; import ai.madara.transport.QoSTransportSettings; import ai.madara.transport.TransportType; /** * This class is a tester for the CounterFilter class */ public class CounterFilterTest { static class Sender extends BaseThread { private ai.madara.knowledge.containers.String payload_ = new ai.madara.knowledge.containers.String(); private KnowledgeBase knowledge_ = null; public Sender(KnowledgeBase knowledge, int dataSize) throws MadaraDeadObjectException { java.lang.String payload = new String(new char[dataSize]).replace('\0', ' '); knowledge_ = knowledge; payload_.setName(knowledge, "payload"); payload_.set(payload); } public void run() throws MadaraDeadObjectException { payload_.modify(); knowledge_.sendModifieds(); } } public static void main(String... args) throws InterruptedException, Exception { String curHost = ""; int id = 0; int dataSize = 1024; double activeTime = 10.0; QoSTransportSettings settings = new QoSTransportSettings(); List<String> hosts = new ArrayList<String>(); CounterFilter filter = new CounterFilter(); for (int i = 0; i < args.length; ++i) { if (args[i].equals("-i") || args[i].equals("--id")) { if (i + 1 < args.length) { id = Integer.parseInt(args[i + 1]); } ++i; } else if (args[i].equals("-f") || args[i].equals("--log-file")) { if (i + 1 < args.length) { GlobalLogger.addFile(args[i + 1]); } ++i; } else if (args[i].equals("-o") || args[i].equals("--host")) { if (i + 1 < args.length) { curHost = args[i + 1]; } ++i; } else if (args[i].equals("-l") || args[i].equals("--log-level")) { if (i + 1 < args.length) { int logLevel = Integer.parseInt(args[i + 1]); GlobalLogger.setLevel(logLevel); } ++i; } else if (args[i].equals("-s") || args[i].equals("--size")) { if (i + 1 < args.length) { dataSize = Integer.parseInt(args[i + 1]); } ++i; } else if (args[i].equals("-t") || args[i].equals("--time")) { if (i + 1 < args.length) { activeTime = Double.parseDouble(args[i + 1]); } ++i; } else if (args[i].equals("-q") || args[i].equals("--queue-length")) { if (i + 1 < args.length) { int length = Integer.parseInt(args[i + 1]); settings.setQueueLength(length); } ++i; } else if (args[i].equals("-m") || args[i].equals("--multicast")) { if (i + 1 < args.length) { hosts.add(args[i + 1]); settings.setType(TransportType.MULTICAST_TRANSPORT); } ++i; } else if (args[i].equals("-b") || args[i].equals("--broadcast")) { if (i + 1 < args.length) { hosts.add(args[i + 1]); settings.setType(TransportType.BROADCAST_TRANSPORT); } ++i; } else if (args[i].equals("-u") || args[i].equals("--udp")) { if (i + 1 < args.length) { hosts.add(args[i + 1]); settings.setType(TransportType.UDP_TRANSPORT); } ++i; } else { GlobalLogger.log(0, "ERROR: unrecognized parameter:" + args[i]); GlobalLogger.log(0, "Arguments:"); GlobalLogger.log(0, " -b|--broadcast: broadcast host to subscribe to"); GlobalLogger.log(0, " -f|--log-file: log to a file as well"); GlobalLogger.log(0, " -i|--id: the identifier. 0 is publisher."); GlobalLogger.log(0, " -l|--log-level: log level to use."); GlobalLogger.log(0, " -m|--multicast: multicast host to subscribe to"); GlobalLogger.log(0, " -o|--host: this device's unique hostname"); GlobalLogger.log(0, " -q|--queue-length: queue length use for send/rcv"); GlobalLogger.log(0, " -s|--size: Size of packet to send"); GlobalLogger.log(0, " -t|--time: Time to stay active"); GlobalLogger.log(0, " -u|--udp: udp host to subscribe to. First host"); GlobalLogger.log(0, " should be self."); return; } } if (hosts.isEmpty()) { hosts.add("239.255.0.1:4150"); settings.setType(TransportType.MULTICAST_TRANSPORT); } settings.setHosts(hosts.toArray(new String[hosts.size()])); if (id == 0) { filter.addSendFilterTo(settings); } else { filter.addReceiveFilterTo(settings); } KnowledgeBase knowledge = new KnowledgeBase(curHost, settings); if (id == 0) { Threader threader = new Threader(knowledge); Sender sender = new Sender(knowledge, dataSize); threader.run(0.0, "sender", sender); ai.madara.util.Utility.sleep(activeTime); threader.terminate(); threader.waitForThreads(); threader.free(); } else { ai.madara.util.Utility.sleep(activeTime); } GlobalLogger.log(0, "Test results:"); GlobalLogger.log(0, " Packet size: " + dataSize); GlobalLogger.log(0, " Packets: " + filter.getCount()); GlobalLogger.log(0, " Elapsed Time (s): " + filter.getElapsed()); GlobalLogger.log(0, " Message Throughput (message/s): " + filter.getThroughput()); GlobalLogger.log(0, " Data Throughput (B/s): " + filter.getThroughput() * dataSize); settings.free(); knowledge.free(); filter.free(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/JavaLockPerformance.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.containers.Integer; /** * This class is a tester for Java locks versus MADARA locks */ public class JavaLockPerformance { static long target = 10000000; static long numThreads = 10; static class MadaraCounter implements Runnable { /** * A thread-safe counter **/ public Integer counter; public MadaraCounter(Integer counter) { this.counter = counter; } @Override public void run() { try { while (counter.inc() < target); } catch (MadaraDeadObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static class AtomicCounter implements Runnable { private final AtomicLong counter; public AtomicCounter(AtomicLong counter) { this.counter = counter; } @Override public void run() { while (counter.incrementAndGet() < target); } } public static class SynchronizedCounter implements Runnable { public static long counter = 0; public SynchronizedCounter() { } public synchronized long incAndGet() { return ++counter; } @Override public void run() { while (incAndGet() < target); } } public static class LockCounter implements Runnable { public static long counter = 0; public static Lock lock = new ReentrantLock(); public LockCounter() { } @Override public void run() { boolean run = true; while (run) { lock.lock(); try { run = ++counter < target; } finally { lock.unlock(); } } } } public static void testMadaraCounter() throws InterruptedException, Exception { KnowledgeBase knowledge = new KnowledgeBase(); Integer counter = new Integer(); counter.setName(knowledge, ".counter"); Thread t1 = new Thread(new MadaraCounter(counter)); Thread t2 = new Thread(new MadaraCounter(counter)); Thread t3 = new Thread(new MadaraCounter(counter)); Thread t4 = new Thread(new MadaraCounter(counter)); Thread t5 = new Thread(new MadaraCounter(counter)); Thread t6 = new Thread(new MadaraCounter(counter)); Thread t7 = new Thread(new MadaraCounter(counter)); Thread t8 = new Thread(new MadaraCounter(counter)); Thread t9 = new Thread(new MadaraCounter(counter)); Thread t10 = new Thread(new MadaraCounter(counter)); knowledge.evaluateNoReturn(".start_time = #get_time()"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); t7.start(); t8.start(); t9.start(); t10.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); t6.join(); t7.join(); t8.join(); t9.join(); t10.join(); knowledge.evaluateNoReturn(".end_time = #get_time();" + ".total_time = .end_time - .start_time;" + ".total_time_in_seconds = #double(.total_time) / 1000000000"); knowledge.set(".num_threads", numThreads); knowledge.set(".target", target); knowledge.evaluateNoReturn(".avg_hertz = .counter / .total_time_in_seconds"); knowledge.evaluateNoReturn(".avg_hertz_per_thread = .avg_hertz / .num_threads"); knowledge.print("MADARA:\n"); knowledge.print(" Time: {.total_time_in_seconds} s\n"); knowledge.print(" Hz: {.avg_hertz}\n Thread Hz: {.avg_hertz_per_thread}\n"); // free the underlying C++ heap counter.free(); knowledge.free(); } public static void testAtomicCounter() throws InterruptedException, Exception { KnowledgeBase knowledge = new KnowledgeBase(); AtomicLong counter = new AtomicLong(0); Thread t1 = new Thread(new AtomicCounter(counter)); Thread t2 = new Thread(new AtomicCounter(counter)); Thread t3 = new Thread(new AtomicCounter(counter)); Thread t4 = new Thread(new AtomicCounter(counter)); Thread t5 = new Thread(new AtomicCounter(counter)); Thread t6 = new Thread(new AtomicCounter(counter)); Thread t7 = new Thread(new AtomicCounter(counter)); Thread t8 = new Thread(new AtomicCounter(counter)); Thread t9 = new Thread(new AtomicCounter(counter)); Thread t10 = new Thread(new AtomicCounter(counter)); knowledge.evaluateNoReturn(".start_time = #get_time()"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); t7.start(); t8.start(); t9.start(); t10.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); t6.join(); t7.join(); t8.join(); t9.join(); t10.join(); knowledge.evaluateNoReturn(".end_time = #get_time();" + ".total_time = .end_time - .start_time;" + ".total_time_in_seconds = #double(.total_time) / 1000000000"); knowledge.set(".num_threads", numThreads); knowledge.set(".target", target); knowledge.set(".counter", counter.get()); knowledge.evaluateNoReturn(".avg_hertz = .counter / .total_time_in_seconds"); knowledge.evaluateNoReturn(".avg_hertz_per_thread = .avg_hertz / .num_threads"); knowledge.print("ATOMIC:\n"); knowledge.print(" Time: {.total_time_in_seconds} s\n"); knowledge.print(" Hz: {.avg_hertz}\n Thread Hz: {.avg_hertz_per_thread}\n"); // free the underlying C++ heap knowledge.free(); } public static void testSynchronizedCounter() throws InterruptedException, Exception { KnowledgeBase knowledge = new KnowledgeBase(); Thread t1 = new Thread(new SynchronizedCounter()); Thread t2 = new Thread(new SynchronizedCounter()); Thread t3 = new Thread(new SynchronizedCounter()); Thread t4 = new Thread(new SynchronizedCounter()); Thread t5 = new Thread(new SynchronizedCounter()); Thread t6 = new Thread(new SynchronizedCounter()); Thread t7 = new Thread(new SynchronizedCounter()); Thread t8 = new Thread(new SynchronizedCounter()); Thread t9 = new Thread(new SynchronizedCounter()); Thread t10 = new Thread(new SynchronizedCounter()); knowledge.evaluateNoReturn(".start_time = #get_time()"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); t7.start(); t8.start(); t9.start(); t10.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); t6.join(); t7.join(); t8.join(); t9.join(); t10.join(); knowledge.evaluateNoReturn(".end_time = #get_time();" + ".total_time = .end_time - .start_time;" + ".total_time_in_seconds = #double(.total_time) / 1000000000"); knowledge.set(".num_threads", numThreads); knowledge.set(".target", target); knowledge.set(".counter", SynchronizedCounter.counter); knowledge.evaluateNoReturn(".avg_hertz = .counter / .total_time_in_seconds"); knowledge.evaluateNoReturn(".avg_hertz_per_thread = .avg_hertz / .num_threads"); knowledge.print("SYNCHRONIZE:\n"); knowledge.print(" Time: {.total_time_in_seconds} s\n"); knowledge.print(" Hz: {.avg_hertz}\n Thread Hz: {.avg_hertz_per_thread}\n"); // free the underlying C++ heap knowledge.free(); } public static void testLockedCounter() throws InterruptedException, Exception { KnowledgeBase knowledge = new KnowledgeBase(); Thread t1 = new Thread(new LockCounter()); Thread t2 = new Thread(new LockCounter()); Thread t3 = new Thread(new LockCounter()); Thread t4 = new Thread(new LockCounter()); Thread t5 = new Thread(new LockCounter()); Thread t6 = new Thread(new LockCounter()); Thread t7 = new Thread(new LockCounter()); Thread t8 = new Thread(new LockCounter()); Thread t9 = new Thread(new LockCounter()); Thread t10 = new Thread(new LockCounter()); knowledge.evaluateNoReturn(".start_time = #get_time()"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); t7.start(); t8.start(); t9.start(); t10.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); t6.join(); t7.join(); t8.join(); t9.join(); t10.join(); knowledge.evaluateNoReturn(".end_time = #get_time();" + ".total_time = .end_time - .start_time;" + ".total_time_in_seconds = #double(.total_time) / 1000000000"); knowledge.set(".num_threads", numThreads); knowledge.set(".target", target); knowledge.set(".counter", SynchronizedCounter.counter); knowledge.evaluateNoReturn(".avg_hertz = .counter / .total_time_in_seconds"); knowledge.evaluateNoReturn(".avg_hertz_per_thread = .avg_hertz / .num_threads"); knowledge.print("LOCK:\n"); knowledge.print(" Time: {.total_time_in_seconds} s\n"); knowledge.print(" Hz: {.avg_hertz}\n Thread Hz: {.avg_hertz_per_thread}\n"); // free the underlying C++ heap knowledge.free(); } public static void main(String...args) throws InterruptedException, Exception { System.out.println("Testing mutexing for counters"); System.out.println(" Target: " + target); System.out.println(" Threads: " + numThreads); testMadaraCounter(); testAtomicCounter(); testSynchronizedCounter(); testLockedCounter(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/LogFilterTest.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeType; import ai.madara.transport.QoSTransportSettings; import ai.madara.transport.TransportType; import ai.madara.transport.filters.LogAggregate; import ai.madara.transport.filters.LogRecord; /** * This class is a tester for the LogRecord filter classes */ public class LogFilterTest { public static void main (String...args) throws InterruptedException, Exception { QoSTransportSettings settings = new QoSTransportSettings(); settings.setHosts(new String[]{"239.255.0.1:4150"}); settings.setType(TransportType.MULTICAST_TRANSPORT); System.out.println ("Adding individual record log filter to receive."); settings.addReceiveFilter(KnowledgeType.ALL_TYPES, new LogRecord()); settings.addReceiveFilter(new LogAggregate()); System.out.println ("Adding individual record log filter to send."); settings.addSendFilter(KnowledgeType.ALL_TYPES, new LogRecord()); settings.addSendFilter(new LogAggregate()); KnowledgeBase knowledge = new KnowledgeBase("", settings); System.out.println ("Beginning to loop."); for (int i = 0; i < 60; ++i) { System.out.println ("Sending an update."); knowledge.set(".base", i); knowledge.evaluateNoReturn(".i[0->10)(updates.{.i}=.base * 5 + .i)"); java.lang.Thread.sleep(1000); } // print all knowledge knowledge.print(); knowledge.print("And we're done.\n"); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/LoggerTest.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.logger.GlobalLogger; import ai.madara.logger.Logger; /** * This class is a tester for the ai.madara.logger package */ public class LoggerTest { public static void testLogger() throws MadaraDeadObjectException { KnowledgeBase knowledge = new KnowledgeBase(); Logger logger = new Logger(); logger.setLevel(5); logger.setTimestampFormat("%Y-%m-%d %H:%M:%S: "); knowledge.attachLogger(logger); System.out.println("***TESTING LOGGER***"); System.out.println(" Testing defaults"); logger.log(0, " This is being printed directly to logger.\n"); knowledge.print(" This should be printed to terminal\n"); logger.clear(); System.out.println(" Disabling terminal output"); knowledge.print(" This should not be printed to terminal\n"); System.out.println(" Enabling file output"); logger.addFile("LoggerTest_Logger.txt"); knowledge.print(" This should be printed to terminal and file\n"); logger.log(0, " This should be printed to terminal and file\n"); } public static void testGlobalLogger() throws MadaraDeadObjectException { KnowledgeBase knowledge = new KnowledgeBase(); System.out.println("***TESTING GLOBALLOGGER***"); System.out.println(" Testing defaults"); knowledge.print(" This should be printed to terminal\n"); GlobalLogger.clear(); System.out.println(" Disabling terminal output"); knowledge.print(" This should not be printed to terminal\n"); System.out.println(" Enabling terminal output"); GlobalLogger.addTerm(); knowledge.print(" This should be printed to terminal\n"); System.out.println(" Attaching GlobalLogger via toLogger()"); Logger logger = GlobalLogger.toLogger(); knowledge.attachLogger(logger); logger.setTimestampFormat("%Y-%m-%d %H:%M:%S: "); System.out.println(" Adding file LoggerTest_GlobalLogger.txt"); GlobalLogger.addFile("LoggerTest_GlobalLogger.txt"); knowledge.print(" This should be printed to terminal and file\n"); logger.log(0, " This should be printed to terminal and file\n"); } public static void main(String...args) throws Exception { testLogger(); testGlobalLogger(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/ProducerConsumerQueueTest.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import java.util.Random; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeRecord; import ai.madara.knowledge.containers.Integer; import ai.madara.knowledge.containers.Queue; import ai.madara.threads.BaseThread; import ai.madara.threads.Threader; // a counter thread that works with other counters public class ProducerConsumerQueueTest { static class Producer extends BaseThread { // Producer's initialization method public void init(KnowledgeBase context) throws MadaraDeadObjectException { generator = new Random(System.currentTimeMillis()); queue = new Queue(); queue.setName(context, ".jobs"); queue.resize(-1); } // Producer's run method. public void run() throws MadaraDeadObjectException { // generate a new job until terminated long job = (long)generator.nextInt(4); queue.enqueue(job); } // Producer's cleanup method public void cleanup() { queue.free(); } Random generator; Queue queue; } static class Consumer extends BaseThread { // Consumer's initialization method public void init(KnowledgeBase context) throws MadaraDeadObjectException { queue = new Queue(); queue.setName(context, ".jobs"); queue.resize(-1); jobsCompleted = new Integer(); jobsCompleted.setName(context, ".jobsCompleted"); } // Consumer's run method. public void run() throws MadaraDeadObjectException { KnowledgeRecord job = queue.dequeue(false); if(job.isValid()) { long value = job.toLong(); if(value == 0) { System.out.println(jobsCompleted.get() + ": Checking News"); } else if(value == 1) { System.out.println(jobsCompleted.get() + ": Checking Stocks"); } else if(value == 2) { System.out.println(jobsCompleted.get() + ": Checking Email"); } else if(value == 3) { System.out.println(jobsCompleted.get() + ": Checking Schedule"); } else { System.out.println(jobsCompleted.get() + ": Unknown Job Type"); } jobsCompleted.inc(); } // clean up the removed job job.free(); } // Consumer's cleanup method public void cleanup() { // clean up the private copies of our queue and counter queue.free(); jobsCompleted.free(); } Queue queue; Integer jobsCompleted; } public static void main(String...args) throws InterruptedException, Exception { KnowledgeBase knowledge = new KnowledgeBase(); Threader threader = new Threader(knowledge); Integer jobsCompleted = new Integer(); jobsCompleted.setName(knowledge, ".jobsCompleted"); Queue jobs = new Queue(); jobs.setName(knowledge, ".jobs"); jobs.resize(100); // run the two counter threads, one at 20hz and one at 40hz threader.run(20.0, "producer", new Producer()); threader.run(40.0, "consumer", new Consumer()); while(jobsCompleted.get() < 100) { java.lang.Thread.sleep(1000); } // terminate all threads threader.terminate(); // wait for all threads to finish threader.waitForThreads(); threader.free(); knowledge.free(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/ProfileArchitecture.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.EvalSettings; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeBase.CompiledExpression; import ai.madara.knowledge.KnowledgeBase.KnowledgeBaseLockedException; import ai.madara.knowledge.KnowledgeRecord; public class ProfileArchitecture { private static final String profile_file = "profile_expressions.txt"; private static final List<Test> tests = new ArrayList<Test> (); private static void warmup (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { System.out.println ("Warming up compilation and evaluation caches..."); knowledge.compile ("var1 = 10"); knowledge.compile ("var2 = 15"); knowledge.compile ("++var3"); knowledge.compile ("++var4"); for (int x = 0; x < 50000; ++x) knowledge.evaluate ("++var2").free (); for (int x = 0; x < 50000; ++x) knowledge.evaluate ("var2 += 1").free (); } private static void compileExpressions (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { System.out.println ("Compiling all expressions..."); Timer timer = new Timer (); for (Test test : tests) { timer.start (); test.expression = knowledge.compile (test.test); timer.stop (); test.compileTime = timer.elapsed (); } } private static void evaluateExpressions (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { System.out.println ("Evaluating all expressions 10,000 times..."); EvalSettings defaultSettings = new EvalSettings (); //Make sure default eval settings are created int i = 0; for (Test test : tests) { test.maxTime = Long.MIN_VALUE; test.minTime = Long.MAX_VALUE; System.out.println (" [" + i++ + "] Evaluating " + test.test); for (int j = 0; j < 100; ++j) { Timer timer = new Timer (); timer.start (); KnowledgeRecord kr = knowledge.evaluate (test.expression, defaultSettings); timer.stop (); kr.free (); test.maxTime = Math.max (timer.elapsed (), test.maxTime); test.minTime = Math.min (timer.elapsed (), test.minTime); } Timer timer = new Timer (); timer.start (); for (int j = 0; j < 10000; ++j) { knowledge.evaluate (test.expression, defaultSettings).free (); } timer.stop (); test.averageTime = timer.elapsed () / 10000; } } private static void printResults () { System.out.println ("\n\n"); System.out.println (String.format ("%18s | %13s | %13s | %13s | %13s", "Expression", "Compile time", "Min eval time", "Max eval time", "Avg eval time")); for (Test test : tests) { System.out.println (String.format ("%18s %13d %13d %13d %13d", test.test.subSequence (0, Math.min (test.test.length (),18)), test.compileTime, test.minTime, test.maxTime, test.averageTime)); } } public static void main (String...args) throws Exception { KnowledgeBase knowledge = new KnowledgeBase (); BufferedReader br = new BufferedReader (new FileReader (profile_file)); String line = null; while ( (line = br.readLine ()) != null) tests.add (new Test (line)); br.close (); if (tests.size () > 0) { warmup (knowledge); compileExpressions (knowledge); evaluateExpressions (knowledge); printResults (); } } private static class Test { public String test; public long maxTime; public long minTime; public long compileTime; public long averageTime; public CompiledExpression expression; public Test (String test) { this.test = test; } } private static class Timer { private long start = 0; private long stop = 0; public void start () { start = System.nanoTime (); } public void stop () { stop = System.nanoTime (); } public long elapsed () { return stop - start; } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/TestKnowledgeBase.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeMap; import ai.madara.knowledge.containers.Integer; import ai.madara.knowledge.containers.String; /** * This class is a tester for basic KnowledgeBase functionality */ public class TestKnowledgeBase { public static void main (java.lang.String...args) throws InterruptedException, Exception { KnowledgeBase knowledge = new KnowledgeBase(); Integer age = new Integer(); age.setName(knowledge, "age"); age.set(24); String name = new String(); name.setName(knowledge, "name"); name.set("Alfred Mooney"); String occupation = new String(); occupation.setName(knowledge, "occupation"); occupation.set("Moonlighter"); java.lang.String contents = knowledge.toString(); System.out.println(contents); knowledge.set("device.0.test.settings", "This is a test (0)"); knowledge.set("device.1.test.settings", "This is a test (1)"); knowledge.set("device.2.test.settings", "This is a test (2)"); knowledge.set("device.2", "is a real device"); knowledge.set("device.location", "USA"); KnowledgeMap deviceSettings = knowledge.toKnowledgeMap("device.", "settings"); System.out.print("Testing toKnowledgeMap with suffix and prefix: "); if (deviceSettings.containsKey("device.0.test.settings") && deviceSettings.containsKey("device.1.test.settings") && deviceSettings.containsKey("device.2.test.settings") && !deviceSettings.containsKey("device.2") && !deviceSettings.containsKey("device.location")) { System.out.println("SUCCESS"); } else { System.out.println("FAIL"); } // print all knowledge knowledge.print(); knowledge.print("And we're done.\n"); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/TestReasoningThroughput.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.KnowledgeBase.CompiledExpression; import ai.madara.knowledge.KnowledgeBase.KnowledgeBaseLockedException; import ai.madara.knowledge.KnowledgeRecord; public class TestReasoningThroughput { private static final double GHZ = 1000000000; private static final double MHZ = 1000000; private static final double KHZ = 1000; private static final long RUNCOUNT = 10; private static final long ITERATIONS = 100000; private static final long EVALUATIONS = RUNCOUNT * ITERATIONS; private static List<Test> tests = new ArrayList<Test> (); private static abstract class Test { public long elapsed = 0; public long hertz = 0; public abstract long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException; public abstract String name (); } private static class SimpleReinforcement extends Test { @Override public String name () { return "KaRL: Simple Reinforcements"; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); timer.start (); for (int x = 0; x < ITERATIONS; ++x) { knowledge.evaluateNoReturn ("++.var1"); } timer.stop (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class LargeReinforcement extends Test { @Override public String name () { return "KaRL: Large Reinforcements"; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); long maxSize = ITERATIONS > 1000 ? 1000 : ITERATIONS; long actualIterations = ITERATIONS > 1000 ? ITERATIONS / 1000 : 1; StringBuilder sb = new StringBuilder (); for (int x = 0; x < maxSize; x++) sb.append ("++.var1;"); final String eval = sb.toString (); timer.start (); for (int x = 0; x < actualIterations; ++x) { knowledge.evaluateNoReturn (eval); } timer.stop (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class SimpleInference extends Test { @Override public String name () { return "KaRL: Simple Inference "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); timer.start (); for (int x = 0; x < ITERATIONS; ++x) { knowledge.evaluateNoReturn ("1 => ++.var1"); } timer.stop (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class LargeInference extends Test { @Override public String name () { return "KaRL: Large Inference "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); long maxSize = ITERATIONS > 1000 ? 1000 : ITERATIONS; long actualIterations = ITERATIONS > 1000 ? ITERATIONS / 1000 : 1; StringBuilder sb = new StringBuilder (); for (int x = 0; x < maxSize; x++) sb.append ("1 => ++.var1;"); final String eval = sb.toString (); timer.start (); for (int x = 0; x < actualIterations; ++x) { knowledge.evaluateNoReturn (eval); } timer.stop (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class CompiledSR extends Test { @Override public String name () { return "KaRL: Compiled SR "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); CompiledExpression ce = knowledge.compile ("++.var1"); timer.start (); for (int x = 0; x < ITERATIONS; ++x) { knowledge.evaluateNoReturn (ce); } timer.stop (); ce.free (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class CompiledLR extends Test { @Override public String name () { return "KaRL: Compiled LR "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); long maxSize = ITERATIONS > 1000 ? 1000 : ITERATIONS; long actualIterations = ITERATIONS > 1000 ? ITERATIONS / 1000 : 1; StringBuilder sb = new StringBuilder (); for (int x = 0; x < maxSize; x++) sb.append ("++.var1;"); CompiledExpression ce = knowledge.compile (sb.toString ()); timer.start (); for (int x = 0; x < actualIterations; ++x) { knowledge.evaluateNoReturn (ce); } timer.stop (); ce.free (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class CompiledSI extends Test { @Override public String name () { return "KaRL: Compiled SI "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); CompiledExpression ce = knowledge.compile ("1 => ++.var1"); timer.start (); for (int x = 0; x < ITERATIONS; ++x) { knowledge.evaluateNoReturn (ce); } timer.stop (); ce.free (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class CompiledLI extends Test { @Override public String name () { return "KaRL: Compiled LI "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); long maxSize = ITERATIONS > 1000 ? 1000 : ITERATIONS; long actualIterations = ITERATIONS > 1000 ? ITERATIONS / 1000 : 1; StringBuilder sb = new StringBuilder (); for (int x = 0; x < maxSize; x++) sb.append ("1 => ++.var1;"); CompiledExpression ce = knowledge.compile (sb.toString ()); timer.start (); for (int x = 0; x < actualIterations; ++x) { knowledge.evaluateNoReturn (ce); } timer.stop (); ce.free (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class LoopedSR extends Test { @Override public String name () { return "KaRL: Looped SR "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); knowledge.set (".iterations", ITERATIONS); CompiledExpression ce = knowledge.compile (".var2[.iterations) (++.var1)"); timer.start (); knowledge.evaluateNoReturn (ce); timer.stop (); ce.free (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class OptimalLoop extends Test { @Override public String name () { return "KaRL: Optimal Loop "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); knowledge.set (".iterations", ITERATIONS); CompiledExpression ce = knowledge.compile (".var2[.iterations)"); timer.start (); knowledge.evaluateNoReturn (ce); timer.stop (); ce.free (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class LoopedSI extends Test { @Override public String name () { return "KaRL: Looped SI "; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); knowledge.set (".iterations", ITERATIONS); CompiledExpression ce = knowledge.compile (".var2[.iterations) (1 => ++.var1)"); timer.start (); knowledge.evaluateNoReturn (ce); timer.stop (); ce.free (); KnowledgeRecord kr = knowledge.get (".var1"); print (timer.elapsed (), kr, name ()); kr.free (); return timer.elapsed (); } } private static class OptimalReinforcement extends Test { @Override public String name () { return "Java: Optimal Reinforcement"; } @Override public long test (KnowledgeBase knowledge) throws KnowledgeBaseLockedException, MadaraDeadObjectException { knowledge.clear (); Timer timer = new Timer (); int var1 = 0; timer.start (); for (int x = 0; x < ITERATIONS; ++x) ++var1; timer.stop (); print (timer.elapsed (), "" + var1, name ()); return timer.elapsed (); } } public static String formatNumber (long num) { return NumberFormat.getInstance ().format (num); } public static void print (long time, KnowledgeRecord value, String type) { print (time, value.toString (), type); } public static void print (long time, String value, String type) { System.out.println (type); System.out.println (" ops=" + formatNumber (ITERATIONS) + ", time=" + formatNumber (time) + " ns, value=" + value); } public static String toLegibleHertz (final long hertz) { double freq = (double) hertz / GHZ; if (freq >= 1) return "" + (Math.round (freq * 100.0) / 100.0) + " ghz"; freq = (double) hertz / MHZ; if (freq >= 1) return "" + (Math.round (freq * 100.0) / 100.0) + " mhz"; freq = (double) hertz / KHZ; if (freq >= 1) return "" + (Math.round (freq * 100.0) / 100.0) + " khz"; freq = (double) hertz; return "" + (Math.round (freq * 100.0) / 100.0) + " hz"; } public static void main (String...args) throws KnowledgeBaseLockedException, MadaraDeadObjectException { KnowledgeBase knowledge = new KnowledgeBase (); tests.add (new SimpleReinforcement ()); tests.add (new LargeReinforcement ()); tests.add (new SimpleInference ()); tests.add (new LargeInference ()); tests.add (new CompiledSR ()); tests.add (new CompiledLR ()); tests.add (new CompiledSI ()); tests.add (new CompiledLI ()); tests.add (new LoopedSR ()); tests.add (new OptimalLoop ()); tests.add (new LoopedSI ()); tests.add (new OptimalReinforcement ()); for (int x = 0; x < RUNCOUNT; ++x) { for (Test test : tests) { test.elapsed += test.test (knowledge); } } for (Test test : tests) { if (test.elapsed == 0) test.elapsed = 1; test.hertz = (1000000000 * EVALUATIONS) / test.elapsed; } System.out.println ("\n\nTotal time taken for each Test with " + ITERATIONS + " iterations * " + RUNCOUNT + " tests was:"); System.out.println ("========================================================================="); for (Test test : tests) { System.out.println (String.format (" %s\t\t%30s ns", test.name (), formatNumber (test.elapsed))); } System.out.println ("========================================================================="); System.out.println ("\n\nAverage time taken per rule evaluation was:"); System.out.println ("========================================================================="); for (Test test : tests) { System.out.println (String.format (" %s\t\t%30s ns", test.name (), formatNumber (test.elapsed / EVALUATIONS))); } System.out.println ("========================================================================="); System.out.println ("\n\nHertz for each Test with " + ITERATIONS + " iterations * " + RUNCOUNT + " tests was:"); System.out.println ("========================================================================="); for (Test test : tests) { System.out.println (String.format (" %s\t\t%33s", test.name (), toLegibleHertz (test.hertz))); } System.out.println ("========================================================================="); } private static class Timer { private long start = 0; private long stop = 0; public void start () { start = System.nanoTime (); } public void stop () { stop = System.nanoTime (); } public long elapsed () { return stop - start; } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/TestRegistry.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.filters.EndpointClear; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.containers.Integer; import ai.madara.threads.BaseThread; import ai.madara.threads.Threader; import ai.madara.transport.QoSTransportSettings; import ai.madara.transport.TransportType; /** * This class is a tester for the RegistryClient transport */ public class TestRegistry { private static class Publisher extends BaseThread { Publisher (KnowledgeBase data) throws MadaraDeadObjectException { knowledge = data; value.setName(data,"value"); } @Override public void run() throws MadaraDeadObjectException { value.inc(); knowledge.print(); knowledge.sendModifieds(); } private final KnowledgeBase knowledge; private final Integer value = new Integer(); } public static void main(String...args) throws Exception { String host = "localhost:40000"; if(args.length == 1) { host = args[0]; } //create transport settings for a multicast transport QoSTransportSettings settings = new QoSTransportSettings(); //assume a registry server on the local host at port 40000 settings.setHosts(new String[]{host}); settings.setType(TransportType.REGISTRY_CLIENT); //create endpoint clear filter, which will tidy up registry updates EndpointClear filter = new EndpointClear(); filter.addReceiveFilterTo(settings); KnowledgeBase knowledge = new KnowledgeBase("", settings); Threader threader = new Threader(knowledge); threader.run(1.0, "publisher", new TestRegistry.Publisher(knowledge)); threader.waitForThreads(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/TestUtility.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.util.Utility; /** * This class is a tester for basic Utility class functionality */ public class TestUtility { public static void main (java.lang.String...args) throws InterruptedException, Exception { java.lang.String version = Utility.getVersion(); System.out.println("MADARA Version information:"); System.out.println(" " + version); System.out.println("Testing sleeps and timestamping utilities..."); long start = Utility.getTime(); // sleep for 4 seconds Thread.sleep(4000); long end = Utility.getTime(); System.out.println(" Slept for 4,000ms in Java. " + "Resulting nanosecond diff: " + (end - start)); start = Utility.getTime(); // sleep for 4 seconds Utility.sleep(4.0); end = Utility.getTime(); System.out.println(" Slept for 4.0s in MADARA. " + "Resulting nanosecond diff: " + (end - start)); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/ThreadedCounter.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.containers.Integer; import ai.madara.threads.BaseThread; import ai.madara.threads.Threader; /** * This class is a tester for the ai.madara.knowledge.containers package */ public class ThreadedCounter extends BaseThread { /** * A thread-safe counter **/ public Integer counter; static long target = 10000000; /** * Initialize the counter variable * @throws MadaraDeadObjectException **/ public void init(KnowledgeBase knowledge) throws MadaraDeadObjectException { counter = new Integer(); counter.setName(knowledge, ".counter"); } /** * Executes the main thread logic. * @throws MadaraDeadObjectException **/ public void run() throws MadaraDeadObjectException { // increment the counter long value = counter.inc(); //System.out.println ("Counter value is " + value); } /** * Clean up the counter residue **/ public void cleanup() { // free the underlying C++ heap counter.free(); } public static void main(String...args) throws InterruptedException, Exception { KnowledgeBase knowledge = new KnowledgeBase(); //GlobalLogger.setLevel(LogLevels.LOG_MINOR.value()); Integer counter = new Integer(); counter.setName(knowledge, ".counter"); long numThreads = 1; double hertz = 300000; if (args.length > 0) { // first arg is the number of threads try { numThreads = java.lang.Long.parseLong(args[0]); } catch (NumberFormatException e) { System.err.println("Argument for numThreads " + args[0] + " must be an integer."); System.exit(1); } if (args.length > 1) { // second arg is the target try { target = java.lang.Long.parseLong(args[1]); } catch (NumberFormatException e) { System.err.println("Argument for target " + args[1] + " must be an integer."); System.exit(1); } if (args.length > 2) { // second arg is the target try { hertz = java.lang.Double.parseDouble(args[2]); } catch (NumberFormatException e) { System.err.println("Argument for hertz " + args[2] + " must be a double."); System.exit(1); } } } } // create a threader for running threads Threader threader = new Threader(knowledge); System.err.println("Test parameters:"); System.err.println(" target:" + target); System.err.println(" threads:" + numThreads); System.err.println(" hertz:" + hertz); for (int i = 0; i < numThreads; ++i) { threader.startPaused(hertz, "thread" + i, new ThreadedCounter()); } // start 4 threads in a paused state //threader.startPaused(1000000.0, "thread1", new ThreadedCounter()); knowledge.evaluateNoReturn(".start_time = #get_time()"); // resume all threads threader.resume(); while(counter.get() < target) { // sleep for a second before checking again java.lang.Thread.sleep(250); } knowledge.evaluateNoReturn(".end_time = #get_time();" + ".total_time = .end_time - .start_time;" + ".total_time_in_seconds = #double(.total_time) / 1000000000"); knowledge.set(".num_threads", numThreads); knowledge.set(".target", target); knowledge.evaluateNoReturn(".avg_hertz = .counter / .total_time_in_seconds"); knowledge.evaluateNoReturn(".avg_hertz_per_thread = .avg_hertz / .num_threads"); // resume all threads threader.terminate(); // print all knowledge knowledge.print(); knowledge.print("And we're done.\n"); // wait for all threads to finish threader.waitForThreads(); // free the underlying C++ heap threader.free(); counter.free(); knowledge.free(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/tests/ThreadedCounterBlaster.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.tests; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.containers.Integer; import ai.madara.threads.BaseThread; import ai.madara.threads.Threader; /** * This class is a tester for the ai.madara.knowledge.containers package */ public class ThreadedCounterBlaster extends BaseThread { /** * A thread-safe counter **/ public Integer counter; static long target = 100000000; /** * Initialize the counter variable * @throws MadaraDeadObjectException **/ public void init(KnowledgeBase knowledge) throws MadaraDeadObjectException { counter = new Integer(); counter.setName(knowledge, ".counter"); } /** * Executes the main thread logic. * @throws MadaraDeadObjectException **/ public void run() throws MadaraDeadObjectException { // increment the counter until it is at least equal to the value long value = counter.inc(); while (value < target) value = counter.inc(); } /** * Clean up the counter residue **/ public void cleanup() { // free the underlying C++ heap counter.free(); } public static void main(String...args) throws InterruptedException, Exception { KnowledgeBase knowledge = new KnowledgeBase(); Integer counter = new Integer(); counter.setName(knowledge, ".counter"); long numThreads = 1; if (args.length > 0) { // first arg is the number of threads try { numThreads = java.lang.Long.parseLong(args[0]); } catch (NumberFormatException e) { System.err.println("Argument for numThreads " + args[0] + " must be an integer."); System.exit(1); } if (args.length > 1) { // second arg is the target try { target = java.lang.Long.parseLong(args[1]); } catch (NumberFormatException e) { System.err.println("Argument for target " + args[1] + " must be an integer."); System.exit(1); } } } // create a threader for running threads Threader threader = new Threader(knowledge); for (int i = 0; i < numThreads; ++i) { threader.run("thread" + i, new ThreadedCounterBlaster()); } // start 4 threads in a paused state //threader.run("thread1", new ThreadedCounterBlaster()); knowledge.evaluateNoReturn(".start_time = #get_time()"); // resume all threads threader.resume(); while(counter.get() < target) { // sleep for a second before checking again java.lang.Thread.sleep(250); } knowledge.evaluateNoReturn(".end_time = #get_time();" + ".total_time = .end_time - .start_time;" + ".total_time_in_seconds = #double(.total_time) / 1000000000"); knowledge.set(".num_threads", numThreads); knowledge.set(".target", target); knowledge.evaluateNoReturn(".avg_hertz = .counter / .total_time_in_seconds"); knowledge.evaluateNoReturn(".avg_hertz_per_thread = .avg_hertz / .num_threads"); // resume all threads threader.terminate(); // print all knowledge knowledge.print(); knowledge.print("And we're done.\n"); // wait for all threads to finish threader.waitForThreads(); // free the underlying C++ heap threader.free(); counter.free(); knowledge.free(); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/threads/BaseThread.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.threads; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; import ai.madara.knowledge.containers.Integer; /** * An extensible thread **/ public abstract class BaseThread { /** * Initializes thread with a data plane (a shared MADARA context) * @param context context for querying/modifying current program state * @throws MadaraDeadObjectException **/ public void init(KnowledgeBase context) throws MadaraDeadObjectException { } /** * Executes the main thread logic. * @throws MadaraDeadObjectException **/ abstract public void run() throws MadaraDeadObjectException; /** * Cleans up any artifacts not taken care of by the Java VM. It will be * very rare to ever override the default behavior. **/ public void cleanup() { } /** * Returns the unique name of the thread * @return the name of the thread **/ public String getName() { return name; } /** * flag from Threader indicating if thread is requested to be terminated **/ public Integer terminated; /** * flag from Threader indicating if thread is paused **/ public Integer paused; /** * the unique name of the thread, set by Threader **/ String name; }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/threads/Threader.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.threads; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.knowledge.KnowledgeBase; /** * A manager of user threads **/ public class Threader extends MadaraJNI { private native long jni_Threader(); private native long jni_Threader(long dataPlane); private native void jni_freeThreader(long cptr); private native void jni_run(long cptr, java.lang.String name, Object obj, boolean paused); private native void jni_runhz(long cptr, double hertz, java.lang.String name, Object obj, boolean paused); private native void jni_pauseThread(long cptr, java.lang.String name); private native void jni_pause(long cptr); private native void jni_waitThread(long cptr, java.lang.String name); private native void jni_wait(long cptr); private native void jni_terminateThread(long cptr, java.lang.String name); private native void jni_terminate(long cptr); private native void jni_resumeThread(long cptr, java.lang.String name); private native void jni_resume(long cptr); /** * Default constructor **/ public Threader() { setCPtr(jni_Threader()); } /** * Constructor with data plane * @param dataPlane the knowledge base for threads to use for data **/ public Threader(KnowledgeBase dataPlane) throws MadaraDeadObjectException { setCPtr(jni_Threader(dataPlane.getCPtr())); } /** * Deletes the C++ instantiation. To prevent memory leaks, this <b>must</b> be called * before an instance of Threader gets garbage collected **/ public void free() { jni_freeThreader(getCPtr()); setCPtr(0); } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } /** * Runs a thread. The thread's run method will only be called once. * @param name the unique name of the thread * @param thread the thread to run **/ public void run (String name, BaseThread thread) throws MadaraDeadObjectException { thread.name = name; jni_run(getCPtr(), name, thread, false); } /** * Runs a thread. The thread's run method will be called at the specified * hertz (executions of run per second) * @param hertz the intended frequency of executions per second * @param name the unique name of the thread * @param thread the thread to run **/ public void run(double hertz, String name, BaseThread thread) throws MadaraDeadObjectException { thread.name = name; jni_runhz(getCPtr(), hertz, name, thread, false); } /** * Starts a thread in a paused state. Once resumed, the run method will * only be called once. * @param name the unique name of the thread * @param thread the thread to start in a paused state **/ public void startPaused(String name, BaseThread thread) throws MadaraDeadObjectException { thread.name = name; jni_run(getCPtr(), name, thread, true); } /** * Starts a thread in a paused state. Once resumed, the run method will * be called at the specified hertz. * @param hertz the intended frequency of executions per second * @param name the unique name of the thread * @param thread the thread to start in a paused state **/ public void startPaused(double hertz, String name, BaseThread thread) throws MadaraDeadObjectException { thread.name = name; jni_runhz(getCPtr(), hertz, name, thread, true); } /** * Requests for the specified thread to pause * @param name the unique name of the thread requested to pause **/ public void pause(String name) throws MadaraDeadObjectException { jni_pauseThread(getCPtr(), name); } /** * Requests all threads to pause **/ public void pause() throws MadaraDeadObjectException { jni_pause(getCPtr()); } /** * Waits for a specific thread to finish * @param name the unique name of the thread **/ public void waitForThread(String name) throws MadaraDeadObjectException { jni_waitThread(getCPtr(), name); } /** * Waits for all threads to finish **/ public void waitForThreads() throws MadaraDeadObjectException { jni_wait(getCPtr()); } /** * Requests for the specified thread to terminate * @param name the unique name of the thread **/ public void terminate(String name) throws MadaraDeadObjectException { jni_terminateThread(getCPtr(), name); } /** * Requests all threads to terminate **/ public void terminate() throws MadaraDeadObjectException { jni_terminate(getCPtr()); } /** * Requests for the specified thread to resume if paused * @param name the unique name of the thread **/ public void resume(String name) throws MadaraDeadObjectException { jni_resumeThread(getCPtr(), name); } /** * Requests all threads to resume if paused **/ public void resume() throws MadaraDeadObjectException { jni_resume(getCPtr()); } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/DropType.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport; public enum DropType { PACKET_DROP_DETERMINISTIC(0), PACKET_DROP_PROBABLISTIC(1); private int num; private DropType(int num) { this.num = num; } /** * Get the integer value of this enum * * @return value of the enum */ public int value() { return num; } public static DropType getType(int val) { for (DropType t : values()) { if (t.value() == val) return t; } return null; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/QoSTransportSettings.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport; import ai.madara.MadaraJNI; import ai.madara.exceptions.MadaraDeadObjectException; import ai.madara.filters.BufferFilter; import ai.madara.knowledge.KnowledgeType; import ai.madara.transport.filters.AggregateFilter; import ai.madara.transport.filters.RecordFilter; public class QoSTransportSettings extends TransportSettings { private native long jni_QoSTransportSettings(); private native long jni_QoSTransportSettings(long cptr); private static native void jni_freeQoSTransportSettings(long cptr); private native void jni_addBufferFilter(long cptr, long filter); private native void jni_addBufferFilterObj(long cptr, BufferFilter filter); private native void jni_clearBufferFilters(long cptr); private native int jni_getNumberOfBufferFilters(long cptr); private native void jni_addRebroadcastRecordFilter(long cptr, int type, RecordFilter filter); private native void jni_addRebroadcastAggregateFilter(long cptr, AggregateFilter filter); private native void jni_addSendRecordFilter(long cptr, int type, RecordFilter filter); private native void jni_addSendAggregateFilter(long cptr, AggregateFilter filter); private native void jni_addReceiveRecordFilter(long cptr, int type, RecordFilter filter); private native void jni_addReceiveAggregateFilter(long cptr, AggregateFilter filter); private native void jni_setRebroadcastTtl(long cptr, int ttl); private native int jni_getRebroadcastTtl(long cptr); private native void jni_enableParticipantTtl(long cptr, int ttl); private native int jni_getParticipantTtl(long cptr); private native void jni_saveQoS(long cptr, java.lang.String filenmae); private native void jni_loadQoS(long cptr, java.lang.String filename); private native void jni_setSendBandwidthLimit(long cptr, int limit); private native int jni_getSendBandwidthLimit(long cptr); private native void jni_setTotalBandwidthLimit(long cptr, int limit); private native int jni_getTotalBandwidthLimit(long cptr); private native void jni_setDeadline(long cptr, int deadline); private native int jni_getDeadline(long cptr); private native void jni_addTrustedPeer(long cptr, java.lang.String host); private native void jni_addBannedPeer(long cptr, java.lang.String host); private native void jni_updateDropRate(long cptr, double percentage, int type, int burstamount); public QoSTransportSettings() { setCPtr(jni_QoSTransportSettings()); } public QoSTransportSettings(QoSTransportSettings transportSettings) throws MadaraDeadObjectException { setCPtr(jni_QoSTransportSettings(transportSettings.getCPtr())); } /** * Adds a BufferFilter to the filter chain. Buffer filters are applied just * after all other filters on send and before all other filters on receive. * * @param filter a filter to encode and decode buffers */ public void addFilter(BufferFilter filter) throws MadaraDeadObjectException { if (filter instanceof MadaraJNI) { MadaraJNI superClass = (MadaraJNI)filter; jni_addBufferFilter(getCPtr(), superClass.getCPtr()); } else { jni_addBufferFilterObj(getCPtr(), filter); } } /** * Clears the list of buffer filters */ public void clearBufferFilters() throws MadaraDeadObjectException { jni_clearBufferFilters(getCPtr()); } /** * Adds a filter that will be applied to certain types after receiving and * before rebroadcasting, if time-to-live is greater than 0 * * @param type the types to add the filter to * @param filter Madara callback function */ public void addRebroadcastFilter(KnowledgeType type, RecordFilter filter) throws MadaraDeadObjectException { jni_addRebroadcastRecordFilter(getCPtr(), type.value(), filter); } /** * Adds an aggregate update filter that will be applied before rebroadcasting, * after individual record filters. * * @param filter Madara callback function */ public void addRebroadcastFilter(AggregateFilter filter) throws MadaraDeadObjectException { jni_addRebroadcastAggregateFilter(getCPtr(), filter); } /** * Adds a filter that will be applied to certain types before sending * * @param type the types to add the filter to * @param filter Madara callback function */ public void addSendFilter(KnowledgeType type, RecordFilter filter) throws MadaraDeadObjectException { jni_addSendRecordFilter(getCPtr(), type.value(), filter); } /** * Adds an aggregate update filter that will be applied before sending, after * individual record filters. * * @param filter Madara callback function */ public void addSendFilter(AggregateFilter filter) throws MadaraDeadObjectException { jni_addSendAggregateFilter(getCPtr(), filter); } /** * Adds an aggregate filter for a map of variables to values before applying * updates to the Knowledge_Base * * @param type the types to add the filter to * @param filter Madara callback function */ public void addReceiveFilter(KnowledgeType type, RecordFilter filter) throws MadaraDeadObjectException { jni_addReceiveRecordFilter(getCPtr(), type.value(), filter); } /** * Adds an aggregate update filter that will be applied after receiving, after * individual record filters. * * @param filter Madara callback function */ public void addReceiveFilter(AggregateFilter filter) throws MadaraDeadObjectException { jni_addReceiveAggregateFilter(getCPtr(), filter); } /** * Sets the rebroadcast time-to-live for all sent packets * * @param ttl the time-to-live */ public void setRebroadcastTtl(int ttl) throws MadaraDeadObjectException { jni_setRebroadcastTtl(getCPtr(), ttl); } /** * Gets the rebroadcast time-to-live for all sent packets * * @return the rebroadcast time-to-live */ public int getRebroadcastTtl() throws MadaraDeadObjectException { return jni_getRebroadcastTtl(getCPtr()); } /** * Enables participation in rebroadcasts up to a certain ttl value * * @param ttl the time-to-live */ public void enableParticipantTtl(int ttl) throws MadaraDeadObjectException { jni_enableParticipantTtl(getCPtr(), ttl); } /** * Gets the rebroadcast time-to-live for all rebroadcasted packets * * @return the rebroadcast time-to-live */ public int getParticipantTtl() throws MadaraDeadObjectException { return jni_getParticipantTtl(getCPtr()); } /** * Sets the send bandwidth limit * * @param limit the bandwidth limit for sending packets */ public void setSendBandwidthLimit(int limit) throws MadaraDeadObjectException { jni_setSendBandwidthLimit(getCPtr(), limit); } /** * Gets the send bandwidth limit * * @return the bandwidth limit for sending packets */ public int getSendBandwidthLimit() throws MadaraDeadObjectException { return jni_getSendBandwidthLimit(getCPtr()); } /** * Sets the total bandwidth limit * * @param limit the bandwidth limit for all packets */ public void setTotalBandwidthLimit(int limit) throws MadaraDeadObjectException { jni_setTotalBandwidthLimit(getCPtr(), limit); } /** * Gets the total bandwidth limit * * @return the bandwidth limit for all packets */ public int getTotalBandwidthLimit() throws MadaraDeadObjectException { return jni_getTotalBandwidthLimit(getCPtr()); } /** * Sets the deadline (seconds) * * @param deadline the maximum lifetime for all packets in seconds */ public void setDeadline(int deadline) throws MadaraDeadObjectException { jni_setDeadline(getCPtr(), deadline); } /** * Gets the deadline (seconds) * * @return the maximum lifetime for all packets in seconds */ public int getDeadline() throws MadaraDeadObjectException { return jni_getDeadline(getCPtr()); } /** * Adds a trusted peer * * @param host the peer to add to the trusted list * */ void addTrustedPeer(java.lang.String host) throws MadaraDeadObjectException { jni_addTrustedPeer(getCPtr(), host); } /** * Adds a banned peer * * @param host the peer to add to the banned list * */ void addBannedPeer(java.lang.String host) throws MadaraDeadObjectException { jni_addBannedPeer(getCPtr(), host); } /** * Updates drop rate * * @param percentage the percentage of drops to enforce * @param type the type of drop policy to use * @param burstamount the amount of bursts of drops to enforce * */ void updateDropRate(double percentage, DropType type, int burstamount) throws MadaraDeadObjectException { jni_updateDropRate(getCPtr(), percentage, type.value(), burstamount); } /** * Saves the transport settings as a KnowledgeBase to a file * * @param filename the file to save the knowledge base to * **/ @Override public void save(String filename) throws MadaraDeadObjectException { jni_saveQoS(getCPtr(), filename); } /** * Loads the transport settings from a KnowledgeBase context file * * @param filename the file to save the knowledge base to * **/ @Override public void load(String filename) throws MadaraDeadObjectException { jni_loadQoS(getCPtr(), filename); } /** * Deletes the C instantiation. To prevent memory leaks, this <b>must</b> be * called before an instance of WaitSettings gets garbage collected */ public void free() { jni_freeQoSTransportSettings(getCPtr()); setCPtr(0); } /** * Cleans up underlying C resources * @throws Throwable necessary for override but unused */ @Override protected void finalize() throws Throwable { try { free(); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/TransportContext.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport; import ai.madara.MadaraJNI; import ai.madara.knowledge.KnowledgeMap; import ai.madara.knowledge.KnowledgeRecord; public class TransportContext extends MadaraJNI { private static native void jni_addRecord(long cptr, String key, long record); private static native void jni_clearRecords(long cptr); private static native long jni_getCurrentTime(long cptr); private static native String jni_getDomain(long cptr); private static native long jni_getMessageTime(long cptr); private static native long jni_getOperation(long cptr); private static native String jni_getOriginator(long cptr); private static native long jni_getReceiveBandwidth(long cptr); private static native void jni_getRecords(long cptr, MapReturn ret); private static native long jni_getSendBandwidth(long cptr); private KnowledgeMap currentMap = null; private TransportContext(long cptr) { setCPtr(cptr); } public static TransportContext fromPointer(long cptr) { return new TransportContext(cptr); } /** * Adds a record to the list that should be appended to send or rebroadcast. * @param key key of the record to add * @param record the record to add */ public void addRecord(String key, KnowledgeRecord record) { KnowledgeRecord value = record; if (value != null && !value.isNew()) value = record.clone(); jni_addRecord(getCPtr(), key, record == null ? 0 : record.getCPtr()); } /** * Clears records added through filtering operations. */ public void clearRecords() { jni_clearRecords(getCPtr()); } /** * Gets the current timestamp * @return the current time stamp */ public long getCurrentTime() { return jni_getCurrentTime(getCPtr()); } /** * Gets the current network domain * @return the network domain */ public String getDomain() { return jni_getDomain(getCPtr()); } /** * Gets the message timestamp * @return the message timestamp */ public long getMessageTime() { return jni_getMessageTime(getCPtr()); } /** * Get operation that the context is performing * @return operation type that is being performed */ public long getOperation() { return jni_getOperation(getCPtr()); } /** * Returns the current message originator * @return the current message originator */ public String getOriginator() { return jni_getOriginator(getCPtr()); } /** * Gets the receive bandwidth in bytes per second * @return the receive bandwidth in bytes per second */ public long getReceiveBandwidth() { return jni_getReceiveBandwidth(getCPtr()); } /** * Returns the additional records stored in the context. Do not free the resulting map * @return the additional records stored in the context */ private KnowledgeMap getRecords() { MapReturn jniRet = new MapReturn(); jni_getRecords(getCPtr(), jniRet); System.err.println("Got the records: " + jniRet.keys.length); // return new KnowledgeMap(jniRet.keys, jniRet.vals); return null; } /** * Gets the send/rebroadcast bandwidth in bytes per second * @return the send/rebroadcast bandwidth in bytes per second */ public long getSendBandwidth() { return jni_getSendBandwidth(getCPtr()); } private static class MapReturn { public String[] keys; public long[] vals; } }
0
java-sources/ai/madara/madara/3.2.3/ai/madara
java-sources/ai/madara/madara/3.2.3/ai/madara/transport/TransportReliability.java
/********************************************************************* * Copyright (c) 2013-2015 Carnegie Mellon University. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following acknowledgments and disclaimers. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The names "Carnegie Mellon University," "SEI" and/or * "Software Engineering Institute" shall not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact permission@sei.cmu.edu. * * 4. Products derived from this software may not be called "SEI" nor may "SEI" * appear in their names without prior written permission of * permission@sei.cmu.edu. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * * This material is based upon work funded and supported by the Department of * Defense under Contract No. FA8721-05-C-0003 with Carnegie Mellon University * for the operation of the Software Engineering Institute, a federally funded * research and development center. Any opinions, findings and conclusions or * recommendations expressed in this material are those of the author(s) and * do not necessarily reflect the views of the United States Department of * Defense. * * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE * MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND * WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. * * This material has been approved for public release and unlimited * distribution. * * @author James Edmondson <jedmondson@gmail.com> *********************************************************************/ package ai.madara.transport; /** * @author jdroot */ public enum TransportReliability { BEST_EFFORT(0), RELIABLE(1); private int num; private TransportReliability(int num) { this.num = num; } /** * Get the integer value of this enum * * @return value of the enum */ public int value() { return num; } public static TransportReliability getReliability(int val) { for (TransportReliability t : values()) { if (t.value() == val) return t; } return null; } }