Apache Tomcat Cataline file changes not reflecting! - java

I am using apache-tomcat-6.0.18 on windows xp prefossional SP3.
My requirement is to show additional information ( like Organization Name) in the Tomcat Manager => Server Status => in between the JVM and http- Header. I have modified the file "org.apache.catalina.manager.StatusTransformer::writeConnectorState<method name>" from catalina.jar source and added simple text to it. Sample code is
public static void writeConnectorState(PrintWriter writer, ObjectName tpName, String name, MBeanServer mBeanServer, Vector globalRequestProcessors, Vector requestProcessors, int mode)throws Exception{
if (mode == 0) {
// START - Added New Code to display org name
writer.print("<h1>");
writer.print("XYZ Organization.");
writer.print("</h1>");
// END - Added New Code to display org name
writer.print("<h1>");
writer.print(name);
writer.print("</h1>");
writer.print("<p>");
writer.print(" Max threads: ");
writer.print(mBeanServer.getAttribute(tpName, "maxThreads"));
writer.print(" Current thread count: ");
writer.print(mBeanServer.getAttribute(tpName, "currentThreadCount"));
writer.print(" Current thread busy: ");
writer.print(mBeanServer.getAttribute(tpName, "currentThreadsBusy"));
...........
...........
}else{
.........
}// end if-else }// method end
Again created catalina.jar with modified code. and replaced with the existing jar from catalina_home/bin. Restarted the tomcat but nothing coming out of it.
Even if i remove catalina.jar from catalina_home/bin and starts the tomcat, its working!!!!
I tried even after restarting the system but my changes are not reflecting.
Please help me out for the following queries
Am i modifying the wrong file?
How tomcat is running without catalina.jar?
How to reflect the changes? i.e. Any other way?

Not 100% sure on this, but I think you should place the modified catalina.jar in catalina_home/lib, as I believe that's where the web-applications load their shared libraries (Tomcat Manager is just another app under catalina_home/webapps/).
Edit: I checked one of our servers, there's no catalina.jar under catalina_home/bin, only under catalina_home/lib.

Related

Using rsync4j library, a Java implementation of Linux rsync tool, how to sync data from a remote directory with a local directory

I need the functionality like that of the rsync linux tool in my Java program. For that, I chose the rsync4j library.
Using their documentation, I wrote the following program:
import com.github.fracpete.processoutput4j.output.ConsoleOutputProcessOutput;
import com.github.fracpete.rsync4j.RSync;
public class MainClass {
public static void main(String [] args) {
System.out.println("Started");//check
RSync rsync = new RSync()
.source("/home/arth/DataSourceFolder/a.txt")
.destination("/home/arth/DataDestinationFolder/")
.recursive(true);
// or if you prefer using commandline options:
// rsync.setOptions(new String[]{"-r", "/one/place/", "/other/place/"});
CollectingProcessOutput output = null;
try {
System.out.println("Inside try");
output = rsync.execute();
System.out.println("End of try");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(output.getStdOut());
System.out.println("Exit code: " + output.getExitCode());
if (output.getExitCode() > 0)
System.err.println(output.getStdErr());
}
}
In the snippet, in out local machine, a file a.txt is copied from one location to another. This works perfectly. The file is successfully copied when I run it and here is the output:
Started
Inside try
End of try
Exit code: 0
But my need is to sync a local directory with a directory lying at a remote host/machine. When I tried to do it using a simple rsync command from a terminal using the following command
rsync remoteUserName#23.24.25.244:/home/beth/remoteFolder/a.png /home/arth/DataSourceFolder
it works like a charm. a.png IS copied to local machine at path specified, although a password of remote machine is asked first.
But the problem when I use the above Java program to do the same operation, by replacing line # 11 and 12 by:
.source("remoteUserName#23.24.25.244:/home/beth/remoteFolder/a.png")
.destination("/home/arth/DataDestinationFolder/")
the program gets stuck after printing Started in the console. Neither an exception is thrown nor does the program proceed.
The question is that how do I fix this problem?
(old post, I know, but here it goes...) The rsync4j library does not allow interaction. In your case, the underlying rysnc binary prompts for a password in the process that the Java library created, but never receives one.
Starting with release 3.2.3-7, you can supply an instance of the sshpass wrapper to feed in the password (see this comment for an example).

java rmi simple project classNotFoundException binding registry

Ok, I'm sure this should be pretty easy, but I'm fairly new to Java (I'm more a .NET boy :P) and after following every single recommendation I found here to no success, I think it's time to step back and ask.
I'm trying to start a simple rmi project with a client, a server and a common project where common interfaces are defined. I've just implemented my server code, and when I try to run it to check if everything is fine, I get struck on a java.lang.ClassNotFoundException.
After following several answers on similar issues, I'm fair sure that my problem comes from rmiregistry running on a different location than my project.
I use following code to set registry codebase:
public class Utils {
public static final String CODEBASE = "java.rmi.server.codebase";
public static void setCodeBase(Class<?> c) {
String ruta = c.getProtectionDomain().getCodeSource().getLocation().toString();
String path = System.getProperty(CODEBASE);
if (path != null && !path.isEmpty()) {
ruta = path + " " + ruta;
}
System.setProperty(CODEBASE, ruta);
}
}
Then, I try to start my server code with this main class:
public class MainRegulador {
public static void main(String[] args) throws AccessException, RemoteException, NotBoundException {
Utils.setCodeBase(IRegulador.class);
Registry registro = null;
Remote proxy = null;
try {
Regulador myReg = new Regulador();
proxy = UnicastRemoteObject.exportObject(myReg, 36510);
registro = LocateRegistry.getRegistry();
registro.rebind("Distribuidor", proxy); //this is the line where exception is thrown
System.out.println("El Regulador está corriendo. Pulse ENTER para finalizar el proceso.");
System.in.read();
} catch(Exception ex) {
System.out.println("No se ha logrado inicializar el Registrador");
System.out.println(ex.getMessage());
} finally {
if (registro != null && proxy != null) {
registro.unbind("Distribuidor");
UnicastRemoteObject.unexportObject(proxy, true);
}
}
}
}
But when I run it, always get a java.lang.ClassNotFoundException at IRegulador interface.
Now the fun part:
I've printed to console java.rmi.server.codebase value, and it's pointing to bin folder of project where IRegulador interface is defined. (file:/F:/Practicas%20y%20dem%c3%a1s/Sistemas%20Distribuidos/common/bin/)
Obviously, that project is also set in the classpath of server project
(Regulador)
Workspace and rmiregistry are on different disks
Despite all, it doesn't seem a global classpath problem, as Utils class is on the same project as IRegulador interface, and it runs before the exception is thrown (as java.rmi.server.codebase is correctly set).
I've tried to set the classpath of rmiregistry before calling it (although it is directly discouraged on some answers), but nothing changed.
I've also tried to start rmiregistry.exe from Regulador project bin folder, but also seemed to don't change anything.
Coming from a .NET background, I've always found these classpath issues confusing, and this one is starting to consume much more time than I suspect it deserves. I'm in desperate need of help.
UPDATE: I'm starting to think that the problem is within the url it's passed to the codebase from IRegulador.class. If I paste it into windows explorer, the SO is unable to locate it, so I supose that it's being built with some structure problem that prevents the registry to reach the route:
file:/F:/Practicas%20y%20dem%c3%a1s/Sistemas%20Distribuidos/common/bin/
UPDATE2: I thought path route could be too complex, so I decided to simplify it and strip it from any non-straight character. Now codebase value is
file:/F:/Practicas/SD/common/bin/
However the problem persists, I don't know why rmiregistry is unable to reach that folder.
Then I decided to move the whole project to the same disk where rmiregistry is executed, and see if it changes anything. But nothing changed, same problem.
Ok, finally I got it working...
I've just copied rmiregistry.exe into the common/bin folder and launch it directly from there (previously just had called from there).
This seems to fix the problem with the routes (actually it makes the route available to the registry as it's on the same folder, probably all my codebase writting code is superflous now).

Infinite scan for fonts in Apache FOP on CentOS

I use Apache Batik to convert SVG into PDF in one of the projects. The project is Spring application running in Tomcat 7. Everything works OK on development machine which runs under Ubuntu with Tomcat being started using $CATALINA_HOME/bin/startup.sh. But when I try to run the app on production server with CentOS 6 and Tomcat started using service tomcat7 start command the app falls into infinite loop on convertation. I've tried to debug the problem and found this piece of code:
/**
* Creates the {#link FontInfo} instance for the given configuration.
* #param cfg the configuration
* #param useComplexScriptFeatures true if complex script features enabled
* #return the font collection
* #throws FOPException if an error occurs while setting up the fonts
*/
public static FontInfo createFontInfo(Configuration cfg, boolean useComplexScriptFeatures)
throws FOPException {
FontInfo fontInfo = new FontInfo();
final boolean strict = false;
if (cfg != null) {
URI thisUri = new File(".").getAbsoluteFile().toURI();
InternalResourceResolver resourceResolver
= ResourceResolverFactory.createDefaultInternalResourceResolver(thisUri);
//TODO The following could be optimized by retaining the FontManager somewhere
FontManager fontManager = new FontManager(resourceResolver, FontDetectorFactory.createDefault(),
FontCacheManagerFactory.createDefault());
//TODO Make use of fontBaseURL, font substitution and referencing configuration
//Requires a change to the expected configuration layout
DefaultFontConfig.DefaultFontConfigParser parser
= new DefaultFontConfig.DefaultFontConfigParser();
DefaultFontConfig fontInfoConfig = parser.parse(cfg, strict);
DefaultFontConfigurator fontInfoConfigurator
= new DefaultFontConfigurator(fontManager, null, strict);
List<EmbedFontInfo> fontInfoList = fontInfoConfigurator.configure(fontInfoConfig);
fontManager.saveCache();
FontSetup.setup(fontInfo, fontInfoList, resourceResolver, useComplexScriptFeatures);
} else {
FontSetup.setup(fontInfo, useComplexScriptFeatures);
}
return fontInfo;
}
in PDFDocumentGraphics2DConfigurator class. When I'm running the app on developer machine the line URI thisUri = new File(".").getAbsoluteFile().toURI(); results with thisUri being assigned with ~/tomcat/bin/. folder. When the app is running on production machine it is assigned with /. value. I think that this is the main problem because the value of thisUri is the folder in which FOP starts fonts search and on the production machine this is the root of file system and recursive search on the whole FS structure is very slow. I tried to add fop.xconf file to the WEB-INF directory with fonts configuration but it didn't affected the behavior of FOP. And I can't start Tomcat on production server the same way as I start on the dev machine.
Has anyone ideas on how to configure the base directory for font scan of FOR? Or am I doing something wrong?
I've found the workaround for the problem. I'm not sure if its wright or wrong to do stuff like that but it works. The workaround is based on the fact that File.getAbsolutFile() by default returns the directory resolved against the directory defined by user.dir option. So I need some way to pass this option on Tomcat service start. The only way I've found to do this is to add -Duser.dir=/%CATALINA_HOME/ to the CATALINA_OPTS variable defined in %CATALINA_HOME/bin/setenv.sh file. After that the font scan process took normal amount of time and my app started to work fine.

Detect Play 2.2.x mode prior to start of Application using Java

I want to point my play application to a particular application config file based on the environment it is running in. There are three and they correspond to the standard Play states:
application.dev.conf
application.test.conf
application.prod.conf
A co-worker shared a method for doing this which requires setting an OS environment variable.
I'd like to eliminate the need to set an OS variable.
My preference is the use whatever Play uses at startup to know what mode it is in.
For example, if you execute play run from the command line, part of the output is "[info] play - Application started (Dev)"
I want to use this information in my Global.java where I override onLoadConfig like so:
public Configuration onLoadConfig(Configuration baseConfiguration, File f, ClassLoader loader) {
String playEnv=<some static method to get mode>;
Config additionalConfig = ConfigFactory.parseFile(new File(f,"conf/application."+playEnv+".conf"));
Config baseConfig = baseConfiguration.getWrappedConfiguration().underlying();
return new Configuration(baseConfig.withFallback(additionalConfig));
}
Everything that I find is how to do this after the application has been started i.e. using isDev(), isTest(), isProd().
Is there static method that provides the mode while I am overriding onLoadConfig in Global.java?
I think play run is dev, play start is prod.
EDIT: If you're looking to see what the current mode is, it's passed in through play.api.Play.current:
Play.current.mode match {
case Play.Mode.Dev => "dev"
case Play.Mode.Prod => "prod"
}
The issue appeared to be addressed in the latest Play (3.0.0). There is another onLoadConfig method added to Global witch has a mode: {Dev,Prod,Test} parameter.
public Configuration onLoadConfig(Configuration config, File path, ClassLoader classloader, Mode mode) {
return onLoadConfig(config, path, classloader); // default implementation
}
Play allows to specifying alternative configuration file with command line so no need for setting OS variables.
You can of course create some bash script / bat file to avoid writing it every time

ClassCastException while executing "HelloWorld" applet code

I am trying to run simple "Hello world" java applet program. But on execution applet does not appear in browser instead ClassNotFoundException occurs.
This is how I am accessing it from browser:-
<applet width="500" height="50" codebase="http://localhost:13383/tuexample/"
code="dk.certificate.demo.DemoApplet.class" >...applet..</applet>
JavaCode:-
import java.applet.Applet;
import java.awt.Graphics;
public class DemoApplet extends Applet
{
private static final long serialVersionUID = 1L;
#Override
public void paint(Graphics g)
{
g.drawString("Welcome in Java Applet.",40,20);
}
}
Exception Log:-
Java Plug-in 10.21.2.11
Using JRE version 1.7.0_21-b11 Java HotSpot(TM) Client VM
User home directory = C:\Users\rahil_khan
----------------------------------------------------
c: clear console window
f: finalize objects on finalization queue
g: garbage collect
h: display this help message
l: dump classloader list
m: print memory usage
o: trigger logging
q: hide console
r: reload policy configuration
s: dump system and deployment properties
t: dump thread list
v: dump thread stack
x: clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------
28-May-2013 14:20:51 <INFO> thread applet-dk.pbs.applet.bootstrap.BootApplet-1 - stop
28-May-2013 14:20:51 <INFO> thread applet-dk.pbs.applet.bootstrap.BootApplet-1 -
destroy
Let me finally answer this Question:
You are getting ClassNotFoundException because Applet class, it seems, can not be found in the configuration you have provided.
Your code does this: It is trying to find DemoApplet.class inside the package dk.certificate.demo inside the localhost:13383/tuexample/
So, if we consider localhost:13383/tuexample/ to be your root webapp directory called xyz then your possible file structure should be like this:
XYZ/dk/certificate/demo/DemoApplet.class which clearly does not seem to be the case.
Also make sure you have package dk.certificate.demo inside your class file which I don't see at the moment.
Now, it should be easy to fix your code from what I have explained.
In tag:
code="dk/certificate/demo/DemoApplet.class"
package dk.certificate.demo;?
dk/certificate/demo/DemoApplet.class?
By the way JApplet, swing i.o. AWT, is the better solution.
Maybe in your case the code base resides in (should be) WEB-INF/classes, which normally is notokay, as WEB-INF files should not be accessible by URL.
In fact normally a .jar is created in a separate project and deposited in the Web Contents directory.
#RaviTrivedi and #JoopEggen thanks for your support I was able to fix the problem.
Two solutions:-
DemoApplet.jar:-
I created jar(DemoApplet.jar) of my applet code(DemoApplet.java) and
placed it in AppletDemo\WebContent\lib folder.
I moved classes folder
from AppletDemo\WebContent\WEB-INF\classes
to AppletDemo\WebContent\classes
And from login.jsp I made call to applet in following way:-
<!-- DemoApplet.jar -->
<applet
width="500"
height="50"
codebase="http://localhost:8080/AppletDemo"
archive="lib/demoApplet.jar"
code=dk.certificate.demo.DemoApplet.class >...applet..</applet>
<!-- classes -->
<applet
width="500"
height="50"
codebase="http://localhost:8080/AppletDemo/classes"
code=dk.certificate.demo.DemoApplet.class >...class...applet..</applet>
It worked both ways.
Thanks a lot. :D

Categories