Running test for database adapter using main() Method - java

I have a problem in a system that I am working as back-end support for. I need to write a test that calls one of the classes handeling the communications with our database so I can log out what it actually returns.
System setup
Our system is developed in Java and deployed on a weblogic server. It consists of many parts that I will not go into detail on here. But the interesting part is that we have a class acting as an adapter for our database. We call it "CMAdapter" and it is an implementations of IBM Content Manager specific code to handle interaction with our database. In this class we have a methid called fetchAct() that take one object with search parameters as an argument and it returns the result of the search. In this case it returns one act. The code we have is running on a weblogic server, that has an IBM Information Integrator for Content installed so that it can communicate with IBM Content Manager that is installed and running on a different server. The system is deployed on the server using a .ejb and a few .jar files.
The problem
I have recieved a case stating that for some acts the users are not recieving the full act as expected but only parts of it. The system itself displays no errors and the documents are present in the database. So what I am trying to do is write a simple test program that calls this "CMAdapter" with a predetermined set of searchcriteria so that I may log out the return of the search.
My question
How can I make a freestading class with a main() method and run it on the server? I need to make a call to the CMAdapter.fetchAct() method in a way so it runs on the server like any normal query?
My test class
public class TestHamtaAkt
{
public static void main(String[] args) throws BasException
{
Log LOG = Log.getLog(TestHamtaAkt.class);
// Get the CMAdapter
CMAdapter cmadapter = new CMAdapter();
// Create empty instance of our query object
SokVO sokvo = new SokVO();
// Put a value to search for in our query object
AttributVO aktAttribut = new AttributVO();
aktAttribut.setNamn(DLAKonstanter.AKT_KORT_R_KOD);
aktAttribut.setVarde("090084831574");
sokvo.aktAttributLista().add(aktAttribut);
// do the search an recieve the answer
AktVO aktvo = cmadapter.hamtaAkt(sokvo);
// log out the result
LOG.debug("main", "Akten som hämtades: " + aktvo.toString(), null);
}
}

Thanks to all for reading my question. It appears I have found the answer to my own question. It was hiding with a collegue of mine. The answer to my problem was, to be able to access the server deployed code, I need to get the JNDI context from my webserver and from that do a jndi lookup for the class I need.
I still have some problems making the connection but that is problably just my configurations that are off. I now know how I get a simple java class to make a call to a deployed class on a server.
here is the code I am currently using to get the context from the WLS server:
private static InitialContext getWLSContext(String url) throws NamingException
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, WLS_CONTEXT_FACTORY);
//env.put(Context.PROVIDER_URL, "t3://" + host + ":" + port);
env.put(Context.PROVIDER_URL, url);
return new InitialContext(env);
}
This is my code for geting the class I need.
public static EJBObject getRemote(String url, String jndiname, Class homeClass, AppserverTyp typ) throws Exception
{
Object obj = getWLSContext(url).lookup(jndiname);
EJBHome home = (EJBHome) javax.rmi.PortableRemoteObject.narrow(obj, homeClass);
Class homeBase = home.getClass();
Method m = homeBase.getMethod("create", (Class[])null);
EJBObject remote = (EJBObject) m.invoke(home, (Object[])null);
return remote;
}
I hope this helps someone with a similar problem to move forward. Like I said I have still to actually get this code working for me but my this is the answer to my initial question on how to make a call to a deployed method from an external class.

Related

Issues with Displaying information on JSP from servlet

I'm having a spot of bother with a uni assignment where I am trying to display data from a cassandra database on a JSP through a servlet. Basically I am getting a null pointer exception when I try to use get methods on the class storing a user's information for a profile page.
The code below is the part of the JSP that requests the servlet send an object that holds the current user's details. When looking in the debugger it seems it gets the username without any problems but the request for Profile Details returns an empty object whereas it should be populated by information from the database.
<%
String Username=null;
LoggedIn lg = (LoggedIn) session.getAttribute("LoggedIn");
Username = lg.getUsername();
ProfileDetails pd= new ProfileDetails();
pd = (ProfileDetails) request.getAttribute("Profile");
if (pd!=null)
{
String forename= pd.getForename();
String surname=pd.getSurname();
String email=pd.getEmail();
%>
This next segment of code is the method in the servlet which calls the method which returns an object populated with the user's details.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
HttpSession session=request.getSession();
LoggedIn lg = (LoggedIn)session.getAttribute("LoggedIn");
String username=lg.getUsername();
User us = new User();
us.setCluster(cluster);
ProfileDetails pd= new ProfileDetails();
pd = us.GetUserDetails(pd, username);
request.setAttribute("Profile", pd);
RequestDispatcher rd = request.getRequestDispatcher("Profile.jsp");
rd.forward(request, response);
}
I'm fairly sure that the issue I'm having is based in one of these two blocks of code but at the minute I'm stumped. So any help would be appreciated greatly.
If anyone is feeling really enthusiastic about helping here is a link to my project for cloning on GitHub https://github.com/BrodieRoss/Instagrim.git
P.s. sorry if any of my explaining here sounds a bit like nonsense, I'm pretty new to web development.
You have to approach a more MVC version of your web app.
I saw that you have written some getters (voids) but it is better if you write and some setters methods for this class.
Then you have not to forward the servlet to your jsp but redirect it using:
HttpServletResponse.sendRedirect(String Location)
or
HttpServletResponse.sendRedirect("/your/new/location.jsp")
Before redirecting you have to set the attributes you want to this object. For accessing these attributes you use the same variables that your are using on the class. For displaying them in a jsp file you have to use jstl lib. Check more here:
https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm
This tutorial might help you:
https://docs.oracle.com/cd/E15919_01/wlp.1032/e14254/developuserprofiles.htm
User us = new User(); I presume relates a "cluster" of information that is part of the server instance ?, of I see no variable declared or assignment call of any relevant form for "cluster" itself,
though/and too (et tu) I would say also "database" (as you say/wrote) means the "server configuration running instance information and SERVER-environment-variables, globals e.t.c." of the Java J2EE server in this does not have an extra configured set of "connections" to another server program (e.g. MySQL Potgre ...) requiring java drivers and connection pools associated.
Its a wonder it compiled, however, something may be a "static" variable and requires casting to a non static context to be fed to a method or variable.
Can you look through that better now?
The information would be better fed through JSP beans with some state (just a thought)
Of java integration and java compatible drivers for "Cassandra"(Driver interface instance and thread alike MySQL querying and connecting driver systems)...
http://cassandra.apache.org/doc/latest/getting_started/drivers.html?highlight=drivers

Tomcat 7 - Get the application name during runtime without login via java-agent/aspectj

I'm trying to get a list of all deployed applications, and specifically the name of the application mapped to tomcat root.
I want to be able to do it during runtime, using a java agent that collects information on the tomcat server.
I tried using this code sample:
private Iterable<String> collectAllDeployedApps() {
try {
final Set<String> result = new HashSet<>();
final Set<ObjectName> instances = findServer()
.queryNames(new ObjectName("Tomcat:j2eeType=WebModule,*"), null);
for (ObjectName each : instances) {
result.add(substringAfterLast(each.getKeyProperty("name"), "/")); //it will be in format like //localhost/appname
}
return result;
} catch (MalformedObjectNameException e) {
//handle
}
}
taken from a similar question but since I'm not logged into the manager app, I don't have the right permissions, so I get an empty list.
What I actually want - I have a java agent (based on aspectJ), and I'd like during runtime/deployment time etc. to be able to get the list of all deployed apps without actually logging in to the manager myself.
How can I do this? I don't mind instrumenting tomcat's deployment code (which doesn't require any login from my side as I'm already instrumenting the code), but I'm not sure which function to instrument.
Thanks,
Lin
The question consists of 2 parts:
Get a list of all deployed applications - After reviewing Tomcat's API, I found several relevant deployment code parts which can be instrumented:
WarWatcher.java (allows to detect changes), and we can also see the apps from - UserConfig.java which is called on startup (instrumentation can be done on setDirectory name etc.), and of course HostConfig.java that is called on stratup:
protected void org.apache.catalina.startup.HostConfig.deployWARs(java.io.File, java.lang.String[])
protected void org.apache.catalina.startup.HostConfig.deployApps()
protected void org.apache.catalina.startup.HostConfig.deployWAR(org.apache.catalina.util.ContextName, java.io.File)
In addition - you can check the argument for:
protected boolean org.apache.catalina.startup.HostConfig.deploymentExists(java.lang.String)
It includes the war/folder name (which usually means the application name+-).
Get the root application name - This can be done by using ServletContext.getRealPath() - It returns the folder name, from which the war name can be extracted (and can be used, in my case at least as the app name).

Java InvocationTargetException

I have used EMC Documentum Foundation Classes to perform some actions in documentum repository. The code was working fine. I exported the project as a runnable JAR and then tried to run it. However I got following error and I am not able to understand it.
And here is the code for DocMovementHandler.getSession()
Actually this is no new code but regular code for obtaining documentum session
public IDfSession getSession(String userName, String password)
{
DfClientX clientx = null;
IDfClient client = null;
IDfSession session = null;
try {
// create a client object using a factory method in DfClientX
clientx = new DfClientX();
client = clientx.getLocalClient(); //takes time
// call a factory method to create the session manager
IDfSessionManager sessionMgr = client.newSessionManager();
// create an IDfLoginInfo object and set its fields
IDfLoginInfo loginInfo = clientx.getLoginInfo();
loginInfo.setUser(userName);
loginInfo.setPassword(password);
// set single identity for all docbases
sessionMgr.setIdentity("xyz_repo", loginInfo);
session = sessionMgr.getSession("xyz_repo"); //takes time
//sessionMgr.beginTransaction();
System.out.println("Session obtaied.");
}
catch (DfServiceException dse)
{
DfLogger.debug(this, "Error while beginning transaction. ", null, dse);
dse.printStackTrace();
}
catch (Exception e)
{
DfLogger.debug(this, "Error while creating a new session. ", null, e);
e.printStackTrace();
}
return session;
}
And that line 38 is client = clientx.getLocalClient();
InvocationTargetException is a wrapper. It says, "an exception occurred behind this reflection call", and you use getCause() to get at the inner exception.
The stack trace contains the inner exception. It's an ExceptionInInitializerError. That's another wrapper. It says, "whatever you did caused a new class to be loaded, and that class's static initializer threw an exception".
The final exception in this chain is the NullPointerException. That's the one you need to solve. Which means you need to debug this com.documentum thing. As the comments pointed out, that's not going to be easy.
Here is the most likely problem:
The static initializer in one of the classes whose names you have struck is adding an entry with either a null key or a null value to a Hashtable, which does not allow null keys or values.
It is using the Hashtable as a place to store a bunch of persistent properties and all that, and my guess is that the value for one of the entries was the null (which is a perfectly reasonable way to indicate that some feature is unavailable or something like that).
The now deprecated Hashtable needs to be replaced with the more modern HashMap.
If it is a library, that you can't just modify, you should replace the whole library with an updated version.
Here are some clues may be helpful.
The NullPointerException is thrown by Hashtable#put, and this is normally because either the key or the value is null.
Hashtable#put is called by PreferenceManager.readPersistenceProperties, so most likely it's because something is missing in a properties file so the value is null.
This NPE caused the DfClient class could not be loaded.
DfPreferences is the class loading the DFC configuration file dfc.properties. There must be something wrong with it.
Ohkay I did not pin pointed the root cause, but found the solution that will definitely work everytime.
EMC provides a flavor of Eclipse called Documentum Composer to work with Documentum Projects. Since Eclipse variation we can create other types of projects like normal Java project, dynamic web project, web services in this. So I recreated my project in Documetnum Composer and exported it as JAR and whoaaaa it worked.
I tried this many times and this worked all time.
Some points to note:
You have to replace dfc.properties file in Composer installation folder with one in Content Server
The Export to JAR wizard in Composer is a bit different than one in Eclipse
This is usually caused by dfc.properties being incorrect.
Preferences are stored on the global registry repository and the connection details should be specified in dfc.properties. If not, this (or a similar error can occur).
Also, always try to clear cache and use the correct version of the dfc jar's (v6.7 content server requires 6.7 jars, etc...).

Is it possible to connect to java from a firefox extension in the way described below

My objective is to:
Use Firefox to take a series of screendump images and save on the local Filesystem with a reference.
also via my custom extension send a reference to a java program that performs the ftp to a remote server.
This is pretty intimidating
https://developer.mozilla.org/en/JavaScript/Guide/LiveConnect_Overview
Is it possible?
Can you see any potential problems or things Id need to consider?
(I'm aware of file system problems but its for local use only)
Are there any tutorials / references that might be handy?
Ive tried linking to java but hit problems using my own classes Im getting a class not found exception when I try
JS:
var myObj = new Packages.message();
Java file:
public class Message {
private String message;
public Message()
{
this.message = "Hello";
}
public String getMessage()
{
return this.message;
}
}
not using a package java side.
Just trying to run a quick test to see if it is viable and under time pressure from those above so just wanted to see if it was a worthwhile time investment or a dead end
You might consider this Java tutorial instead: http://www.oracle.com/technetwork/java/javase/documentation/liveconnect-docs-349790.html.
What Java version are you using? Is your message class an object inside Java applet?

How does this Java application change when deployed on a server?

I want to write a Java application that talks to a MySQL database on a server and changes the value of some variable v based on what it finds in the database.
If I were to simply do this on my computer I would have something like:
//import database stuff
public class Test{
int v;
public Test()
{
v=0;
}
public void main (String[]args){
Test t = new Test();
t.setVariable();
}
public void setVariable(){
// connect to database etc etc
if(something in MySQL database is true){
v= 10;
}
else{
v=30;
}
}
}
Now lets say I wanted to deploy this on a web server and expose the variable v to multiple users on the web who want to access a home.php file that was something like
$v = //call java program to return v
echo $v;
1) what would change in my java code or how I think of the whole problem? do i need a servlet? or tomcat? or do i just need to install the jdk?
2) how about the call from the home.php file how is it made?
what is a good resource I can use to learn about these issues?
Thanks alot!
i would code this using ajax language. I would write a servlet which would be called from the web page (javascript). In the servlet i would write a DAO layer which will talk to the MySQL database. In the servlet, the business logic (i.e. checking the value) would be written & appropriate value would be returned back to the front end (web page).

Categories