Skip to content
Snippets Groups Projects
Commit 6ee86f8e authored by Mark Prediger's avatar Mark Prediger
Browse files

Macro Recorder tool to record service requests and replay them manually or on...

Macro Recorder tool to record service requests and replay them manually or on specified context events
parent dc9a35ad
No related branches found
No related tags found
No related merge requests found
Showing
with 2224 additions and 0 deletions
In order to work with the makro recorder you have to alter the source code of the universaal middleware. You have to change the method "assessContentSerialization" of the class "ServiceBusImpl.java" to the appended code.
After this change the ServiceBus will create a new textfile "test.txt" which will contain the serialized Service Requests and Service Responses.
public static synchronized void assessContentSerialization(Resource content) {
if (Constants.debugMode()) {
if (contentSerializer == null) {
contentSerializer = (MessageContentSerializer) moduleContext
.getContainer().fetchSharedObject(moduleContext,
contentSerializerParams);
if (contentSerializer == null)
return;
}
LogUtils
.logDebug(
moduleContext,
ServiceBusImpl.class,
"assessContentSerialization",
new Object[] { "Assessing message content serialization:" },
null);
// System.out.println(new RuntimeException().getStackTrace()[1]);
String str = contentSerializer.serialize(content);
if (content instanceof ServiceRequest) {
try {
if (file.exists()) {
out = new BufferedWriter(new FileWriter("test.txt",true));
}
else {
out = new BufferedWriter(new FileWriter("test.txt"));
}
out.write("\nNew Message:" + (new java.util.Date().getTime()) +"\n");
out.write(str);
out.close();
} catch (IOException e) {
LogUtils.logDebug(moduleContext, ServiceBusImpl.class, "assessContentSerialization", new Object[] {"could not write to test.txt"}, null);
e.printStackTrace();
}
}
LogUtils
.logDebug(
moduleContext,
ServiceBusImpl.class,
"assessContentSerialization",
new Object[] { "\n 1. serialization dump\n",
str,
"\n 2. deserialize & compare with the original resource\n" },
null);
new ResourceComparator().printDiffs(content,
(Resource) contentSerializer.deserialize(str));
}
}
\ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>org.universAAL.tools</groupId>
<modelVersion>4.0.0</modelVersion>
<packaging>bundle</packaging>
<artifactId>makro.recorder</artifactId>
<name>Makro recroder</name>
<version>1.1.1</version>
<dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.main</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.osgi.core</artifactId>
<version>1.2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.osgi.compendium</artifactId>
<version>1.2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.log</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.universAAL.middleware</groupId>
<artifactId>mw.container.osgi</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.universAAL.middleware</groupId>
<artifactId>mw.data.representation</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.universAAL.middleware</groupId>
<artifactId>mw.bus.context</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.universAAL.middleware</groupId>
<artifactId>mw.bus.service</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.universAAL.middleware</groupId>
<artifactId>mw.bus.ui</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.universAAL.ontology</groupId>
<artifactId>ont.phWorld</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.universAAL.support</groupId>
<artifactId>uaal.device.connector</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.universAAL.ontology</groupId>
<artifactId>ont.profile</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.universAAL.context</groupId>
<artifactId>ctxt.che</artifactId>
<version>1.1.1-SNAPSHOT</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-maven-milestone</id>
<name>Springframework Maven Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
<repository>
<id>central</id>
<name>Central Maven Repository</name>
<url>http://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>apache-snapshots</id>
<name>Apache Snapshots</name>
<url>http://people.apache.org/repo/m2-snapshot-repository</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<updatePolicy>daily</updatePolicy>
</snapshots>
</repository>
<!--repository>
<id>iks-repository</id>
<name>ETH Zurich IKS Repository</name>
<url>http://www.flowsgi.inf.ethz.ch/repository/maven2</url>
</repository-->
<repository>
<id>uaal</id>
<name>universAAL Repositories</name>
<url>http://depot.universaal.org/maven-repo/releases/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>uaal-snapshots</id>
<name>universAAL Snapshot Repositories</name>
<url>http://depot.universaal.org/maven-repo/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>uaal-thirdparty</id>
<name>universAAL ThirdParty Repositories</name>
<url>http://depot.universaal.org/maven-repo/thirdparty/</url>
</repository>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-Name>${pom.name}</Bundle-Name>
<Bundle-Activator>org.universAAL.tools.makrorecorder.Activator</Bundle-Activator>
<Bundle-Description>${pom.description}</Bundle-Description>
<Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
<Private-Package>org.universAAL.tools.makrorecorder.makrorecorder.*,org.universAAL.tools.makrorecorder.swinggui.*</Private-Package>
<Bundle-ClassPath>.,images,{maven-dependencies}</Bundle-ClassPath>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package org.universAAL.tools.makrorecorder;
import javax.swing.UIManager;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.universAAL.middleware.container.ModuleContext;
import org.universAAL.middleware.container.osgi.uAALBundleContainer;
import org.universAAL.middleware.sodapop.msg.MessageContentSerializer;
import org.universAAL.tools.makrorecorder.makrorecorder.ResourceOrginazer;
import org.universAAL.tools.makrorecorder.makrorecorder.myContextSubscriber;
import org.universAAL.tools.makrorecorder.makrorecorder.myLogger;
import org.universAAL.tools.makrorecorder.makrorecorder.myServiceProvider;
import org.universAAL.tools.makrorecorder.swinggui.MainFrame;
public class Activator implements BundleActivator {
public static myLogger logger;
public static MainFrame gui;
public static myServiceProvider myServiceProvider;
public static MessageContentSerializer contentSerializer;
public static myContextSubscriber myContextSubscriber;
public static ResourceOrginazer resourceOrginazer;
public static Object[] contentSerializerParams = new Object[] { MessageContentSerializer.class.getName() };
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(final BundleContext context) throws Exception {
UIManager.put("ClassLoader", this.getClass().getClassLoader());
ServiceReference sr = context.getServiceReference(MessageContentSerializer.class.getName());
final ModuleContext moduleContext = uAALBundleContainer.THE_CONTAINER.registerModule(new Object[] { context });
if (contentSerializer == null) {
contentSerializer = (MessageContentSerializer) moduleContext
.getContainer().fetchSharedObject(moduleContext,
contentSerializerParams);
if (contentSerializer == null)
contentSerializer = (MessageContentSerializer) context.getService(sr);
}
new Thread() {
public void run() {
logger = new myLogger(context);
myServiceProvider = new myServiceProvider(moduleContext);
myContextSubscriber = new myContextSubscriber(moduleContext);
resourceOrginazer = new ResourceOrginazer();
gui = new MainFrame();
}
}.start();
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
}
}
package org.universAAL.tools.makrorecorder.makrorecorder;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;
import org.universAAL.middleware.context.ContextEvent;
import org.universAAL.middleware.owl.ManagedIndividual;
import org.universAAL.middleware.rdf.Resource;
import org.universAAL.middleware.service.ServiceRequest;
import org.universAAL.middleware.util.ResourceComparator;
import org.universAAL.tools.makrorecorder.Activator;
public class Pattern {
private BufferedReader reader;
private BufferedWriter writer;
private File Contextfile;
private File Requestfile;
private File Configfile;
private int position; // list position
private Vector<Resource> resources;
private Long duration;
private Date date;
private String Name;
private Boolean active;
public synchronized Boolean getActive() {
return active;
}
public synchronized void setActive(Boolean active) {
this.active = active;
}
public synchronized Boolean toggleActive() {
this.active = !this.active;
return active;
}
public static final boolean HIGHER = true;
public static final boolean LOWER = false;
/**
* creates a new Pattern from scratch
**/
private Pattern(String filename, String Name, Date date, long duration) {
this.Name = Name;
this.date = date;
this.duration = new Long(duration);
Contextfile = new File(filename + ".context");
Requestfile = new File(filename + ".request");
Configfile = new File(filename + ".config");
resources = new Vector<Resource>();
position = 0;
active = true;
}
/**
* reads a Pattern from file
**/
private Pattern(String filename) {
Contextfile = new File(filename + ".context");
Requestfile = new File(filename + ".request");
Configfile = new File(filename + ".config");
resources = new Vector<Resource>();
position = 0;
active = true;
}
/**
* creates a new Pattern and fills it with the ServiceRequest and the ContextEvents
**/
public static Pattern createPattern(String filename, ArrayList<Object[]> requests, Vector<ContextEvent> events,
String Name, Long duration) {
Date date = new Date();
Pattern pattern = new Pattern(filename, Name, date, duration);
if (pattern.writePattern(events, requests)) {
pattern.resources.addAll(events);
pattern.subscribe();
return pattern;
} else
return null;
}
/**
* loads a Pattern from file
**/
public static Pattern loadPattern(String string) {
Pattern pattern = new Pattern(string);
if (pattern.loadContextEvents()) {
pattern.loadConfig();
pattern.subscribe();
return pattern;
}
return null;
}
/**
* adds the ContextEvent from this pattern to the subscribtion of the ContextSubscriber
**/
private void subscribe() {
if (resources.size() == 0) {
return;
}
for (Iterator iterator = resources.iterator(); iterator.hasNext();) {
ContextEvent event = (ContextEvent) iterator.next();
Activator.myContextSubscriber.addSubscription(event);
}
}
/**
* saves ContextEvents to the a file
**/
private void writeFile(Vector<? extends Resource> resources, File file) throws IOException {
writer = new BufferedWriter(new FileWriter(file));
if (resources.size() == 0) {
writer.write(" ");
writer.close();
return;
}
for (Iterator iterator = resources.iterator(); iterator.hasNext();) {
Resource resource = (Resource) iterator.next();
writer.write("NewResource:");
writer.write(Activator.contentSerializer.serialize(resource));
}
writer.close();
}
/**
* saves the Service Requests to a file
**/
private void writeFile(ArrayList<Object[]> resources, File file) throws IOException {
writer = new BufferedWriter(new FileWriter(file));
if (resources.size() == 0) {
writer.write(" ");
writer.close();
return;
}
for (Iterator iterator = resources.iterator(); iterator.hasNext();) {
Object[] entry = (Object[]) iterator.next();
writer.write("NewResource:" + (Long) entry[0]);
String srString = Activator.contentSerializer.serialize((ServiceRequest) entry[1]);
writer.write(srString);
}
writer.close();
}
/**
* save the Pattern to on the Harddisk in the Folder "Pattern"
**/
private boolean writePattern(Vector<ContextEvent> events, ArrayList<Object[]> requests) {
try {
writeFile(events, Contextfile);
writeFile(requests, Requestfile);
writeConfig();
return true;
} catch (FileNotFoundException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
} catch (IOException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
}
return false;
}
/**
* reads all ContextEvents from file
**/
private boolean loadContextEvents() {
try {
resources = loadResource(Contextfile);
return true;
} catch (FileNotFoundException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
} catch (IOException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
}
return false;
}
/**
* reads the configfile The ConfigFile consits of: Name of the Pattern date on which the pattern was recorded
* duration of the recording
**/
private void loadConfig() {
try {
reader = new BufferedReader(new FileReader(Configfile));
Name = reader.readLine();
date = new Date(new Long(reader.readLine()));
duration = new Long(reader.readLine());
} catch (FileNotFoundException e) {
Activator.logger.error("Error: while reading Configfile: " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Activator.logger.error("Error: while reading Configfile: " + e.toString());
e.printStackTrace();
}
}
/**
* writes Configfile The ConfigFile consits of: Name of the Pattern date on which the pattern was recorded duration
* of the recording
**/
private void writeConfig() {
try {
writer = new BufferedWriter(new FileWriter(Configfile));
writer.write(Name + "\n");
writer.write(new Long(date.getTime()).toString() + "\n");
writer.write(duration.toString() + "\n");
writer.close();
} catch (IOException e) {
Activator.logger.error("Error: while writing Configfile: " + e.toString());
e.printStackTrace();
}
}
/**
* Reads the ContextEvents from file
**/
private Vector<Resource> loadResource(File file) throws FileNotFoundException, IOException {
Vector<Resource> requests = new Vector<Resource>();
reader = new BufferedReader(new FileReader(file));
String line;
String text = new String("");
while (null != (line = reader.readLine())) {
if (line.contains("NewResource:")) {
if (!text.equalsIgnoreCase("")) {
requests.add((Resource) Activator.contentSerializer.deserialize(text));
}
text = new String("");
} else
text += line;
}
text = text.trim();
if (!text.equalsIgnoreCase("") && (Resource) Activator.contentSerializer.deserialize(text) != null)
requests.add((Resource) Activator.contentSerializer.deserialize(text)); // for the last Resource or if the
// file only contains one Resource
return requests;
}
/**
* Reads the ServiceRequests from file
**/
private ArrayList<Object[]> loadRequests(File file) throws FileNotFoundException, IOException {
ArrayList<Object[]> requests = new ArrayList<Object[]>();
reader = new BufferedReader(new FileReader(file));
String line;
StringBuilder text = new StringBuilder();
Long time = null;
while (null != (line = reader.readLine())) {
if (line.contains("NewResource:")) {
if (text.length() > 0) {
ServiceRequest request = (ServiceRequest) Activator.contentSerializer.deserialize(text.toString());
Object[] entry = { time, request };
requests.add(entry);
}
time = new Long(line.split("\\:")[1]);
text = new StringBuilder();
} else
text.append(line);
}
String last = text.toString().trim();
if (!last.isEmpty()) {
ServiceRequest request = (ServiceRequest) Activator.contentSerializer.deserialize(last);
if (request != null) {
Object[] entry = { time, request };
requests.add(entry);// for the last Resource or if the file only contains one Resource
}
}
return requests;
}
/**
* loads Service Requests
**/
public ArrayList<Object[]> getRequests() {
try {
ArrayList<Object[]> requests = loadRequests(Requestfile);
return requests;
} catch (FileNotFoundException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
} catch (IOException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
} catch (ClassCastException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
}
return null;
}
/**
* extracts only the important parts of a context event into a Resource else we can't compare it with a other
* ContextEvent important parts are: Subject predicate Object
**/
static public Resource convertResource(ContextEvent ce, String newUri) {
if (ce == null)
return null;
// first prepare the subject
Resource subj_orig = (Resource) ce.getProperty(ContextEvent.PROP_RDF_SUBJECT);
Resource subj_copy = ManagedIndividual.getInstance(subj_orig.getType(), subj_orig.getURI());
if (subj_copy == null) {
subj_copy = Resource.getResource(subj_orig.getType(), subj_orig.getURI());
if (subj_copy == null) {
subj_copy = new Resource(subj_orig.getURI());
subj_copy.addType(subj_orig.getType(), true);
}
}
subj_copy.setProperty(ce.getRDFPredicate(), ce.getRDFObject());
// now prepare the converted resource
Resource result = new Resource(newUri);
result.setProperty(ContextEvent.PROP_RDF_SUBJECT, subj_copy);
result.setProperty(ContextEvent.PROP_RDF_PREDICATE, ce.getProperty(ContextEvent.PROP_RDF_PREDICATE));
result.setProperty(ContextEvent.PROP_RDF_OBJECT, ce.getProperty(ContextEvent.PROP_RDF_OBJECT));
// result.setProperty(ContextEvent.PROP_CONTEXT_PROVIDER, ce.getProperty(ContextEvent.PROP_CONTEXT_PROVIDER));
// do the same for any other props that you think you might need in your
// record
// props currently not copied: ContextEvent.PROP_CONTEXT_CONFIDENCE,
// ContextEvent.PROP_CONTEXT_EXPIRATION_TIME,
// ContextEvent.PROP_CONTEXT_TIMESTAMP, ContextEvent.PROP_RDFS_COMMENT,
// ContextEvent.PROP_RDFS_LABEL
// remember that from props currently not copied, only the timestamp is
// always not-null
// return the result
return result;
}
/**
* converts a set of Context into a set of compareable Resources
**/
static public Vector<Resource> convertResources(Vector<ContextEvent> events) {
Vector<Resource> resources = new Vector<Resource>();
for (Iterator iterator = events.iterator(); iterator.hasNext();) {
ContextEvent event = (ContextEvent) iterator.next();
resources.add(convertResource(event, "test"));
}
return resources;
}
/**
* compares a ContextEvent with the ContextEvents of actual list position if they are not equel we will reset the
* list position and return false.
**/
public boolean check(ContextEvent event) {
if(resources.isEmpty())
return false;
Resource r1 = convertResource(event, "test");
ContextEvent savedEvent = (ContextEvent) resources.elementAt(position);
Resource r2 = convertResource(savedEvent, "test");
if (new ResourceComparator().areEqual(r1, r2)) {
position++;
if (position >= resources.size()) {
position = 0;
return true;
}
} else {
position = 0;
new ResourceComparator().printDiffs(r1, r2);
}
return false;
}
public void deleteContextEvent(int index) {
resources.remove(index);
try {
writeFile(resources, Contextfile);
} catch (IOException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
e.printStackTrace();
}
}
public void deleteServiceRequest(int index) {
ArrayList<Object[]> requests = getRequests();
requests.remove(index);
try {
writeFile(requests, Requestfile);
} catch (IOException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
e.printStackTrace();
}
}
public void changePositionOfContextEvent(int index, boolean direction) {
if (direction) {
if (index == 0)
return;
Resource temp = resources.get(index);
resources.add(index - 1, temp);
resources.remove(index + 1);
} else {
if (index + 1 == resources.size())
return;
Resource temp = resources.get(index);
resources.add(index + 2, temp);
resources.remove(index);
}
try {
writeFile(resources, Contextfile);
} catch (IOException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
e.printStackTrace();
}
}
public void changePositionOfServiceRequest(int index, boolean direction) {
ArrayList<Object[]> requests = getRequests();
if (direction) {
if (index == 0)
return;
Object[] temp = requests.get(index);
requests.add(index - 1, temp);
requests.remove(index + 1);
} else {
if (index + 1 == requests.size())
return;
Object[] temp = requests.get(index);
requests.add(index + 2, temp);
requests.remove(index);
}
try {
writeFile(requests, Requestfile);
} catch (IOException e) {
Activator.logger.error(e.toString() + "\n" + e.getStackTrace());
e.printStackTrace();
}
}
public String getName() {
return this.Name;
}
public String getDate() {
return this.date.toString();
}
public Vector<Resource> getEvents() {
return resources;
}
public Long getDuration() {
return duration;
}
public void deleteFiles() {
Configfile.delete();
Contextfile.delete();
Requestfile.delete();
}
public ContextEvent getEvent(int index) {
return (ContextEvent) resources.get(index);
}
public ServiceRequest getRequest(int index) {
Object[] entry = getRequests().get(index);
return (ServiceRequest) entry[1];
}
}
package org.universAAL.tools.makrorecorder.makrorecorder;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import org.universAAL.middleware.context.ContextEvent;
import org.universAAL.tools.makrorecorder.Activator;
public class ResourceOrginazer {
Vector<Pattern> patterns;
String basedir;
/**
* starts Orginazer and loads all existing patterns
**/
public ResourceOrginazer() {
patterns = new Vector<Pattern>();
basedir = "Pattern";
File file = new File(basedir);
if (file.exists()) {
String[] children = file.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.contains(".context")) {
return true;
}
return false;
}
});
for (int i = 0; i < children.length; i++) {
String string = children[i];
string = string.replace(".context", "");
patterns.add(Pattern.loadPattern(basedir + "/" + string));
}
} else {
file.mkdir();
}
}
public void addPattern(Vector<ContextEvent> events, ArrayList<Object[]> requests, String Name, long duration) {
String filename = basedir + "/" + (Name);
patterns.add(Pattern.createPattern(filename, requests, events, Name, duration));
}
/**
* invokes the "check" Method for each pattern if true is returned, we will add the ServiceRequest to our list of
* ServiceRequests to be invoked.
**/
public void check(ContextEvent event) {
ArrayList<Object[]> requests = new ArrayList<Object[]>();
for (Iterator iterator = patterns.iterator(); iterator.hasNext();) {
Pattern pattern = (Pattern) iterator.next();
if (pattern.getActive() && pattern.check(event)) {// pattern will only be check if active
requests.addAll(pattern.getRequests());
}
}
if (!requests.isEmpty()) {// only call the Requests if the list is not empty
Activator.myServiceProvider.startCallingServices(requests, Activator.gui.keepTimeDependencies(), null);
}
}
public Vector<Pattern> getPatterns() {
return patterns;
}
public Vector<String> getPatternNames() {
Vector<String> Names = new Vector<String>();
for (Iterator iterator = patterns.iterator(); iterator.hasNext();) {
Pattern pattern = (Pattern) iterator.next();
Names.add(pattern.getName());
}
return Names;
}
public Vector<Boolean> getState() {
Vector<Boolean> booleans = new Vector<Boolean>();
for (Iterator iterator = patterns.iterator(); iterator.hasNext();) {
Pattern pattern = (Pattern) iterator.next();
booleans.add(pattern.getActive());
}
return booleans;
}
public Vector<String> getPatternDates() {
Vector<String> Dates = new Vector<String>();
for (Iterator iterator = patterns.iterator(); iterator.hasNext();) {
Pattern pattern = (Pattern) iterator.next();
Dates.add(pattern.getDate());
}
return Dates;
}
public Pattern getPatternByName(String Name) {
for (Iterator iterator = patterns.iterator(); iterator.hasNext();) {
Pattern pattern = (Pattern) iterator.next();
if (pattern.getName().equalsIgnoreCase(Name)) {
return pattern;
}
}
return null;
}
public void deletePattern(Pattern pattern) {
for (Iterator iterator = patterns.iterator(); iterator.hasNext();) {
if (iterator.next().equals(pattern)) {
pattern.deleteFiles();
iterator.remove();
}
}
}
}
package org.universAAL.tools.makrorecorder.makrorecorder;
public interface ServiceCallHandler {
/**
* @param progress between 0 and 1
* @param time time in ms elapsed since playback was started
*/
public void progressChanged(float progress, long time);
public void callingFinished(boolean result);
public void callingCanceled();
}
package org.universAAL.tools.makrorecorder.makrorecorder;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import org.universAAL.middleware.container.ModuleContext;
import org.universAAL.middleware.context.ContextEvent;
import org.universAAL.middleware.context.ContextEventPattern;
import org.universAAL.middleware.context.ContextSubscriber;
import org.universAAL.middleware.owl.MergedRestriction;
import org.universAAL.middleware.rdf.Resource;
import org.universAAL.tools.makrorecorder.Activator;
public class myContextSubscriber extends ContextSubscriber {
static Long startTime;
static Long stopTime;
public static Long getStartTime() {
return startTime;
}
static boolean recording;
static Vector<String> subscribedUris;
public myContextSubscriber(ModuleContext context) {
super(context, null);
subscribedUris = new Vector<String>();
}
@Override
public void communicationChannelBroken() {
}
@Override
public void handleContextEvent(ContextEvent arg0) {
if (!recording) {
Activator.resourceOrginazer.check(arg0);
}
}
/**
* creates the subscribtion pattern for the ContextSubscriber from a Resource which should be a ContextEvent
**/
private ContextEventPattern createSubscription(Resource event) {
ContextEventPattern contextEventPattern = new ContextEventPattern();
Resource subject = (Resource) event.getProperty(ContextEvent.PROP_RDF_SUBJECT);
String subjectUri = subject.getURI();
// contextEventPattern.addRestriction(MergedRestriction.getAllValuesRestriction(ContextEvent.PROP_RDF_SUBJECT,
// subjectUri));//29.03.2012@maxim
contextEventPattern.addRestriction(MergedRestriction.getFixedValueRestriction(ContextEvent.PROP_RDF_SUBJECT,
subject));
return contextEventPattern;
}
/**
* creates the subscribtion pattern for the ContextSubscriber form a SubjectUri of a ContextEvent
**/
private ContextEventPattern createSubscription(String uri) {
ContextEventPattern contextEventPattern = new ContextEventPattern();
contextEventPattern.addRestriction(MergedRestriction
.getAllValuesRestriction(ContextEvent.PROP_RDF_SUBJECT, uri));
return contextEventPattern;
}
/**
* adds a new contextEventPattern to the Contextsubscriber from a ContextEvent.
**/
public void addSubscription(Resource resource) {
String subjectUri = ((Resource) resource.getProperty(ContextEvent.PROP_RDF_SUBJECT)).getURI();
if (!subscribedUris.contains(subjectUri)) {
subscribedUris.add(subjectUri);
addNewRegParams(new ContextEventPattern[] { createSubscription(resource) });
}
}
/**
* removes a contextEventPattern to the Contextsubscriber from a ContextEvent.
**/
public void removeSubscription(Resource resource) {
String subjectUri = ((Resource) resource.getProperty(ContextEvent.PROP_RDF_SUBJECT)).getURI();
if (subscribedUris.contains(subjectUri)) {
subscribedUris.remove(subjectUri);
removeMatchingRegParams(new ContextEventPattern[] { createSubscription(resource) });
}
}
/**
* switch the Programm into Recording state.
**/
public void startRecording() {
recording = true;
startTime = new Date().getTime();
}
/**
* Leaves Recordingstate and invokes the reading of the Service Requests and ContextEvents
**/
public void stopRecording(String Name) {
recording = false;
stopTime = new Date().getTime();
long duration = stopTime - startTime;
try {
Vector<ContextEvent> events = (Activator.myServiceProvider.callChe(startTime, stopTime));
ArrayList<Object[]> requests = (Activator.myServiceProvider.readServiceRequests(startTime, stopTime));
if (events == null) {
events = new Vector<ContextEvent>();
Activator.logger.error("Che returned null, is the Che started?");
} /*
* else { int i=1; while (i<events.size()) { if
* (events.get(i).getProperty(ContextEvent.PROP_CONTEXT_TIMESTAMP
* ).equals(events.get(i-1).getProperty(ContextEvent.PROP_CONTEXT_TIMESTAMP))) events.remove(i); else i++; }
* }
*/
if (requests.isEmpty())
Activator.logger.error("no ServiceCalls where read, is the Middleware modified?");
for (ContextEvent event : events)
System.err.println(event.toString());
// create new pattern.
Activator.resourceOrginazer.addPattern(events, requests, Name, duration);
} catch (FileNotFoundException e) {
Activator.logger.error("Error: Request-Log not found: " + e.toString());
} catch (IOException e) {
Activator.logger.error("Error: while reading Request-Log: " + e.toString());
} catch (Exception e) {
Activator.logger.error("Error: " + e.toString());
}
}
}
package org.universAAL.tools.makrorecorder.makrorecorder;
import org.osgi.framework.BundleContext;
import org.osgi.service.log.LogService;
import org.slf4j.LoggerFactory;
public class myLogger {
// static LogUtils log;
static LogService log;
public static org.slf4j.Logger logger = LoggerFactory.getLogger(myLogger.class);
public myLogger(BundleContext context) {
log = (LogService) context.getService(
context.getServiceReference(LogService.class.getName()));
}
public void info(String info){
log.log(LogService.LOG_INFO, info);
// log.logInfo(logger, this.getClass().toString(), "info", new Object[]{info}, null);
}
public void debug(String debug) {
log.log(LogService.LOG_DEBUG, debug);
// log.logDebug(logger, this.getClass().toString(), "debug",new Object[]{debug}, null);
}
public void error(String error) {
log.log(LogService.LOG_ERROR, error);
// log.logError(logger, this.getClass().toString(), "error",new Object[]{error}, null);
}
}
package org.universAAL.tools.makrorecorder.makrorecorder;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.universAAL.context.che.ontology.ContextHistoryService;
import org.universAAL.middleware.container.ModuleContext;
import org.universAAL.middleware.context.ContextEvent;
import org.universAAL.middleware.owl.MergedRestriction;
import org.universAAL.middleware.rdf.PropertyPath;
import org.universAAL.middleware.rdf.Resource;
import org.universAAL.middleware.service.CallStatus;
import org.universAAL.middleware.service.DefaultServiceCaller;
import org.universAAL.middleware.service.ServiceCaller;
import org.universAAL.middleware.service.ServiceRequest;
import org.universAAL.middleware.service.ServiceResponse;
import org.universAAL.middleware.service.owl.Service;
import org.universAAL.middleware.service.owls.process.ProcessOutput;
import org.universAAL.middleware.sodapop.msg.MessageContentSerializer;
import org.universAAL.tools.makrorecorder.Activator;
public class myServiceProvider {
public static String NAMESPACE_MY_SERVICE_PROVIDER = "http://ontology.igd.fhg.de/myServiceProvider.owl#";
String OUTPUT_LIST_OF_EVENTS = NAMESPACE_MY_SERVICE_PROVIDER + "listOfEvents";
MessageContentSerializer contentSerializer;
ServiceCaller serviceCaller;
private Thread serviceCallingThread = null;
public myServiceProvider(ModuleContext context) {
serviceCaller = new DefaultServiceCaller(context);
}
private ServiceResponse callService(ServiceRequest request) {
ServiceResponse response = serviceCaller.call(request);
return response;
}
/**
* sends a list of ServiceRequest.
**/
public void startCallingServices(final ArrayList<Object[]> requests, final boolean keepTimeDeps,
final ServiceCallHandler onFinish) {
stopCallingServices();
if (requests.isEmpty())
return;
serviceCallingThread = new Thread() {
@Override
public void run() {
boolean result = false;
long starttime = System.currentTimeMillis();
long endtime = (Long) ((Object[]) requests.get(requests.size() - 1))[0];
long timenow = System.currentTimeMillis();
for (Iterator<Object[]> iterator = requests.iterator(); iterator.hasNext();) {
Object[] entry = iterator.next();
if (entry[1] instanceof ServiceRequest) {
ServiceRequest request = (ServiceRequest) entry[1];
if (keepTimeDeps) { // if true we will wait between each request
long time = (Long) entry[0];
try {
if (starttime + time - timenow > 0)
Thread.sleep(starttime + time - timenow);
} catch (InterruptedException e) {
break;
}
timenow = System.currentTimeMillis();
if (onFinish != null)
onFinish.progressChanged((float) (timenow - starttime) / endtime, timenow - starttime);
}
if (callService(request).getCallStatus() == CallStatus.succeeded)
result = true;
}
}
if (onFinish != null) {
if (interrupted())
onFinish.callingCanceled();
else
onFinish.callingFinished(result);
}
}
};
serviceCallingThread.start();
}
public void startCallingServices(String name, boolean keepTimeDeps, ServiceCallHandler onFinish) {
Pattern pattern = Activator.resourceOrginazer.getPatternByName(name);
startCallingServices(pattern.getRequests(), keepTimeDeps, onFinish);
}
public void stopCallingServices() {
if (serviceCallingThread != null) {
serviceCallingThread.interrupt();
try {
serviceCallingThread.join();
} catch (InterruptedException e) {
e.printStackTrace(); // should not happen
}
}
}
/**
* creates the Service Request which will be answered with a list of ContextEvents which occured from a "startTime"
* to the Time of this Request
**/
private ServiceRequest buildCheRequest(Long startTime) {
org.universAAL.context.che.ontology.ContextEvent matchEvent = new org.universAAL.context.che.ontology.ContextEvent(
"urn:org.universAAL.middleware.context.rdf:ContextEvent#_:0000000000000000:00");
ServiceRequest request = new ServiceRequest(new ContextHistoryService(null), null);
Service service = request.getRequestedService();
MergedRestriction restriction = MergedRestriction.getFixedValueRestriction(ContextHistoryService.PROP_MANAGES,
matchEvent);
service.addInstanceLevelRestriction(restriction, new String[] { ContextHistoryService.PROP_MANAGES });
MergedRestriction restriction2 = MergedRestriction.getFixedValueRestriction(
ContextHistoryService.PROP_TIMESTAMP_FROM, new Long(startTime));
service.addInstanceLevelRestriction(restriction2, new String[] { ContextHistoryService.PROP_TIMESTAMP_FROM });
request.addSimpleOutputBinding(new ProcessOutput(OUTPUT_LIST_OF_EVENTS), new PropertyPath(null, false,
new String[] { ContextHistoryService.PROP_MANAGES }).getThePath());
return request;
}
/**
* handels the Return Value of the Che Service Request
**/
private Object getReturnValue(List outputs, String expectedOutput) {
Object returnValue = null;
if (outputs == null)
Activator.logger.info("History Client: No events found!");
else
for (Iterator i = outputs.iterator(); i.hasNext();) {
ProcessOutput output = (ProcessOutput) i.next();
if (output.getURI().equals(expectedOutput))
if (returnValue == null)
returnValue = output.getParameterValue();
else
Activator.logger.info("History Client: redundant return value!");
else
Activator.logger.info("History Client - output ignored: " + output.getURI());
}
return returnValue;
}
/**
* calls the Che and returns a list of ContextEvents which occured between "startTime" and "stopTime"
**/
public Vector<ContextEvent> callChe(Long startTime, Long stopTime) {
ServiceResponse response = callService(buildCheRequest(startTime));
Vector<ContextEvent> resources = new Vector<ContextEvent>();
if (response.getCallStatus() == CallStatus.succeeded) {
Object vaObject = getReturnValue(response.getOutputs(), OUTPUT_LIST_OF_EVENTS);
if (vaObject == null) {
Activator.logger.info("Che Call was null");
return resources; // we return a emtpy List
} else if (vaObject instanceof Resource) {
Activator.logger.info("Che Call was empty");
return resources; // we return a emtpy List
} else if (vaObject instanceof List) {
resources.addAll((List<ContextEvent>) vaObject);
for (Iterator<ContextEvent> iterator = resources.iterator(); iterator.hasNext();) {
ContextEvent contextEvent = iterator.next();
System.out.println("----------------------------");
System.out.println(contextEvent);
for (Enumeration<String> e = contextEvent.getPropertyURIs(); e.hasMoreElements();) {
String uri = e.nextElement();
System.out.println(uri + " : " + contextEvent.getProperty(uri));
}
// since the From - To Request doesn't work we have to delete the ContextEvent which are out of our
// scope by "hand"
if (contextEvent.getTimestamp() > stopTime) {
Activator.logger.info("Removing: " + contextEvent.toString());
iterator.remove();
}
}
Activator.logger.info("Che delivered:" + resources.size());
return resources;
} else {
Activator.logger.info("Che Call was neither null nor a list or resource");
return resources; // we return a emtpy List
}
}
return null;
}
/**
* Reads the ServiceRequest from the file "text.txt" which is created after we modified the Middleware.service
* implemantion for futher information regard the doc or the readme.
*
* Each entry of the List consists of an array with two entrys, the first is the time intervall between the last
* entry (or "startTime" if this is the first entry) and this one, the second entry is the Service Request
**/
public ArrayList<Object[]> readServiceRequests(Long startTime, Long stopTime) throws FileNotFoundException,
IOException {
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line;
String text = new String("");
boolean gettext = false;
long time = 0;
// long lasttime = startTime;
ArrayList<Object[]> objects = new ArrayList<Object[]>();
while (null != (line = reader.readLine())) {
if (line.contains("New Message:")) {
if (gettext && text != "" && text.contains("ServiceRequest")) {
Resource request = (Resource) Activator.contentSerializer.deserialize(text);
if (request instanceof ServiceRequest) {
// time will always be set before we get into this part
Object[] entry = { new Long(time - startTime), (ServiceRequest) request };
objects.add(entry);
}
// lasttime = time;
gettext = false;
}
time = Long.parseLong(line.split("\\:")[1]);
if (time > startTime && time < stopTime) {
gettext = true;
text = "";
}
} else if (gettext) {
text += line + "\n";
}
}
return objects;
}
}
package org.universAAL.tools.makrorecorder.swinggui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.universAAL.tools.makrorecorder.Activator;
import org.universAAL.tools.makrorecorder.makrorecorder.Pattern;
import org.universAAL.tools.makrorecorder.makrorecorder.ServiceCallHandler;
public class MainFrame extends JFrame implements ListSelectionListener, MouseListener, ServiceCallHandler {
// Menubar is not working with Sensekit o:O
/*
* JMenuBar menuBar; JMenu menu; JMenuItem playMenuItem; JMenuItem recordMenuItem; JMenuItem editMenuItem; JMenuItem
* deleteMenuItem; JCheckBoxMenuItem keepTimeItem;
*/
private static final long serialVersionUID = -1020520993429013831L;
JButton recordButton;
JButton playButton;
JButton deleteButton;
JCheckBox keepTimeBox;
JTable table;
DefaultTableModel model;
ImageIcon logo;
ImageIcon recordIconBig;
ImageIcon playIconBig;
ImageIcon recordIconSmall;
ImageIcon playIconSmall;
ImageIcon deleteIconSmall;
ImageIcon deleteIconBig;
boolean recording = false;
private AbstractAction startAction;
private AbstractAction playAction;
private AbstractAction editAction;
private AbstractAction deleteAction;
private JFrame playProgressFrame;
private JProgressBar playProgressBar;
public MainFrame() {
this.setBounds(0, 0, 300, 450);
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setResizable(false);
this.setLayout(new BorderLayout(10, 10));
// reads all the images.
// big images are for the main Frame
logo = new ImageIcon(MainFrame.class.getClassLoader().getResource("images/uaal.gif"));
recordIconBig = new ImageIcon(MainFrame.class.getClassLoader().getResource("images/RecordButton.png"));
playIconBig = new ImageIcon(MainFrame.class.getClassLoader().getResource("images/StartButton.png"));
deleteIconBig = new ImageIcon(MainFrame.class.getClassLoader().getResource("images/Delete.png"));
// small images are for the Menubar
recordIconSmall = new ImageIcon(MainFrame.class.getClassLoader().getResource("images/RecordButton.png"));
playIconSmall = new ImageIcon(MainFrame.class.getClassLoader().getResource("images/StartButton.png"));
deleteIconSmall = new ImageIcon(MainFrame.class.getClassLoader().getResource("images/Delete.png"));
Image icon = logo.getImage();
ImageIcon newlogo = new ImageIcon(icon.getScaledInstance(200, 100, Image.SCALE_SMOOTH));
JLabel logoLabel = new JLabel(newlogo);
// logoLabel.setBounds(50, 10, 200, 100);
logoLabel.setPreferredSize(new Dimension(200, 100));
icon = recordIconBig.getImage();
recordIconBig = new ImageIcon(icon.getScaledInstance(70, 70, Image.SCALE_SMOOTH));
icon = playIconBig.getImage();
playIconBig = new ImageIcon(icon.getScaledInstance(70, 70, Image.SCALE_SMOOTH));
icon = recordIconSmall.getImage();
recordIconSmall = new ImageIcon(icon.getScaledInstance(25, 25, Image.SCALE_SMOOTH));
icon = playIconSmall.getImage();
playIconSmall = new ImageIcon(icon.getScaledInstance(25, 25, Image.SCALE_SMOOTH));
icon = deleteIconSmall.getImage();
deleteIconSmall = new ImageIcon(icon.getScaledInstance(25, 25, Image.SCALE_SMOOTH));
icon = deleteIconBig.getImage();
deleteIconBig = new ImageIcon(icon.getScaledInstance(70, 70, Image.SCALE_SMOOTH));
/*
* menuBar = new JMenuBar(); menu = new JMenu("File"); menu.setMnemonic(KeyEvent.VK_F); menuBar.add(menu);
*
* // keepTimeItem = new JCheckBoxMenuItem(); // keepTimeItem.setText("Keep Time dependancie"); //
* keepTimeItem.addItemListener(this); // keepTimeItem.setMnemonic(KeyEvent.VK_K); // menu.add(keepTimeItem);
*
*
* playMenuItem = new JMenuItem(); playMenuItem.setAction(playRecord()); playMenuItem.setText("Play");
* playMenuItem.setMnemonic(KeyEvent.VK_P); playMenuItem.setEnabled(false); playMenuItem.setIcon(playIconSmall);
* menu.add(playMenuItem);
*
* recordMenuItem = new JMenuItem(); recordMenuItem.setAction(startRecording());
* recordMenuItem.setText("Record"); recordMenuItem.setMnemonic(KeyEvent.VK_R); recordMenuItem.setEnabled(true);
* recordMenuItem.setIcon(recordIconSmall); menu.add(recordMenuItem);
*
* editMenuItem = new JMenuItem(); editMenuItem.setAction(editRecord()); editMenuItem.setText("Edit");
* editMenuItem.setMnemonic(KeyEvent.VK_E); editMenuItem.setEnabled(false); menu.add(editMenuItem);
*
* deleteMenuItem = new JMenuItem(); deleteMenuItem.setAction(deleteRecord()); deleteMenuItem.setText("Delete");
* deleteMenuItem.setMnemonic(KeyEvent.VK_D); deleteMenuItem.setEnabled(false);
* deleteMenuItem.setIcon(deleteIconSmall); menu.add(deleteMenuItem);
*/
recordButton = new JButton();
// recordButton.setBounds(20, 130, 75, 75);
recordButton.setPreferredSize(new Dimension(75, 75));
recordButton.setAction(startRecording());
recordButton.setEnabled(true);
recordButton.setIcon(recordIconBig);
playButton = new JButton();
// playButton.setBounds(170, 130, 75, 75);
playButton.setPreferredSize(new Dimension(75, 75));
playButton.setAction(playRecord());
playButton.setEnabled(false);
playButton.setIcon(playIconBig);
deleteButton = new JButton();
deleteButton.setPreferredSize(new Dimension(75, 75));
deleteButton.setAction(deleteRecord());
deleteButton.setEnabled(false);
deleteButton.setIcon(deleteIconBig);
// JButton fakeeditButton = new JButton();
// fakeeditButton.setAction(editRecord());
keepTimeBox = new JCheckBox();
keepTimeBox.setText("Keep the time dependancie of reqeusts");
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
});
table = new JTable(fillTable()) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
table.getColumn("Active").setCellRenderer(table.getDefaultRenderer(Boolean.class));
table.getColumn("Active").setCellEditor(table.getDefaultEditor(Boolean.class));
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(true);
// table.setCellSelectionEnabled(false);
ListSelectionModel selectionModel;
selectionModel = table.getSelectionModel();
selectionModel.addListSelectionListener(this);
table.setSelectionModel(selectionModel);
table.addMouseListener(this);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(270, 200));
JPanel buttonPanel = new JPanel(new BorderLayout(10, 10));
buttonPanel.add(recordButton, BorderLayout.WEST);
buttonPanel.add(playButton, BorderLayout.CENTER);
buttonPanel.add(deleteButton, BorderLayout.EAST);
JPanel northpanel = new JPanel(new BorderLayout());
northpanel.add(logoLabel, BorderLayout.NORTH);
northpanel.add(keepTimeBox, BorderLayout.PAGE_END);
this.getContentPane().add(buttonPanel, BorderLayout.CENTER);
this.getContentPane().add(scrollPane, BorderLayout.SOUTH);
this.getContentPane().add(northpanel, BorderLayout.NORTH);
// this.setJMenuBar(menuBar);
this.setVisible(true);
playProgressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
playProgressBar.setStringPainted(true);
playProgressFrame = new JFrame();
playProgressFrame.add(playProgressBar);
playProgressFrame.setSize(500, 90);
}
/**
* invoked on delete
**/
private AbstractAction deleteRecord() {
if (deleteAction == null) {
deleteAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (table.getSelectedRow() != -1) {
String name = (String) table.getModel().getValueAt(table.getSelectedRow(), 1);
Activator.resourceOrginazer.deletePattern(Activator.resourceOrginazer.getPatternByName(name));
model.removeRow(table.getSelectedRow());
table.repaint();
}
}
};
}
return deleteAction;
}
/**
* invoked on record button press
**/
public AbstractAction startRecording() {
if (startAction == null) {
startAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
String eingabe = JOptionPane.showInputDialog(null, "Geben Sie einen Namen ein", "Name?",
JOptionPane.PLAIN_MESSAGE);
if (eingabe != null) {
Activator.myContextSubscriber.startRecording();
recording = true;
RecordFrame recordFrame = new RecordFrame(eingabe, Activator.gui);
recordFrame.setVisible(true);
recordFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (Activator.gui.recording) {
Activator.gui.recording = false;
Activator.gui.setEnabled();
}
super.windowClosing(e);
}
});
setDisabled();
}
}
};
}
return startAction;
}
public boolean keepTimeDependencies() {
return keepTimeBox.isSelected();
}
/**
* invoked on play button press
**/
public AbstractAction playRecord() {
if (playAction == null) {
playAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (table.getSelectedRow() != -1) {
String name = (String) table.getModel().getValueAt(table.getSelectedRow(), 1);
playAction.setEnabled(false);
progressChanged(0, 0);
Activator.myServiceProvider.startCallingServices(name, keepTimeDependencies(), MainFrame.this);
}
}
};
}
return playAction;
}
/**
* invoked on double click of a Record
**/
public AbstractAction editRecord() {
if (editAction == null) {
editAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
String patternName = (String) model.getValueAt(table.getSelectedRow(), 1);
Pattern pattern = Activator.resourceOrginazer.getPatternByName(patternName);
RecordFrame frame = new RecordFrame(pattern, Activator.gui);
frame.setVisible(true);
table.clearSelection();
}
};
}
return editAction;
}
/**
* is invoked after a new Record is added and on programm start
**/
public TableModel fillTable() {
Vector<String> Names = Activator.resourceOrginazer.getPatternNames();
Vector<String> Dates = Activator.resourceOrginazer.getPatternDates();
Vector<Boolean> booleans = Activator.resourceOrginazer.getState();
String[] colNames = { "Active", "Name", "Date" };
model = new DefaultTableModel(colNames, 0);
for (int i = 0; i < Names.size(); i++) {
Object[] data = { booleans.get(i), Names.get(i), Dates.get(i) };
model.addRow(data);
}
return model;
}
/**
* invoked on change of the pattern-table
**/
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
setEnabled();
Object object = table.getSelectedColumn();
if (table.getSelectedColumn() != -1 && table.getSelectedRow() != -1 && table.getSelectedColumn() == 0) {
String patternName = (String) model.getValueAt(table.getSelectedRow(), 1);
Pattern pattern = Activator.resourceOrginazer.getPatternByName(patternName);
table.setValueAt(pattern.toggleActive(), table.getSelectedRow(), table.getSelectedColumn());
table.clearSelection();
table.repaint();
}
}
}
/**
* adds new pattern to table and repaints it
**/
public void addToTable(Pattern pattern) {
Object[] data = { pattern.getActive(), pattern.getName(), pattern.getDate() };
model.addRow(data);
table.repaint();
}
/**
* triggers editaction on doublelick
**/
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
ActionEvent event = new ActionEvent(e.getSource(), e.getID(), "editAction");
editRecord();
editAction.actionPerformed(event);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void setEnabled() {
playButton.setEnabled(true);
// playMenuItem.setEnabled(true);
recordButton.setEnabled(true);
// recordMenuItem.setEnabled(true);
deleteButton.setEnabled(true);
// deleteMenuItem.setEnabled(true);
// editMenuItem.setEnabled(true);
}
public void setDisabled() {
playButton.setEnabled(false);
// playMenuItem.setEnabled(false);
recordButton.setEnabled(false);
// recordMenuItem.setEnabled(false);
deleteButton.setEnabled(false);
// deleteMenuItem.setEnabled(false);
// editMenuItem.setEnabled(false);
}
public void callingCanceled() {
playAction.setEnabled(true);
playProgressFrame.setVisible(false);
}
public void callingFinished(boolean result) {
playAction.setEnabled(true);
playProgressFrame.setVisible(false);
}
public void progressChanged(float progress, long time) {
if (keepTimeDependencies()) {
playProgressBar.setValue((int) (progress * 100));
playProgressBar.setString(String.valueOf(time) + " ms");
playProgressFrame.setVisible(true);
}
}
}
package org.universAAL.tools.makrorecorder.swinggui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.universAAL.middleware.context.ContextEvent;
import org.universAAL.middleware.rdf.Resource;
import org.universAAL.middleware.service.ServiceRequest;
import org.universAAL.tools.makrorecorder.Activator;
import org.universAAL.tools.makrorecorder.makrorecorder.Pattern;
import org.universAAL.tools.makrorecorder.makrorecorder.myContextSubscriber;
public class RecordFrame extends JFrame implements ActionListener,MouseListener, ListSelectionListener{
private static final long serialVersionUID = 8508553212473882557L;
JButton stopButton;
JButton higherButton;
JButton lowerButton;
JButton deleteButton;
ImageIcon stopIcon;
ImageIcon higherIcon;
ImageIcon lowerIcon;
ImageIcon deleteIcon;
JLabel durationLabel;
JList contextEventList;
JList serviceRequestList;
DefaultListModel serviceRequestModel;
DefaultListModel contextEventModel;
Timer timer;
MainFrame parent;
String Name;
AbstractAction stopAction;
AbstractAction higherAction;
AbstractAction lowerAction;
AbstractAction deleteAction;
/**
this constructor is used when a new recording session is started
**/
public RecordFrame(String Name, MainFrame parent) {
this.parent = parent;
this.Name = Name;
buildGui();
timer = new Timer(1000, this);
timer.setInitialDelay(1000);
timer.start();
durationLabel.setText("recording");
higherButton.setEnabled(false);
deleteButton.setEnabled(false);
lowerButton.setEnabled(false);
}
/**
this constructor is used when a existing record is viewed
**/
public RecordFrame(Pattern pattern, MainFrame parentFrame) {
this.parent = parentFrame;
this.Name = pattern.getName();
buildGui();
long currentTime = pattern.getDuration();
long timeInSec = (currentTime / 1000) % 60;
long timeInMin = (currentTime / 60000);
if (timeInSec < 10)
durationLabel.setText(timeInMin +":0" + timeInSec);
else
durationLabel.setText(timeInMin +":" + timeInSec);
durationLabel.setText("duration: "+durationLabel.getText());
fillModel();
contextEventList.repaint();
serviceRequestList.repaint();
higherButton.setEnabled(false);
deleteButton.setEnabled(false);
lowerButton.setEnabled(false);
stopButton.setEnabled(false);
stopButton.setVisible(false);
}
private void buildGui() {
this.setBounds(300, 100, 900, 400);
this.setMinimumSize(new Dimension(600, 300));
this.setLayout(new BorderLayout(10,10));
this.setTitle("Record of " +Name);
//creates all image
stopIcon = new ImageIcon(RecordFrame.class.getClassLoader().getResource("images/StopButton.png"));
Image icon = stopIcon.getImage();
stopIcon = new ImageIcon(icon.getScaledInstance(50, 50, Image.SCALE_SMOOTH));
higherIcon = new ImageIcon(RecordFrame.class.getClassLoader().getResource("images/Higher.png"));
icon = higherIcon.getImage();
higherIcon = new ImageIcon(icon.getScaledInstance(50, 50, Image.SCALE_SMOOTH));
lowerIcon = new ImageIcon(RecordFrame.class.getClassLoader().getResource("images/lower.png"));
icon = lowerIcon.getImage();
lowerIcon = new ImageIcon(icon.getScaledInstance(50, 50, Image.SCALE_SMOOTH));
deleteIcon = new ImageIcon(RecordFrame.class.getClassLoader().getResource("images/Delete.png"));
icon = deleteIcon.getImage();
deleteIcon = new ImageIcon(icon.getScaledInstance(50, 50, Image.SCALE_SMOOTH));
durationLabel = new JLabel();
//durationLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
durationLabel.setVerticalAlignment(SwingConstants.CENTER);
durationLabel.setHorizontalAlignment(SwingConstants.CENTER);
stopButton = new JButton();
stopButton.setAction(stopRecording());
stopButton.setIcon(stopIcon);
higherButton = new JButton();
higherButton.setAction(setHigher());
higherButton.setIcon(higherIcon);
deleteButton = new JButton();
deleteButton.setAction(deleteResource());
deleteButton.setIcon(deleteIcon);
lowerButton = new JButton();
lowerButton.setAction(setLower());
lowerButton.setIcon(lowerIcon);
contextEventModel = new DefaultListModel();
contextEventList = new JList(contextEventModel);
contextEventList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
contextEventList.setLayoutOrientation(JList.VERTICAL);
contextEventList.addMouseListener(this);
contextEventList.addListSelectionListener(this);
//contextEventList.setPreferredSize(new Dimension(280, 200));
serviceRequestModel = new DefaultListModel();
serviceRequestList = new JList(serviceRequestModel);
serviceRequestList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
serviceRequestList.setLayoutOrientation(JList.VERTICAL);
serviceRequestList.addMouseListener(this);
serviceRequestList.addListSelectionListener(this);
//serviceRequestList.setPreferredSize(new Dimension(280, 200));
JScrollPane scrollPane1 = new JScrollPane(contextEventList);
//scrollPane1.setPreferredSize(new Dimension(400, 200));
//scrollPane1.setMinimumSize(new Dimension(400, 200));
JScrollPane scrollPane2 = new JScrollPane(serviceRequestList);
//scrollPane2.setPreferredSize(new Dimension(400, 200));
//scrollPane2.setMinimumSize(new Dimension(400, 200));
//JPanel left = new JPanel(new GridLayout(1,1));
//JPanel right = new JPanel(new GridLayout(1,1));
JPanel middle = new JPanel(new GridBagLayout());
JPanel south = new JPanel(new GridBagLayout());
JPanel center = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
south.add(durationLabel,c);
c.fill = GridBagConstraints.NONE;
c.weightx = 0;
c.gridx = 1;
c.gridy = 0;
south.add(stopButton,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
middle.add(higherButton,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
middle.add(deleteButton,c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
middle.add(lowerButton,c);
/*c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 3;
middle.add(new JPanel(),c);*/
/*middle.setMinimumSize(new Dimension(100, 150));
middle.setSize(new Dimension(100, 150));
middle.setMaximumSize(new Dimension(100, 150));*/
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.gridx = 0;
c.gridy = 0;
c.ipadx = 10;
c.ipady = 10;
center.add(scrollPane1,c);
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 0;
c.weighty = 1;
c.gridx = 1;
c.gridy = 0;
c.ipadx = 10;
c.ipady = 10;
center.add(middle,c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.gridx = 2;
c.gridy = 0;
c.ipadx = 10;
c.ipady = 10;
center.add(scrollPane2,c);
this.getContentPane().add(center,BorderLayout.CENTER);
this.getContentPane().add(south,BorderLayout.PAGE_END);
}
public AbstractAction stopRecording(){
if (stopAction == null) {
stopAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Activator.myContextSubscriber.stopRecording(Name);
parent.setEnabled();
stopButton.setEnabled(false);
stopButton.setVisible(false);
higherButton.setEnabled(true);
deleteButton.setEnabled(true);
lowerButton.setEnabled(true);
parent.addToTable(fillModel());
timer.stop();
long currentTime = Activator.resourceOrginazer.getPatternByName(Name).getDuration();
long timeInSec = (currentTime / 1000) % 60;
long timeInMin = (currentTime / 60000);
if (timeInSec < 10)
durationLabel.setText(timeInMin +":0" + timeInSec);
else
durationLabel.setText(timeInMin +":" + timeInSec);
durationLabel.setText("duration: "+durationLabel.getText());
}
};
}
return stopAction;
}
public AbstractAction setHigher() {
if (higherAction == null) {
higherAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (contextEventList.getSelectedIndex() != -1) {
Pattern pattern = Activator.resourceOrginazer.getPatternByName(Name);
pattern.changePositionOfContextEvent(contextEventList.getSelectedIndex(),Pattern.HIGHER);
contextEventList.clearSelection();
}else if (serviceRequestList.getSelectedIndex() != -1) {
Pattern pattern = Activator.resourceOrginazer.getPatternByName(Name);
pattern.changePositionOfServiceRequest(serviceRequestList.getSelectedIndex(),Pattern.HIGHER);
serviceRequestList.clearSelection();
}
contextEventModel.clear();
serviceRequestModel.clear();
fillModel();
contextEventList.repaint();
serviceRequestList.repaint();
}
};
}
return higherAction;
}
public AbstractAction setLower() {
if (lowerAction == null) {
lowerAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (contextEventList.getSelectedIndex() != -1) {
Pattern pattern = Activator.resourceOrginazer.getPatternByName(Name);
pattern.changePositionOfContextEvent(contextEventList.getSelectedIndex(), Pattern.LOWER);
contextEventList.clearSelection();
}else if (serviceRequestList.getSelectedIndex() != -1) {
Pattern pattern = Activator.resourceOrginazer.getPatternByName(Name);
pattern.changePositionOfServiceRequest(serviceRequestList.getSelectedIndex(),Pattern.LOWER);
serviceRequestList.clearSelection();
}
contextEventModel.clear();
serviceRequestModel.clear();
fillModel();
contextEventList.repaint();
serviceRequestList.repaint();
}
};
}
return lowerAction;
}
public AbstractAction deleteResource() {
if (deleteAction == null) {
deleteAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (contextEventList.getSelectedIndex() != -1) {
Pattern pattern = Activator.resourceOrginazer.getPatternByName(Name);
pattern.deleteContextEvent(contextEventList.getSelectedIndex());
contextEventList.clearSelection();
}else if (serviceRequestList.getSelectedIndex() != -1) {
Pattern pattern = Activator.resourceOrginazer.getPatternByName(Name);
pattern.deleteServiceRequest(serviceRequestList.getSelectedIndex());
serviceRequestList.clearSelection();
}
contextEventModel.clear();
serviceRequestModel.clear();
fillModel();
contextEventList.repaint();
serviceRequestList.repaint();
}
};
}
return deleteAction;
}
/**
adds one ContexEvent to the ContexEvent-List
**/
public void addContexEvent(ContextEvent event) {
String [] arry = ((Resource)event.getProperty(ContextEvent.PROP_RDF_SUBJECT)).getURI().split("#");
String status = "Subject: ";
status += arry[arry.length -1];
status += " Predicate: ";
arry = ((Resource)event.getProperty(ContextEvent.PROP_RDF_PREDICATE)).getURI().split("#");
status += arry[arry.length -1];
status += " Object: ";
// arry = ((Resource) event.getProperty(ContextEvent.PROP_RDF_OBJECT)).getURI().split("#");
status += event.getProperty(ContextEvent.PROP_RDF_OBJECT);
// status += arry[arry.length -1];
contextEventModel.addElement(status);
}
/**
adds one ServiceRequest to the ServiceRequest-List
**/
public void addServiceRequest(ServiceRequest request) {
if (request.getProperty(ServiceRequest.PROP_REQUESTED_SERVICE) instanceof Resource) {
Resource res = (Resource) request.getProperty(ServiceRequest.PROP_REQUESTED_SERVICE);
if (res.getURI().contains("urn:anonymous")) {
Object ject = res.getProperty(Resource.PROP_RDF_TYPE);
if (ject instanceof ArrayList<?>) {
ArrayList<?> list = (ArrayList<?>) ject;
res = (Resource) list.get(0);
}
}
serviceRequestModel.addElement(res);
}
else {
Object object = request.getProperty(ServiceRequest.PROP_REQUESTED_SERVICE);
if(object==null)
object="unknown ServiceRequest";
serviceRequestModel.addElement(object);
}
}
/**
fills the two Lists after recording is stoped or changed
**/
private Pattern fillModel() {
Pattern pattern = Activator.resourceOrginazer.getPatternByName(Name);
Vector<Resource> events = pattern.getEvents();
if(events.size() != 0){
for (Iterator iterator = events.iterator(); iterator.hasNext();) {
addContexEvent( (ContextEvent)iterator.next() );
}
}
ArrayList<Object[]> requests = pattern.getRequests();
if (requests.size() != 0) {
for (Iterator iterator = requests.iterator(); iterator.hasNext();) {
Object[] entry = (Object[]) iterator.next();
ServiceRequest request = (ServiceRequest)entry[1];
addServiceRequest(request);
}
}
return pattern;
}
public void actionPerformed(ActionEvent e) {
long currentTime = (new Date()).getTime();
currentTime -= myContextSubscriber.getStartTime();
long timeInSec = (currentTime / 1000) % 60;
long timeInMin = (currentTime / 60000);
if (timeInSec < 10) {
durationLabel.setText(timeInMin +":0" + timeInSec);
}
else {
durationLabel.setText(timeInMin +":" + timeInSec);
}
durationLabel.setText("recording: "+durationLabel.getText());
}
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JList source = (JList)e.getSource();
String name = "";
Resource resource;
Pattern pattern = Activator.resourceOrginazer.getPatternByName(Name);
if (source.equals(contextEventList)) {
resource = pattern.getEvent(contextEventList.getSelectedIndex());
name = "ContextEvent: " + resource.getURI();
}else if(source.equals(serviceRequestList)){
resource = pattern.getRequest(serviceRequestList.getSelectedIndex());
name = "ServiceRequest: " + resource.getURI();
}else
return;
JFrame frame = new JFrame(name);
JTextArea area = new JTextArea(Activator.contentSerializer.serialize(resource));
frame.getContentPane().add(area);
frame.pack();
frame.setVisible(true);
source.clearSelection();
}
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
higherButton.setEnabled(true);
deleteButton.setEnabled(true);
lowerButton.setEnabled(true);
}
}
}
makrorecorder/makro.recorder/src/main/resources/images/Delete.png

49.6 KiB

makrorecorder/makro.recorder/src/main/resources/images/Higher.png

64.1 KiB

makrorecorder/makro.recorder/src/main/resources/images/RecordButton.png

53 KiB

makrorecorder/makro.recorder/src/main/resources/images/StartButton.png

28.1 KiB

makrorecorder/makro.recorder/src/main/resources/images/StopButton.png

7.43 KiB

makrorecorder/makro.recorder/src/main/resources/images/lower.png

64.8 KiB

makrorecorder/makro.recorder/src/main/resources/images/uaal.gif

3.58 KiB

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment