Glassfish v2.1 starts fine but logs don't get displayed - java.util.logging

I'm facing this problem everytime I start glassfish server. The server starts fine but due to this error my logger outputs don't get logged to the server.log file. This seems like a bug in glassfish version 2.1. I cant shift to a higher version as the application I'm running doesn't support higher versions. Most of the posts online report this error when glassfish is started from MyEclipse IDE and suggest stopping the server from IDE and then restarting it from command-line. I always start my server from the terminal still I get this error. I'm really confused and can't do much debugging without viewing my logs. Could anyone suggest a suitable workaround please?
Few of the things I tried were
My log level was INFO initially, changed it to FINE and SEVERE but still it has no effect.
I redirected my logs to a different loacation thinking that might help but No use.
I even tried modifying /etc/java-6-openjdk/logging.properties as per the post -recursive call into SystemOutandErrhandler
but that did not help either.
This is really annoying. Help would be really appreciated.
Thanks in advance.
-client
-XX:+UnlockDiagnosticVMOptions
-XX:MaxPermSize=192m
-Xmx512m
-XX:NewRatio=2
-XX:+LogVMOutput
-XX:LogFile=/home/aakanksha/softwares/glassfish/domains/visionael/logs/jvm.log
-cp
/home/aakanksha/softwares/glassfish/lib/jhall.jar:/home/aakanksha/softwares/glassfish/lib/appserv-launch.jar
com.sun.enterprise.server.PELaunch
start
recursive call into SystemOutandErrhandler
java.lang.RuntimeException: recursivecall
at com.sun.enterprise.server.logging.SystemOutandErrHandler$LoggingByteArrayOutputStream.flush(SystemOutandErrHandler.java:359)
at java.io.PrintStream.write(PrintStream.java:449)
at com.sun.enterprise.server.logging.SystemOutandErrHandler$LoggingPrintStream.write(SystemOutandErrHandler.java:293)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:220)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:281)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:124)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:134)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:220)
at java.io.Writer.write(Writer.java:157)
at java.util.logging.StreamHandler.publish(StreamHandler.java:209)
at java.util.logging.ConsoleHandler.publish(ConsoleHandler.java:105)
at java.util.logging.Logger.log(Logger.java:573)
at java.util.logging.Logger.doLog(Logger.java:598)
at java.util.logging.Logger.log(Logger.java:621)
at com.sun.enterprise.server.logging.SystemOutandErrHandler$LoggingByteArrayOutputStream.flush(SystemOutandErrHandler.java:368)
at java.io.PrintStream.write(PrintStream.java:449)
at com.sun.enterprise.server.logging.SystemOutandErrHandler$LoggingPrintStream.write(SystemOutandErrHandler.java:293)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:220)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:290)
at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:294)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:140)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
at java.util.logging.StreamHandler.flush(StreamHandler.java:242)
at java.util.logging.ConsoleHandler.publish(ConsoleHandler.java:106)
at java.util.logging.Logger.log(Logger.java:573)
at java.util.logging.Logger.doLog(Logger.java:598)
at java.util.logging.Logger.log(Logger.java:662)
at com.sun.enterprise.server.ApplicationServer.printStartupInfo(ApplicationServer.java:618)
at com.sun.enterprise.server.ApplicationServer.onInitialization(ApplicationServer.java:170)
at com.sun.enterprise.server.ondemand.OnDemandServer.onInitialization(OnDemandServer.java:103)
at com.sun.enterprise.server.PEMain.run(PEMain.java:399)
at com.sun.enterprise.server.PEMain.main(PEMain.java:336)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:622)
at com.sun.enterprise.server.PELaunch.main(PELaunch.java:415)

From GLASSFISH-6164 the workaround is listed as:
If I reset System.out and System.err to point to a temporary file before calling
readConfiguration and don't reset them to point to the logger then everything
works fine.
You might be able to create a custom LogManager that performs that workaround when readConfiguration is called. Then install the custom LogManager by using the java.util.logging.manager system property on startup.
public class ConsoleLogManager extends LogManager {
#Override
public void readConfiguration() throws IOException, SecurityException {
final PrintStream out = System.out;
final PrintStream err = System.err;
System.setOut(off());
try {
System.setErr(off());
try {
super.readConfiguration();
} finally {
System.setErr(err);
}
} finally {
System.setOut(out);
}
}
#Override
public void readConfiguration(InputStream ins) throws IOException, SecurityException {
final PrintStream out = System.out;
final PrintStream err = System.err;
System.setOut(off());
try {
System.setErr(off());
try {
super.readConfiguration(ins);
} finally {
System.setErr(err);
}
} finally {
System.setOut(out);
}
}
#Override
public void reset() throws SecurityException {
final PrintStream out = System.out;
final PrintStream err = System.err;
System.setOut(off());
try {
System.setErr(off());
try {
super.reset();
} finally {
System.setErr(err);
}
} finally {
System.setOut(out);
}
}
private static PrintStream off() {
return new PrintStream(new ByteArrayOutputStream());
}
}
Another workaround would be to wrap the System.out and System.in print streams and do nothing when you detect reentrance. You can use the custom LogManager to get them installed.

Related

Testing camel-sql route with in-memory database not fetching results

I have written the code using camel-sql which is working fine. Now I have to write test cases for the same. I have used in-memory database H2. I have initialized the database and assigned the datasource to sqlComponent.
// Setup code
#Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry jndi = super.createRegistry();
// this is the database we create with some initial data for our unit test
database = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2).addScript("createTableAndInsert.sql").build();
jndi.bind("myDataSource", database);
return jndi;
}
// Testcase code
#SuppressWarnings("unchecked")
#Test
public void testRoute() throws Exception {
Exchange receivedExchange = template.send("direct:myRoute", ExchangePattern.InOut ,exchange -> {
exchange.getIn().setHeader("ID", new Integer(1));
});
camelContext.start();
MyClass updatedEntity = (MyClass)jdbcTemplate.queryForObject("select * from MY_TABLE where id=?", new Long[] { 1l } ,
new RouteTest.CustomerRowMapper() );
// Here I can get the updatedEntity from jdbcTemplate
assertNotNull(receivedExchange);
assertNotNull(updatedEntity);
}
// Main code
from("direct:myRoute")
.routeId("pollDbRoute")
.transacted()
.to("sql:select * from MY_TABLE msg where msg.id = :#"+ID+"?dataSource=#myDataSource&outputType=SelectOne&outputClass=com.entity.MyClass")
.log(LoggingLevel.INFO,"Polled message from DB");
The problem is, as soon as the test case starts, it is saying
No bean could be found in the registry for: myDataSource of type: javax.sql.DataSource
I looked into camel-SQL component test cases and doing the same thing but the code is not able to find dataSource. Please help. Thanks in advance.
After spending a lot of time on this issue, I identified that H2 database was using JDBCUtils to fetch records and It was throwing ClassNotFoundException. I was getting it nowhere in Camel exception hierarchy because this exception was being suppressed and all I was getting a generic exception message. Here is the exception:
ClassNotFoundException: com.vividsolutions.jts.geom.Geometry
After searching for the issue I found out that It requires one more dependency. So I added it and it resolved the issue.
Issue URL: https://github.com/elastic/elasticsearch/issues/9891
Dependency: https://mvnrepository.com/artifact/com.vividsolutions/jts-core/1.14.0

Getting the "no type was found that matches the controller named" error message during Ajax Request

I've seen a lot of topics about this, but unfortunately I believe that each case is a different case (or most of them), and I really would love some experts opinion about my case in particular since I cannot make my code work even after reading through some of the other topics.
Situation: I am using an Ajax Request call in jQuery to a WebService method I have created in an WebApi project together with a MVC 4 Application.
My WebService controller class looks like the default, like this:
public class AdditionalInfoController : ApiController
{
//GET api/AdditionalInfo
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
//GET api/AdditionalInfo/5
public string Get(int id)
{
return "value";
}
//PUT api/AdditionalInfo/5
public void Put(int id)
{
string test = "";
}
}
My Ajax Request from jQuery looks like this:
function GetAdditionalInfo(obj)
{
var request = jQuery.ajax({
url: "/api/AdditionalInfo/Get",
type: "GET",
data: { id: obj.id },
datatype: "json",
async: false,
beforeSend: function () {
},
complete: function () {
}
})
.done(function (a,b,c) {
alert("Additional info was retrieved successfully!");
})
.fail(function (a,b,c) {
alert("An error happened while trying to get the additional info!");
});
}
My WebAPIConfig file looks like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
And last but not least, this is my problem: this error message keeps appearing when I browse the returned data variable in .fail and this is what is written:
"{
"Message":"No HTTP resource was found that matches the request URI 'http://localhost:59096/api/AdditionalInfo/Get?id=1'.",
"MessageDetail":"No type was found that matches the controller named 'AdditionalInfo'."
}"
I would really appreciate it if someone could help me as soon as possible. Thanks in advance!
Best regards,
Mad
Looking at the error looks like Web API is unable to find the controller 'type' AdditionalInfo. Web API uses assemblies resolver to scan through the assemblies and finds out the controller types. In your case for some reason its unable to find your 'AdditionalInfo' controller probably because it has some problem loading the assembly having this controller.
Try the following and see if there are any errors logged in your EventLog. If you notice any errors then probably you should check if your controllers are present in those assemblies.
Make the following change in Web.config to view errors in EventLog
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="WebApiDiagnostics" />
</listeners>
</trace>
</system.diagnostics>
In your WebApiConfig.cs, you can do the following:
IAssembliesResolver assembliesResolver = config.Services.GetAssembliesResolver();
ICollection<Assembly> assemblies = assembliesResolver.GetAssemblies();
StringBuilder errorsBuilder = new StringBuilder();
foreach (Assembly assembly in assemblies)
{
Type[] exportedTypes = null;
if (assembly == null || assembly.IsDynamic)
{
// can't call GetExportedTypes on a dynamic assembly
continue;
}
try
{
exportedTypes = assembly.GetExportedTypes();
}
catch (ReflectionTypeLoadException ex)
{
exportedTypes = ex.Types;
}
catch (Exception ex)
{
errorsBuilder.AppendLine(ex.ToString());
}
}
if (errorsBuilder.Length > 0)
{
//Log errors into Event Log
Trace.TraceError(errorsBuilder.ToString());
}
BTW, some of the above code is actually from the DefaultHttpControllerTypesResolver which Web API uses to resolve the controller types.
http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Http/Dispatcher/DefaultHttpControllerTypeResolver.cs
Edited:
One more scenario where you could hit this problem is if your controller is nested inside another class. This was a bug which was fixed later though.
Ok, so I believe I found out what was going on. I am not entirely certain, but at least my problem got fixed.
Simply by changing what was inside of the "data" field in the Ajax call and I have created a class for an object in the application to hold the whole data. It seems that for some reason the method could not have the syntax "Get(int ID)".
Instead, I did something like "Get( object)" and in the Ajax Request something like "data: obj.ID" and voila, it worked.
Also, since the framework is picky about the names of the REST methods (Get, Post, Put and Delete), I changed the name of the method to something else (like Retrieve or something).
Hopefully this will help someone in the future as well.
Best regards,
Mad
Be sure that you have the same parameter names in your methods (int id) as well as in your WebApiConfig/RouteConfig. Try it by changing
public string Get(int id)
{
return "hello";
}
to
public string Get(int? id = null)
{
return "hello";
}
I had the same problem. with me it happens due to a crush in the visual studio (2012). I had the controller file open in visual studio but it wasn't a part of my solution - I couldn't find him in the controllers directory in the solution explorer.
I just added the file to the solution by right clicking on controllers directory => add => existing item.
that fixed the problem for me.
if that doesn't work maybe try to delete the controller and add a new one with the same code . . .

PHPUnit 3.7.19 and Symfony2 broken tests

I'm developing some test for a Symfony2.0 project and running them with PHPUnit.
On my PC works fine but trying them in other environments the tests fails. I thought the problem was php version but after run them in differents environments I'm lost.
My environment is Ubuntu 12.04 and PHP 5.3.10 => Works fine.
2 PC with Ubuntu 12.10 and PHP 5.4.6:
Fatal error: Call to a member function get() on a non-object
This error is on a class which extends Symfony\Bundle\FrameworkBundle\Test\WebTestCase where is overwritten the setUp() and tearDown() methods.
public function setUp()
{
$this->client = static::createClient();
$this->client->followRedirects(true);
$crawler = $this->client->request('GET', '/admin/login');
$loginForm = $crawler->selectButton('save')->form(array(
'_username' => 'user',
'_password' => 'pass'
));
$this->client->submit($loginForm);
$this->container = $this->client->getContainer();
parent::setUp();
}
public function tearDown()
{
//Here is get() on a non-object, $this->container doesn't exists
$this->container->get('doctrine.odm.mongodb.document_manager')->getConnection()->close();
parent::tearDown();
}
2 PC, one with Ubuntu 12.10 and PHP 5.4.6 and other with Windows 7 and PHP 5.3.8:
PHP Fatal error: Call to a member function getSite() on a non-object
This error is on a class which extends the above class that has tearDown() method wrong but in this case this class works and the error is different although is related with $this->container:
//In this case, the user doesn't exists
$site = $this->container->get('security.context')
->getToken()->getUser()->getSite();
The problem is I don't know why is this. If this is related to PHP, PHPUnit(All of us have the same version), Symfony2.0 or SO.
Edit:
Ok, problems solved.
First:
Fatal error: Call to a member function get() on a non-object
Had a wrong line of code in the class which has setUp() and tearDown() methods. A line like that:
$link = $crawler->filter('a:contains("Test")')->eq(1)->link();
I had this line commented, sorry :). But I don't know why PHPUnit show me this error and not the error of link method.
Second:
PHP Fatal error: Call to a member function getSite() on a non-object
In the others environments, the test database had not been deployed.
This question will not help anyone but help me to try new things. Thanks!
It is an exected behavior for PHPUnit.
I managed to reproduce the error with the following code:
final class ExceptionErrorTest extends PHPUnit_Framework_TestCase
{
/**
* #var MyObject
*/
private $object;
public function setUp() {
throw new \RuntimeException();
$this->object = new MyObject();
}
public function testItShouldNeverBeCalled()
{
var_dump('never called');
}
public function tearDown()
{
$this->object->neverCalled();
}
}
class MyObject
{
public function neverCalled() {
return true;
}
}
// will ouput PHP Fatal error:
Call to a member function neverCalled() on a non-object in ExceptionErrorTest.php on line 22
To explain more clearly, PHPUnit will catch any exceptions triggered in the setUp method (in order for the printers to show at the end of the execution).
After that you can see that the tearDown() is called to finish the test, but since the initialization of the attribute was never reached, a PHP error is issued, and PHPUnit will never reach the code where it shows all the exceptions that occurred.
That is why you did not get the exception. To fix this, you need to make sure that any code that can throw exceptions in the setup is wrapped in a try() catch () statement like this:
public function setUp() {
try {
throw new \RuntimeException('My message');
} catch (\Exception $e) {
echo 'An error occured in the setup: ' $e->getMessage();
die;
}
$this->object = new MyObject();
}
Hope it helps someone in the future.

NoSuchMethodException with getter and setter in play framework 1.2.5, when deployed in weblogic

I am using play framework for my application. It workks correctly in dev mode but gives me an error in prod mode
Execution exception (In /app/helper/FinansHelper.java around line 189)
NoSuchMethodException occured : finansServis.helper.KayitliIslemDto.getIpcMemo()
How can I solve this problem?
Edit: My KayitliIslemDto class
public class KayitliIslemDto {
public IPCMemo ipcMemo;
public TahsilatMemoOut tahsilatMemoOut;
public HesabaHavaleMemoOut hesabaHavaleMemoOut;
public IsmeHavaleMemoOut ismeHavaleMemoOut;
public KayitliIslemDto(IPCMemo ipcMemo, IsmeHavaleMemoOut ismeHavaleMemoOut) {
this.ipcMemo = ipcMemo;
this.ismeHavaleMemoOut = ismeHavaleMemoOut;
}
public KayitliIslemDto(IPCMemo ipcMemo, HesabaHavaleMemoOut hesabaHavaleMemoOut) {
this.ipcMemo = ipcMemo;
this.hesabaHavaleMemoOut = hesabaHavaleMemoOut;
}
public KayitliIslemDto(IPCMemo ipcMemo, TahsilatMemoOut tahsilatMemoOut) {
this.ipcMemo = ipcMemo;
this.tahsilatMemoOut = tahsilatMemoOut;
}
I had a similar problem with Play Framework. It might highly possible that your JVM locale is Turkish. 'I' in method names are sometimes converted to 'İ' by the JVM that you use.
I solved the problem by setting up JVM system parameters:
play run ExampleProject -Duser.language=en -Duser.country=TR -Duser.variant=TR
I hope it works for you, too.

Run Jettys ServletTester within JUnit test

I'm trying to run Jettys ServletTester in my JUnit test. I created a simple HelloServlet first to test the setup, but I get an IllegalAccessException when I try to request the servlet. Here is what I have so far:
My unit test
#Before
public void setUp() throws Exception {
tester = new ServletTester();
tester.setContextPath("/context");
tester.addServlet(HelloServlet.class, "/hello/*");
tester.start();
}
#After
public void tearDown() throws Exception {
tester.stop();
}
#Test
public void testDefaultServlet() throws Exception {
HttpTester request = new HttpTester();
request.setMethod("GET");
request.setHeader("Host","127.0.0.1");
request.setURI("/context/hello/info");
request.setVersion("HTTP/1.0");
HttpTester response = new HttpTester();
response.parse(tester.getResponses(request.generate()));
assertNull(response.getMethod());
assertEquals(200,response.getStatus());
assertEquals("<h1>Hello Servlet</h1>",response.getContent());
}
My HelloServlet
This servlet is defined in the same file as the unit test, because I want it to be there for the initial setup of jetty. After everything is running, I'll remove it (or maybe keep it, but it will stay within the unit test then).
Update This servlet was defined inside the unit test itself because it was meant only as a configuration test for the jetty server itself. But jetty wasn't able to access it, and after moving it into a public class and a file for itself everything worked like expected. See the comment.
class HelloServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
out.println("Hello, World!");
out.flush();
}
}
My Exception...
2009-10-20 09:36:28.973::INFO: Logging to STDERR via org.mortbay.log.StdErrLog
2009-10-20 09:36:28.989::INFO: jetty-6.1.21
2009-10-20 09:36:29.098::INFO: Started LocalConnector#0.0.0.0:1
2009-10-20 09:36:29.161:/context:WARN: unavailable
java.lang.IllegalAccessException: Class org.mortbay.jetty.servlet.Holder can not access a member of class my.package.HelloServlet with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.Class.newInstance0(Class.java:349)
at java.lang.Class.newInstance(Class.java:308)
at org.mortbay.jetty.servlet.Holder.newInstance(Holder.java:153)
at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:428)
at org.mortbay.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:339)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:390)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:536)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:915)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:539)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:405)
at org.mortbay.jetty.LocalConnector.accept(LocalConnector.java:186)
at org.mortbay.jetty.AbstractConnector$Acceptor.run(AbstractConnector.java:707)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Strange enough, because I got this example almost straight from http://docs.codehaus.org/display/JETTY/ServletTester. Any thoughts or maybe a working example of a embedded jetty servlet container in a junit test?
Your HelloServlet must be implemented as a public class:
public class HelloServlet extends HttpServlet { ... }