Liferay, how to get root logger? - java

I'm trying to develop portlet which sends email to administrators when a set of specified excpetions occured in a given time period. I'm trying to get root logger in liferay so i can add my appender to it and process all messages going trough the logging mechanism.
I looked into source code and seems that liferay uses java.util.logging.LogManager. I made a hook which is fired when server starts up. Here is my run() method:
public void run(String[] ids) throws ActionException {
System.out.println("initializing");
LogListener listener = new LogListener();
listener.setLevel(Level.ALL);
listener.setFilter(null);
Logger.getGlobal().addHandler(listener);
_log.debug("complete");
}
And LogListener class
package pl.com.mds.portlet.mailing.hook;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class LogListener extends Handler {
#Override
public void publish(LogRecord record) {
System.out.println("publishing******");
}
#Override
public void flush() {
// TODO Auto-generated method stub
System.out.println("have to flush! *****");
}
#Override
public void close() throws SecurityException {
// TODO Auto-generated method stub
System.out.println("close meee!");
}
}
But when some exception is thrown i cant see in console publishing****** only exception stacktrace. How can i get all logs in application and expceptions?
Thanks :)

Root logger can be obtained through standard procedure Logger.getLogger("logger name goes here"). Root logger has an empty string as its name. So you should edit your code as follows:
Logger.getLogger("").addHandler(listener);

Consider using LogFactoryUtil. Like following
private static final Log LOG = LogFactoryUtil.getLog(MyPortlet.class);

Related

Such a simple lejos program about EV3UltrasonicSensor also can appear mistake?

import lejos.hardware.lcd.LCD;
import lejos.hardware.port.SensorPort;
import lejos.hardware.sensor.EV3UltrasonicSensor;
import lejos.robotics.SampleProvider;
import lejos.utility.Delay;
public class NewUl {
private EV3UltrasonicSensor ev3UltrasonicSensor;
public NewUl() {
// TODO Auto-generated constructor stub
ev3UltrasonicSensor=new EV3UltrasonicSensor(SensorPort.S4);
}
public void getData() {
SampleProvider sampleProvider=ev3UltrasonicSensor.getDistanceMode();
float[] sample=new float[sampleProvider.sampleSize()];
sampleProvider.fetchSample(sample, 0);
LCD.clear();
LCD.drawString(String.valueOf(sample[0]),0,3);
LCD.refresh();
Delay.msDelay(3000);
LCD.clear();
LCD.refresh();
}
public void close() {
ev3UltrasonicSensor.close();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
NewUl newUl=new NewUl();
newUl.getData();
newUl.close();
}
}
This is a simple lejos program about EV3UltrasonicSensor.
The 13th line of code is:
ev3UltrasonicSensor=new EV3UltrasonicSensor(SensorPort.S4);
The 31th line of code is:
NewUl newUl=new NewUl();
The exception thrown is:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid sensor mode at lejos.hardware.sensor.UARTSensor.<init>(UARTSensor.java:62)
at lejos.hardware.sensor.EV3UltrasonicSensor.<init>(EV3UltrasonicSensor.java:75)
at control.NewUl.<init>(NewUl.java:13) at control.NewUl.main(NewUl.java:31)
Such a simple program also can appear mistake? It make me confused.
Could you give me some help or some tips? Any help is appreciated and if you need to know anything more feel free to ask.
From the Exception messages, it looks like that the creation of the instance of lejos.hardware.sensor.EV3UltrasonicSensor is not correct. It may be that the value SensorPort.S4 you passed to the constructor is not proper or you may have to set values to a few more properties of the instance in question.

Standalone Apache Camel application doesn' run

I'm on this problem: can't get my apache camel batch run. Here is the code:
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class Launch {
private Main main;
public static void main(String[] args) {
Launch l = new Launch();
System.out.println(System.getProperty("from") +" -> "+System.getProperty("to"));
try {
l.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public void execute() throws Exception {
main = new Main();
main.enableHangupSupport();
main.addRouteBuilder(new FromFileToFile());
main.run();
}
private static class FromFileToFile extends RouteBuilder {
#Override
public void configure() throws Exception {
onException(Exception.class).handled(true).process(new Processor() {
public void process(Exchange arg0) throws Exception {
arg0.getException().printStackTrace();
}
});
from(System.getProperty("from") + "")
.filter(body().contains("DOTHIS"))
.process(new Processor() {
public void process(Exchange arg0) throws Exception {
System.out.println(arg0.getIn().getBody()
.toString());
}
}).to(System.getProperty("to"))
.to(System.getProperty("to") + ".BAK");
}
}
}
I don't want to use the Thread.sleep(...) workaround. I simply copied and modified the source stuff posted on this official docs page. When I run my dummy program using Eclipse, application simply hangs. I can't figure out what's wrong.
Your application doesn't probably hang, it just won't do anything. :)
You have defined filter that checks if Camel Message body contains word "DOTHIS". When you consume file with File consumer the body will be of type GenericFile. Then when your filter checks for that string it surely won't find it since the body is not string.
Solution: Convert file body to string first and then your filter will work and you get the result you were expecting. Conversion can be done like this
from(System.getProperty("from") + "")
.convertBodyTo(String.class, "UTF-8")
.filter(body().contains("DOTHIS"))
You might also want to increase logging level so you can get the grasp of what's going on in your route.
It was a problem about path. I passed arguments as options like this:
file://Users/francesco/..
As I'm using windows I must specify uri like this
file:///C:/Users/francesco/..
The batch doesn't hangs, it continues to poll directory for new files to consumes.

how to show result of java program in console output in eclipse using log4j logger?

i am trying to write a program with jena library for my ontology. For jena i am using log4j when i add jena libraries to my project, eclipse console do not show any result but without it System.out.println("something") works good. i think problem is in log4j. and to set console output to it.but i don't know how to use this. this is my code:
package tutorial;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.datatypes.xsd.*;
import java.io.*;
public class helloRDFworld {
private InfModel model;
public static void main(String[] args) {
// TODO Auto-generated method stub
helloRDFworld application=new helloRDFworld();
application.test();
}
private void loadantology (String antologyfile)
{
try {
String uri =new File(antologyfile).toURI().toString();
model.read(uri);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public helloRDFworld(){
model=ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM_RULE_INF);
}
public void test()
{
loadantology("food.owl");
}
}
this is my library list
share your information please
with Regard
You need to create a log4j.properties file and add it to your classpath. Add this to your log4j.properties:
log4j.rootLogger = ALL, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.conversionPattern=%m%n
Make sure you have your apache log4j library.
Then declare and initialise like this:
final static Logger logger = Logger.getLogger(classname.class);
Then use it to capture errors, debug or info messages e.g.
logger.info("This is info ");
Hope it helps

Junit testing an Akka singleton actor: preStart() hook not called

I would like to test a singleton actor using java in Scala IDE build of Eclipse SDK (Build id: 3.0.2-vfinal-20131028-1923-Typesafe) and Akka is 2.3.1.
public class WorkerTest {
static ActorSystem system;
#BeforeClass
public static void setup() {
system = ActorSystem.create("ClusterSystem");
}
#AfterClass
public static void teardown() {
JavaTestKit.shutdownActorSystem(system);
system = null;
}
#Test
public void testWorkers() throws Exception {
new JavaTestKit(system) {{
system.actorOf(ClusterSingletonManager.defaultProps(
Props.create(ClassSingleton.class), "class",
PoisonPill.getInstance(),"backend"), "classsingleton");
ActorRef selection = system.actorOf(ClusterSingletonProxy.defaultProps("user/classsingleton/class", "backend"), "proxy");
System.out.println(selection);
}};
}
}
the ClassSingleton.java:
public class ClassSingleton extends UntypedActor {
LoggingAdapter log = Logging.getLogger(getContext().system(), this);
public ClassSingleton() {
System.out.println("Constructor is done");
}
public static Props props() {
return Props.create(ClassOperator.class);
}
#Override
public void preStart() throws Exception {
ActorRef selection = getSelf();
System.out.println("ClassSingleton ActorRef... " + selection);
}
#Override
public void onReceive(Object message) {
}
#Override
public void postStop() throws Exception {
System.out.println("postStop ... ");
}
}
The ClassSingleton actor is doing nothing, the printout is:
Actor[akka://ClusterSystem/user/proxy#-893814405] only, which is printed from the ClusterSingletonProxy. No exception and Junit is done, green flag. In debugging ClassSingleton is not called (including contructor and preStart()). Sure it is me, but what is the mistake? Even more confusing that the same ClassSingleton ClusterSingletonManager code is working fine outside of javatestkit and junit.
I suspect that the cluster setup might be reponsible, so I tried to include and exclude the following code (no effect). However I would like to understand why we need it, if we need it (it is from an example code).
Many thanks for your help.
Address clusterAddress = Cluster.get(system).selfAddress();
Cluster.get(system).join(clusterAddress);
Proxy pattern standard behavior is to locate the oldest node and deploy the 'real' actor there and the proxy actors are started on all nodes. I suspect that the cluster configuration did not complete and thus why your actor never got started.
The join method makes the node to become a member of the cluster. So if no one joins the cluster the actor with proxy cannot be created.
The question is are your configuration files that are read during junit test have all the information to create a cluster? Seed-nodes? Is the port set to the same as the seed node?

GWT: execution stops when adding a Composite widget to RootPanel

I have an abstract class extending Composite (AbstractWhiteBoard). Then I have a concrete class extending AbstractWhiteBoard. When I instantiate the concrete class and try to add it to the RootPanel, the program simply stops executing. There is no error or any output to direct me to a log file. I have no idea what is going wrong.
Here is my abstract class:
public abstract class AbstractWhiteBoard extends Composite {
/*
* FIELDS
*/
protected HorizontalPanel WhiteBoardWrapperPanel;
public AbstractWhiteBoard( ) {
WhiteBoardWrapperPanel = new HorizontalPanel();
WhiteBoardWrapperPanel.setStyleName("WhiteBoard-Wrapper");
initWidget(WhiteBoardWrapperPanel);
}
/*
* ABSTRACT PUBLIC METHODS
*/
abstract public void addNotecard( Notecard nc );
abstract public void addPostit( Postit postit );
/*
* ABSTRACT PROTECTED HELPER METHODS
*/
abstract protected void registerDragDropControllers();
}
And here is my concrete implementation class:
public class ConcreteWhiteBoard extends AbstractWhiteBoard {
/*
* CONTSTRUCTORS
*/
public ConcreteWhiteBoard() {
super();
}
/*
* PUBLIC METHOD OVERRIDES
*/
#Override
public void addNotecard(Notecard nc) {
// TODO Auto-generated method stub
}
#Override
public void addPostit(Postit postit) {
// TODO Auto-generated method stub
}
/*
* PRIVATE HELPER METHOD OVERRIDES
*/
#Override
protected void registerDragDropControllers() {
// TODO Auto-generated method stub
}
}
So, what is happening, is I have this code:
AbstractWhiteBoard wb = new ConcreteWhiteBoard();
RootPanel.get().add(wb);
Window.alert("wb added!");
But after I add wb to the RootPanel, execution stops. The alert statement never even gets called. There is no error and I don't see anything in the log.
Is there something wrong with having an abstract class that extends Composite? Or is it something entirely different that I am just not seeing? any help is greatly appreciated!
take a look at the uncaught exception handler in gwt. if a runtime exception occurs it is called. Think of it as a global try catch around your code.
But if your code is inside your entrypoint on module load make sure to set the uncaught exception handler and call the next function within a timer (so that the uncaught exception handler is active.
For a quick example take a look here:
http://code.google.com/p/mgwt/source/browse/src/main/java/com/googlecode/mgwt/examples/showcase/client/ShowCaseEntryPoint.java?repo=showcase
In web mode you can turn on emulated stack (and get meaningful stacktraces). YOu need to add this to your gwt.xml file (only for debug purposes because it is quite slow):
<set-property name="compiler.emulatedStack" value="true" />
<set-configuration-property name="compiler.emulatedStack.recordLineNumbers" value="true" />
<set-configuration-property name="compiler.emulatedStack.recordFileNames" value="true" />
So, this is one of those times that you feel like the most retarded developers of all time. What happened is that I was running several async calls all at the same time and I tried to refer to an object that was returned by one of those calls before it was actually created. Dunce cap on me, I got confused with async threads.
Major thanks to Daniel. Your input lead me straight to the problem!

Categories