I am developing an Apache UIMA v2 application to annotate documents.
I developed properly the process() method because I obtain the correct annotations (tested with debug and UIMA CAS Visual Debugger).
My application consists in a simple instantiation of the JCas object and the process of a document, i.e. a simple string in this case. Here's the code:
public class MainProgram {
public static void main(String[] args) {
try {
XMLInputSource in = new XMLInputSource("desc/dictionaryDescriptor.xml");
ResourceSpecifier specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(specifier);
JCas jcas = ae.newJCas();
jcas.setDocumentText("prova di a#gmail.com, timido, word, excel. ");
ae.process(jcas);
processResults(jcas);
ae.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidXMLException e1) {
e1.printStackTrace();
} catch (ResourceInitializationException e2) {
e2.printStackTrace();
} catch (AnalysisEngineProcessException e3) {
e3.printStackTrace();
}
}
public static void processResults(JCas jcas) {
System.out.println("Done!");
// TODO read annotations from jcas
}
}
If I add a breakpoint inside the processResults() method I can see the content of jcas and the list of annotation:
I want to access to the SubTypes list in the AnnotationIndex object, without taking care of the class type.
Here is an example through a specific type:
AnnotationIndex<Annotation> programIndex = jcas.getAnnotationIndex(Programma.type);
Iterator programIter = programIndex.iterator();
while(programIter.hasNext()) {
Programma p = (Programma) programIter.next();
}
You can use the JCasUtil to extract the annotations of the JCas:
JCasUtil.select(jCas, Annotation.class).stream()....
and with the getType() method of the annotation you can check for the type of the annotation.
Related
I'm using ByteBuddy to make some perfomance measuremnts of certian methods. Therefore, I'm annotating the interessting ones. As the method signature is not stable, I choose the generic way for my interceptor:
public class ChronometryInterception {
#RuntimeType
public Object intercept(#Origin MethodHandle methodHandle, #AllArguments Object[] allArguments, #Origin Method method) throws Exception {
System.out.println("in interceptor");
long startTime = System.currentTimeMillis();
try {
return methodHandle.invoke(allArguments);
} catch (Throwable e) {
System.out.println("ex in interceptor " + e.getMessage());
throw new Exception(e);
} finally {
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("took " + elapsedTime;
}
}
}
and I bind it in my premain() like this
ChronometryInterception chronometryInterception = new ChronometryInterception();
new AgentBuilder.Default()
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.type(declaresMethod(isAnnotatedWith(Timed.class)))
.transform((builder, type, classLoader, module) -> builder
.method(isAnnotatedWith(Timed.class))
.intercept(MethodDelegation.to(chronometryInterception))
).installOn(instrumentation);
In the listener stream, I can see the annotated classes have been transformed and they try to do something, but in end up with a NPE. Using the debugger, I'm not getting anywhere in the ChronometryInterception. Any way out? Thanks!
I have found a working solution. At the end, the method signature of my interceptor was not ok. This one is working, even with an instance of the ChronometryInterception:
public class ChronometryInterception {
#RuntimeType
public Object intercept(#SuperCall Callable<?> zuper) throws Exception {
long startTime = System.currentTimeMillis();
try {
return zuper.call();
} catch (Exception e) {
throw e;
} finally {
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("took " + elapsedTime);
}
}
}
I am new to developing plugins, and was wondering what causes a test plugin to hang when started i.e. Eclipse is unresponsive.
I know that my code is working as I developed a voice recognition plugin to write to the screen what is said and when I open notepad everything I say is printed to notepad.
So I was wondering, am I missing something in the plugin life-cycle that causes the IDE to hang when my plugin is started?
package recognise.handlers;
public class SampleHandler extends AbstractHandler {
public SampleHandler() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
return null;
}
}
Does the start.startVoiceRecognition() need to be threaded?
Thanks in advance and let me know if you would like to see my manifest/activator etc.
Conclusion
Added a job separate to the UI thread
/*
* Start a new job separate to the main thread so the UI will not
* become unresponsive when the plugin has started
*/
public void runVoiceRecognitionJob() {
Job job = new Job("Voice Recognition Job") {
#Override
protected IStatus run(IProgressMonitor monitor) {
TakeInput start = new TakeInput();
try {
start.startVoiceRecognition(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// use this to open a Shell in the UI thread
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
}
As shown start.startVoiceRecognition() is running in the UI thread, and it will block the UI thread until it is finished and the app will be unresponsive during that time. So if it is doing a significant amount of work either use a Thread or use an Eclipse Job (which runs work in a background thread managed by Eclipse).
To unblock your UI you have to use Display thread.
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
MessageDialog.openInformation(shell, "Your Popup ",
"Your job has finished.");
}
});
return null;
}
You can use Display.getDefault().asyncExec() as mentioned above, so your UI will be unblocked, while your non UI code will be executing.
When I try to serialize and deserialize an ArrayList wrapped in Collections.synchronizedList using beans.XMLEncoder and beans.XMLDecoder, I get the following error:
java.lang.reflect.InvocationTargetException
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject*Collections$SynchronizedRandomAccessList);
Continuing ...
Since the program I am working on is a multithreaded music library client/server application, I need the synchronization. If using an ordinary ArrayList, the serialization/deserialization works fine. I really don't want to use Vector, since it contains a lot of legacy operations.
Here are my methods to serialize and deserialize:
/**
* Serializes library into an XML file
* #param xmlFileLocation - location of XML file
*/
public void saveLibrary (String xmlFileLocation) {
FileOutputStream fos;
try {
fos = new FileOutputStream(xmlFileLocation);
XMLEncoder encoder = new XMLEncoder(fos);
encoder.writeObject(lib);
encoder.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Constructor for Library, deserializes XML file
* #param xmlFileLocation - location of XML file
*/
#SuppressWarnings("unchecked")
public Library(String xmlFileLocation) {
FileInputStream fis;
try {
fis = new FileInputStream(xmlFileLocation);
XMLDecoder decoder = new XMLDecoder(fis);
Object o = decoder.readObject();
if (o instanceof List)
setLib((List<MusicDescription>) o);
decoder.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
As I stated, I really don't want to use Vector, since it contains a lot of legacy operations.
I wanted to write a test for a method in Groovy that throws an IOException. The only way for me to simulate this in the test is to force the method to throw this exception
This is what the original code looks like:
public void cleanUpBermudaFiles(RequestMessage requestMessage)
{
final File sourceDirectory = new File(preferenceService.getPreference("bermuda.landingstrip") + File.separator + requestMessage.getWorkflowId().getValue());
if(sourceDirectory!=null && sourceDirectory.exists())
{
deleteDirectory(sourceDirectory);
}
else
{
LOG.error("Directory must exist in order to delete");
}
}
private void deleteDirectory(File directoryToDelete)
{
try {
FileUtils.deleteDirectory(directoryToDelete);
} catch (Exception e) {
LOG.error("Failed to delete Bermuda files directory located at:" + directoryToDelete.getPath() + "with an exception" + e.getMessage());
}
}
MY TEST: (I'm looking for a way to make deleteDirectory throw IOException)
public void testCleanUpBermudaFailure()
{
workflowId = new WorkflowId("123456")
workflowDirectory = new File(srcDirectory, workflowId.value)
workflowDirectory.mkdir()
File.createTempFile('foo','.lst', workflowDirectory)
def exception = {throw new IOException()}
expect(mockRequestMessage.getWorkflowId()).andReturn(workflowId)
expect(mockPreferenceService.getPreference("bermuda.landingstrip")).andReturn(srcDirectory.path)
replay(mockPreferenceService, mockRequestMessage)
fileCleanUpService.preferenceService = mockPreferenceService
fileCleanUpService.metaClass.deleteDirectory = exception
fileCleanUpService.cleanUpBermudaFiles(mockRequestMessage)
verify(mockPreferenceService, mockRequestMessage)
assert srcDirectory.listFiles().length == 0, 'CleanUp failed'
}
If the service class is a Groovy class, you would want to mock FileUtils like:
FileUtils.metaClass.static.deleteDirectory = { File f -> throw new IOException() }
However, as ataylor pointed out, you cannot intercept calls if it's a Java class. You can find a nice blog post about it here.
You are mocking a no-arg call to deleteDirectory, but the real deleteDirectory takes one argument of type File. Try this:
def exception = { File directoryToDelete -> throw new IOException() }
...
fileCleanUpService.metaClass.deleteDirectory = exception
Is it possible to serialize an object into a string or a byte array using either the J2ME or BlackBerry APIs?
Thanks.
The way I handle the object serialization case is by implementing my own infrastructure for handling everything. You don't have reflection in this API, but you do have "Class.forName()" which is better than nothing. So here's what I do...
First, this is the interface that I have every serializable object implement:
public interface Serializable {
void serialize(DataOutput output) throws IOException;
void deserialize(DataInput input) throws IOException;
}
The serialize() method writes the object's fields to the DataOutput instance, while the deserialize() method sets the object's fields from the DataInput instance. (these are both plain top-level interfaces used by the data-oriented I/O streams, which allows me to have more flexibility) Also, any class implementing this interface needs to have a default no-arguments constructor. Of course if you want your serialized class to be robust against change, you may want to choose your underlying data formats accordingly. (for example, I implemented a serializable hashtable as an underlying container to handle these cases)
Now, to actually serialize a class implementing this interface, I have a method that looks something like this:
public static byte[] serializeClass(Serializable input) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(buffer);
try {
output.writeUTF(input.getClass().getName());
input.serialize(output);
} catch (IOException ex) {
// do nothing
}
return buffer.toByteArray();
}
And to deserialize:
public static Serializable deserializeClass(byte[] data) {
DataInputStream input = new DataInputStream(new ByteArrayInputStream(data));
Object deserializedObject;
Serializable result = null;
try {
String classType = input.readUTF();
deserializedObject = Class.forName(classType).newInstance();
if(deserializedObject instanceof Serializable) {
result = (Serializable)deserializedObject;
result.deserialize(input);
}
} catch (IOException ex) {
result = null;
} catch (ClassNotFoundException ex) {
result = null;
} catch (InstantiationException ex) {
result = null;
} catch (IllegalAccessException ex) {
result = null;
}
return result;
}
Java ME, unfortunately, doesn't have any built-in APIs for serialization, so you'll have to invent something yourself.
If your goal is to serialize an object or object graph for persisting to flash memory, you can use the PersistentStore class. Many of the native object types such as Boolean, Byte, Character, Integer, Long, Object, Short, String, Vector, Hashtable are implicitly persistable.
You are stuck with creating your own serialization process for your classes. It wouldn't be too difficult to create your own base class and then use somesort of reflection to automatically serialize your properties.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(baos);
try {
// serialize your object -
outputStream.writeInt(this.name);
// Then push the player name.
outputStream.writeUTF(this.timestamp);
}
catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}
// Extract the byte array
byte[] b = baos.toByteArray();