public class AtrExceptionResolver implements HandlerExceptionResolver {
private final static Log log =LogFactory.getLog(AtrExceptionResolver.class);
#Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
boolean ajaxrequest = false;
if (request.getRequestURI().indexOf("/ajax/") > 0)
ajaxrequest = true;
if (ex instanceof AtrException) {
AtrException atrE = (AtrException) ex;
log.error(
"AtrException:code:" + atrE.getCode() + ",desc:"
+ atrE.getMsg(), ex);
if (ajaxrequest) {
PrintWriter out = null;
try {
out = response.getWriter();
out.print("{\"e\":\"" + atrE.getCode()
+ "\",\"message\":\"" + atrE.getMsg() + "\"}");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.close();
}
} else {
try {
goToError(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
log.error("Exception:desc:" + ex.getMessage(), ex);
if (ajaxrequest) {
PrintWriter out = null;
try {
out = response.getWriter();
out.print("{\"e\":\"3\",\"message\":\"system error\"}");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.close();
}
} else {
try {
goToError(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
private void goToError(HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.sendRedirect(request.getContextPath() + "/jsp/error.jsp");
}
atrException is defined by myself,so I do not want to printStackTrace() in console.only print it in log.
I debug it,found it print by standardwrappervalve.invoke().
How to not print atrException message in console?
If I understand your question then you want the exception stack trace in a String object which you can use it for logging.
You can use below method.
public String getErrorLog(Throwable throwable) {
if (throwable != null) {
StringWriter errors = new StringWriter();
throwable.printStackTrace(new PrintWriter(errors));
return errors.toString();
}
return "";
}
Returned value is stack trace which you can log.
return new ModelAndView();
This way can solve.
Related
I have a list of free sockets conn, and i put then in a Map , if status of free or inUse, but the synchronized dosent seens to be working correctly
this is my code:
my map is like this:
private ConcurrentHashMap<MVConnection, Boolean> listaConn = new ConcurrentHashMap<>();
my connManager is this:
public synchronized MVConnection getInstance() {
System.out.println("pass here on getInstance");
System.out.println("--------------------------------------------------------");
System.out.println("Before request Instance");
LogLinhas();
System.out.println("--------------------------------------------------------");
MVConnection searchResult = null;
System.out.println(Thread.currentThread().getName() + " is running");
while (searchResult == null) {
searchResult = this.listaConn.search(1, (conn, free) -> {
if (free) {
return conn;
}
return null;
});
}
notify();
System.out.println(Thread.currentThread().getName() + " notifying");
if (searchResult != null) {
this.listaConn.replace(searchResult, false);
try {
System.out.println("Set " + searchResult.getServerPort() + " as busy");
} catch (MVException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("--------------------------------------------------------");
System.out.println("After request Instance");
LogLinhas();
System.out.println("--------------------------------------------------------");
return searchResult;
}
and the function the request the cont is this:
public abstract class AbstractD3Dao<T extends Serializable> {
#Autowired
ConexaoD3 conexao;
protected MVConnection getCurrentSession() {
System.out.println("Abstract request the conn");
MVConnection connPool = null;
synchronized (conexao.getInstance()) {
while (connPool == null) {
try {
System.out.println("Aguardando Conexao");
System.out.println(Thread.currentThread().getName() + " is waiting");
wait();
} catch (InterruptedException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
connPool = conexao.getInstance();
}
}
try {
System.out.println(" Abstract assineg the PIB " + connPool.getServerPort() + "to use");
} catch (MVException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connPool;
}
`
I need to log my messages not only into system logs ( as I know, system log buffer is quite short, but I need to see logs for 3-5 days ), but also in a separate text file. Logging must be asynchronous.
Could you give me an advice about which component should I use in this case?
Thanks.
I hope it will be useful for you.
public void appendLog(String text) {
File logFile = new File("sdcard/log.file");
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Don't forget to add permission for android.permission.WRITE_EXTERNAL_STORAGE in Manifest!
Works asynchronously and dose not need to permission !
just remember call the init method from your application in onCreateMethod for initializing the Logger
class Logger {
private static File logFileLoc;
private static ExecutorService logExecutor;
public static void init(Context applicationContext, String logFileName, boolean reCreate) {
logFileLoc = new File(applicationContext.getCacheDir(), logFileName);
if (reCreate && logFileLoc.exists()) logFileLoc.delete();
logExecutor = Executors.newSingleThreadExecutor();
}
public static void log(final String tag, final String msg) {
if (logFileLoc == null) try {
throw new Exception("First you should call init method in your application");
} catch (Exception e) {
e.printStackTrace();
}
Log.d(tag, msg);
logExecutor.execute(new Runnable() {
#Override
public void run() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(logFileLoc,true));
String timeStamp = DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis()));
writer.append(timeStamp + " " + tag + " : " + msg );
writer.newLine();
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
also you can do the same thing with Timber library for more info :
https://medium.com/#vicky7230/file-logging-with-timber-4e63a1b86a66
I'm trying to parse json (steam webchat) which looks like that (I've changed response cause I don't wanna show the data):
/**/({
"pollid": 00,
"messages": [
{
"type": "personastate",
"timestamp": 0000000000,
"utc_timestamp": 000000000,
"steamid_from": "000000000000",
"status_flags": 0000000,
"persona_state": 0,
"persona_name": "asd"
}
]
,
"messagelast": 00,
"timestamp": 0000000000,
"utc_timestamp": 000000000000,
"messagebase": 00,
"sectimeout": 0,
"error": "OK"
})
And my parsing class looks like that:
package jsonRequest;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class NewMessageJson {
public Integer poollid;
private String lastMessageId;
private String error;
private String messageBase;
public NewMessageJson(String response) {
response = response.substring(response.indexOf("{"),
response.indexOf("}") + 1); // cut off comment block
JsonFactory factory = new JsonFactory();
JsonParser jp = null;
try {
jp = factory.createJsonParser(response);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (jp.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Server didn't return any data");
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
jp.nextToken();
if (fieldName.equals("messagelast")) {
setLastMessageId(jp.getText());
} else if (fieldName.equals("pollid")) {
setPoollid(jp.getIntValue());
} else if (fieldName.equals("messagebase")) {
setMessageBase(jp.getText());
} else if (fieldName.equals("error")) {
setError(jp.getText());
}
}
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Integer getPoollid() {
return poollid;
}
public void setPoollid(Integer poollid) {
this.poollid = poollid;
}
public String getLastMessageId() {
return lastMessageId;
}
public void setLastMessageId(String lastMessageId) {
this.lastMessageId = lastMessageId;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessageBase() {
return messageBase;
}
public void setMessageBase(String messageBase) {
this.messageBase = messageBase;
}
}
And when it comes to the line
if (fieldName.equals("messagelast")) {
It crashes and returns NPE.
I have 3 other classes looking exactly like this one and everything works perfectly.
I am pretty sure the reason you are getting the NPE is because you initially instantiate JsonParser jp as null. You assign it to factory.createJsonParser(response) in your try block but do not deal with the error in any way besides printing the stack trace. If there was an error executing factory.createJsonParser(response), you need to make sure nothing else runs.
I would suggest changing your code to this:
...
JsonFactory factory = new JsonFactory();
JsonParser jp = null;
try {
jp = factory.createJsonParser(response);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("There was an error while setting jp to factory.createJsonParser(response). Error message is: " + e1.getMessage());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("There was an error while setting jp to factory.createJsonParser(response). Error message is: " + e1.getMessage());
}
if(jp != null) {
try {
if (jp.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Server didn't return any data");
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
jp.nextToken();
if (fieldName.equals("messagelast")) {
setLastMessageId(jp.getText());
} else if (fieldName.equals("pollid")) {
setPoollid(jp.getIntValue());
} else if (fieldName.equals("messagebase")) {
setMessageBase(jp.getText());
} else if (fieldName.equals("error")) {
setError(jp.getText());
}
}
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
...
This way, you can avoid all NPEs!
EDIT: You should also implement what peeskillet suggested
I have a class that allows to download a file from the internet:
public String download(String URL) {
try {
if(somethingbad) {
// set an error?
return false;
}
}
//...
catch (SocketException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch(InterruptedIOException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
Now, I am calling this function in another class and i want to show a message that will help me figure out why this will not work.
what can i do to display something like this?
HTTPReq r = new HTTPReq("http://www.stack.com/api.json");
if(r.err) {
showMessage(getMessage());
}
and the getMessage() will return the SocketException or IOException or even "empty url" if the URL is empty.
First of all I do not think you need all these:
SocketException, UnsupportedEncodingException, ClientProtocolException since they extend IOException
but if you want you can do this:
public String download(String URL) throws IOException, Exception {
try {
if(somethingbad) {
throws new Exception("My Message);
}
}
catch (IOException e) {
throw e;
}
}
And then in your other file:
try {
// some stuff
}
catch (Exception e) {
// do something with e.getMessage();
}
catch (IOException e) {
// do something with e.getMessage();
}
Instead of just doing e.printStackTrace() inside the catch blocks, throw the exception back like so:
throw e;
Then you can surround the calling code like so:
try {
HTTPReq r = new HTTPReq("http://www.stack.com/api.json");
} catch (Exception e) {
// Show error message
}
I'm trying to implement multiplayer in a game I've been writing, and I've gotten everything to successfully connect (I think..), but when I'm running it, there's an EOFException thrown by the client, and the object (an ArrayList) isn't successfully received.
Code for the server thread:
class ServerThread implements Runnable
{
ServerSocket server = null;
Socket controlSocket = null;
ObjectOutputStream outStream = null;
ObjectInputStream inStream = null;
#Override
public void run() {
setupConnection();
while(true){
sendObject(out.getStuff());
}
}
void setupConnection(){
Log.e("OUTPUTSHOOTER","init-connect");
try {
server = new ServerSocket(SERVERPORT);
Log.e("OUTPUTSHOOTER","server initiated port: "+SERVERPORT);
controlSocket = server.accept();
Log.e("OUTPUTSHOOTER","connected");
inStream = new ObjectInputStream(controlSocket.getInputStream());
outStream = new ObjectOutputStream(controlSocket.getOutputStream());
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("OUTPUTSHOOTER",server+" "+controlSocket+" "+inStream+" "+outStream);
}
public Object recieveObject(){
Object o = null;
try {
o = inStream.readObject();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
public void sendObject(Object o)
{
try {
outStream.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And then the code for the client:
class ClientThread implements Runnable
{
Socket controlSocket = null;
ObjectOutputStream outStream = null;
ObjectInputStream inStream = null;
#Override
public void run() {
setupConnection();
while(true){
Log.e("OUTPUTSHOOTER","recieving");
Object in = recieveObject();
if(in!= null && in instanceof ArrayList)
{
Log.e("OUTPUTSHOOTER","loading");
out.load((ArrayList<UniverseObject>)in);
}
}
}
void setupConnection(){
Log.e("OUTPUTSHOOTER","ip: "+SERVERIP);
while(controlSocket == null) {
try {
controlSocket = new Socket(SERVERIP,SERVERPORT);
Log.e("OUTPUTSHOOTER","socket connected");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Log.e("OUTPUTSHOOTER","attempting streams");
outStream = new ObjectOutputStream(controlSocket.getOutputStream());
Log.e("OUTPUTSHOOTER","output working");
inStream = new ObjectInputStream(controlSocket.getInputStream());
Log.e("OUTPUTSHOOTER","streams connected");
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object recieveObject(){
Object o = null;
try {
o = inStream.readObject();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
public void sendObject(Object o)
{
try {
outStream.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What does this mean? And perhaps more importantly, how can I fix it? Thanks in advance..
I don't see you closing your outputstream.
See this SO topic: Problem serializing and deserializing ArrayList
Turns out the server wasn't properly initiating it's input and output streams, even though its sockets were successful. Dunno why, but it only works if I started with the output stream first, then the input (?). Having some other really strange bugs, but at least the communication seems to work.. I'll look more in to them before posting here about it. Thanks guys!