I have a AbstractJobPerformable, which is an import job. The job itself works great, but sometimes it fails.
I saved the error entries into a List, but I don't know how to extend the Job itself to send me the list troguh email.
Firstly, AbstractJobPerformable is not an import job.Its an abstract class that is extended for writing cronjob logic.
To send an email from the perform() method of cronjob you put all your code in one big try{} block and send an email in finally{} or catch{} block of Exception.
#Override
public PerformResult perform(CSVImportCronJobModel csvImportCronJobModel) {
try {
//your code
return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED);
} catch (Exception e) {
emailService.sendEmail(csvImportCronJobModel.getLogs());
return new PerformResult(CronJobResult.FAILURE, CronJobStatus.FINISHED);
}
}
Related
A bit of background: PropertyFunction is an interface in Jena API that allows doing performing custom operations using SPARQL syntax. Example:
select ?result { ?result f:myPropertyFunction 'someObject' . }
So I made a class Launch that implements this interface and extends a class Client. Within the body of the exec method of my Launch class I establish a connection to a server and, while sending information is no problem, waiting for the server to respond is. Whenever I try to wait() for server response I get the following exception: java.lang.IllegalMonitorStateException.
Here is the body of my exec method for reference:
QueryIterator it = null;
try {
this.connect(); // works well
this.send(algorithmAndArgs); // works well
this.wait(); // exception is thrown
#SuppressWarnings("unused")
ResultSet rs = ResultSetFactory.create(it, Arrays.asList(resultIdentifiers));
} catch (Exception e) {
e.printStackTrace();
}
return it;
Anyone know what the problem may be? Thank you for your answer.
EDIT 1: One thing that I forgot to mention is that the Client class has a method called onObjectReceived(Object o, Socket s) that is triggered each time something is received from the server. I tried using a isDone variable with a while loop in the exec method and set it to true once an object is received, but it did not work.
I solved my own problem: I created an attribute private final CountDownLatch objectWasReceivedLatch = new CountDownLatch(1) and, in the exec method I do boolean objectWasReceived = objectWasReceivedLatch.await(60, TimeUnit.SECONDS); when I want to wait for a response; in the onObjectReceived method I call objectWasReceivedLatch.countDown().
I have the below code where I made a simple GUI. I would like Button2 to navigate to class 'Project2', which should start another piece of code. Just to note, in its current state, 'Project2' has no GUI, though I intend to add one soon. Anyway, this 'code jump' which I used by adding: String[] args = {};
Project2.main(args);
is not working, as the IDE says 'IOException must be caught or thrown'. I know how this works, though I am not sure how to implement it in the program.
Thanks in advance!
You can try to use dynamic class loading for your program. Below you can find lambda, which calls main method from com.stackoverflow.ExternalCaller class.
If you do not like to use lambda, you can create a simple anonymous class.
button.addActionListener(s -> {
try {
Class<?> externalCaller = Class.forName("com.stackoverflow.ExternalCaller");
Method main = externalCaller.getDeclaredMethod("main", new Class[]{String[].class});
main.invoke(null, new Object[]{new String[0]});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
});
ExternalCaller class in its turn looks something like that:
package com.stackoverflow;
public class ExternalCaller {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
In result once you click on the button you will get Hello World output in console.
If you would like to work with external jars etc. please look on Process class. Quick example:
Process proc = Runtime.getRuntime().exec("java -jar External.jar");
Or even more on fork/exec. You can read From Runtime.exec() to ProcessBuilder for more details.
Hope this will help. Good luck.
In most of the IDE's, when you right-click on the Button2 in the Design(GUI) pane, you can travel through:
Events -> Actions -> actionPerformed().
And write this code in the selected method to switch classes:
this.setVisible(false); //turns off the visibility of the current class
outputClass out = new outputClass(); //creating the object of the class you want to redirect to
out.setVisible(true);//turns on the visibility of the class you want to redirect to
I am trying to create a client library that reads JSON from an external file online. I already know about the function interfaces and optionals, but I was wondering if there is a way to allow users to supply callback functions such that the parent function exits completely. For JavaScript, such a function is as follows:
file.read('hello', function(err, data) {
// something here
});
Basically, I wish to do the same in Java. How can I do this such that the error callback supersedes the read function? What I mean is that in the event that the error callback is called, then read should not return a value at all. If the callback is not called then the read should return the value.
You could have the user pass in a function and then just not do anything with it if there is no error.
This example assumes that you have a custom class called Error that the caller is aware of and would like to interact with in case of an error.
public void read (String str, Function<Error,Void> errorFunc)
{
//interact w/ libraries, boolean error = true or false
//if there is an error, variable err of type Error contains information
if (error)
{
errorFunc.apply(err);
}
}
In Java upto 1.7 the only way to achieve javascript like callbacks is thru interface. The api user who calls your method read has the liberty of implementing what he feels needs to be done to handle the error by writing an implementation class for the interface at the invocation point.
public String read(String options,IErrorCallBack errorHandler) throws Exception {
try {
// When everything works fine return what you think should be returned.
return "Success";
}
catch(Exception e) {
// On Error call the function on the error handler.
errorHandler.doSomething();
throw e;
}
}
public interface IErrorCallBack {
public void doSomething();
}
// The invocation point.
read("myString", new IErrorCallBack() {
public void doSomething() {
// Your implementation.
}
});
I am doing something with fix protocol using quickfix library.
I wrote class like this:
public class ApplicationImpl implements Application {
...
#Override
public void toApp(Message arg0, SessionID arg1) throws DoNotSend {
//this is invoked before sending message
}
...
}
I wonder how to invoke some method after sending message?
QuickFIX does not offer a after-message-send callback.
You need to have this somewhere in your code to send a message (not in the overriden methods):
Session.sendToTarget(outgoingMessage, orderSession);
That will execute some internal quickfixJ code and then call toApp(). The toApp() method allows you do modify the message before it is sent to the broker. But ideally in order to do something after you send you just need to add code after the call to Session.sendToTarget().
If you are adventurous, you can modify QuickFIX/J to do it. The MINA network layer does provide a messageSent callback. If you override that method in QFJ's InitiatorIoHandler (or AcceptorIoHandler) you could either directly process the messageSent event or propagate it to a modified Application interface.
If I undertand correctly. You need to do some action after you send a message. If it is correct I have the following example:
public static void send(Message message) {
boolean sent = Session.sendToTarget(message, mySessionId);
if (sent){
//do something
}else {
//something else
}
System.out.println("El mensaje se mandó: " + sent);
} catch (SessionNotFound e) {
System.out.println(e);
}
}
I have a method, that connects to mail server, gets all the messages and returns these messages in an Array.
So this looks like this (pseudocode):
public Message[] getMessages() throws Exception {
try{
//Connection to mail server, getting all messages and putting them to an array
return Message[];
} finally {
CloseConnectionToMailServer(); //I don't need it anymore, I just need messages
}
}
I can put "return" instruction to "finally" block, but this disable potential Exception.
If I leave it as it is now, "return" can never be reached.
I think you caught the problem I ran at. How can I get all the messages I need, return an array with these messages and close connection to server in a delicate (in even "best practices") way?
Thank you in advance.
Your method is just fine. Even if you return from a try block finally block will be executed.
And your method must return a value :
public Message[] getMessages() throws Exception {
try{
//Connection to mail server, getting all messages and putting them to an array
return Message[];
} finally {
CloseConnectionToMailServer(); //I don't need it anymore, I just need messages
}
return null;
}
The 'standard' version (that I've seen) is
try {
doStuff()
} catch (Exception e) {
throw e;
} finally {
closeConnections();
}
return stuff;
I see no reason that shouldn't work for your code.
As a side note, if your code is a 'returns data' thing, I'd generally think it easier to make it a 'public Message[] getStuff() throws SQLException', then let the calling class handle the errors.
Why not this:
public Message[] getMessages() throws Exception {
Message = null;
try{
//Connection to mail server, getting all messages and putting them to an array
Message = Messages;
} finally {
CloseConnectionToMailServer(); //I don't need it anymore, I just need messages
return Message;
}
}