Create InitialContext from context.xml in plain java application - java

As the question implies, I have a simple java app (aka a "simple main") that needs to initialize a hibernate connection whose information is in context.xml.
After lots of searching and with some hacks from here I concluded to this:
public static void main(String[] args) {
//JNDI provider is needed and RMI registry has one...
try {
java.rmi.registry.LocateRegistry.createRegistry(1099);
System.out.println("RMI registry ready.");
} catch (Exception e) {
System.out.println("Exception starting RMI registry:");
e.printStackTrace();
}
new InitialContext().readContextXml("context.xml");//of course there is nothing like that. But is there an equivalent?
String result = thatWillConnectWithHibernate();
System.out.println(result);
}
private static String thatWillConnectWithHibernate() {
//does stuff
}
So is there a simple way to create an InitialContext from an xml file? I'm not interested in parsing the file manually, I can do that my self.

Related

Does MariaDB disconnect automatically or Should i have to disconnect Manually?

I got to use MariaDB for my University Project.
it's my first time doing it, so I dont't know well how to use and code JDBC Driver and mariaDB.
Now I'm implementing the code in many places while looking at examples.
As I see, All the examples seems to creating Statement and making connection by using "DriverManager.getConnection"
Now I have a question.
I'm going to create a DBmanager Class that can connect, create tables, execute queries, and execute the code that updates data on tables in a single line.
I thought all the examples would run alone in one method and came from different places, so I could only try a new connection and create a code that would not close. But I have a gut feeling that this will be a problem.
Is there any way I can leave a connection connected at a single connection to send a command, and disconnect it to DB.disconnect()? And I'd appreciate it if you could tell me whether what I'm thinking is right or wrong.
The code below is the code I've written so far.
I am sorry if you find my English difficult to read or understand. I am Using translator, So, my English could not be display as I intended.
import java.sql.*;
import java.util.Properties;
public class DBManager {
/*********INNITIAL DEFINES********/
final static private String HOST="sumewhere.azure.com";//Azure DB URL
final static private String USER="id#somewhere";//root ID
final static private String PW="*****";//Server Password
final static private String DRIVER="org.mariadb.jdbc.Driver";//DB Driver info
private String database="user";
/***************API***************/
void setDB(String databaseinfo){
database=databaseinfo;
}
private void checkDriver() throws Exception
{
try
{
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
}
public void checkOnline(String databaseinfo) throws Exception
{
setDB(databaseinfo);
this.checkDriver();
Connection connection = null;
try
{
String url = String.format("jdbc:mariadb://%s/%s", HOST, database);
// Set connection properties.
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PW);
properties.setProperty("useSSL", "true");
properties.setProperty("verifyServerCertificate", "true");
properties.setProperty("requireSSL", "false");
// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
void makeCcnnection() throws ClassNotFoundException
{
// Check DB driver Exists
try
{
Class.forName("org.mariadb.jdbc");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
Connection connection = null;
}
public void updateTable(){}
public static void main(String[] args) throws Exception {
DBManager DB = new DBManager();
DB.checkOnline("DB");
}
}
For a studying project it's okay to give a connection from your DB Manager to client code and close it there automatically using try-with-resources construction.
Maybe you will find it possible to check Connection Pool tools and apply it further in your project or use as example (like HikariCP, here is a good introduction).
Read about Java try with resources. I think that this link could be usefull for your problem.
JDBC with try with resources

Not able to enable JMX for Grizzly

I tried enabling the JMX for grizzly server. I added the gmbal-api-only-3.1.0 jar file to the project and wrote the following simple code :
public class Main {
public static void main(String[] args) {
HttpServer gws = new HttpServer();
NetworkListener listener1 = new NetworkListener("listener1", "localhost", 19080);
gws.addListener(listener1);
try {
gws.start();
gws.getServerConfiguration().setJmxEnabled(true);
System.in.read();
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} finally {
try {
gws.stop();
} catch (Exception ignored) {}
}
}
}
I ran this program and opened it up in the JConsole, but the JConsole do not show any MBean for the grizzly server in spite of using setJMXEnabled(true).
Please tell me what could be missing here or what is wrong with the code? Else, please suggest how to enable JMX for grizzly and how to verify it. I tried using the "Grizzly HTTP JMX Server Monitoring" approach given on the link : https://grizzly.java.net/monitoring.html

JDBC not connecting

While the build paths are not correct I obtain “com.microsoft.sqlserver.jdbc.SQLServerDriver” from the stack trace. As they are built correctly, I obtain my printed statement “Successfully connected”. The JDBC is living within the getter/setters of the webservice as a method.
When I place the JDBC content in its own file with no builds and run as a java application I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
When I place the JDBC content in its own file with builds and run as a java application I receive: “Successfully connected”
When the method is called from a test file as a java application I receive: “Successfully connected”
Ex:
public static void main(String[] args) {
insert.main(args);
When the method is run as a java application on PO I receive: “Successfully connected”
When I place the method to be called under a setter (which will be invoked by the client, which will cause the jdbc to be invoked) I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
Would you happen to have any tips for me? I’m clueless why it will work under being invoked as an application but not via client?
public class insert{
public static void main(String[] args) {
Connection con = null;
Statement st = null;
final String DB_URL = "jdbc:jtds:sqlserver://00.00.00.00:0000/DB";
// Database credentials
final String USER = "usrname";
final String PASS = "pw";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
st = con.createStatement();
System.out.println("successfully connected!");
} catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
finally {
try {
con.close();
} catch (Exception e) { /* ignored */ }
try {
st.close();
} catch (Exception e) {
/* ignored */
}
}
}
}
Any tips at this point would be greatly appreciated.
The problem is that your jar misses the necessary libraries that provides com.microsoft.sqlserver.jdbc.SQLServerDriver class and others to communicate with your SQL server. You have to make sure the library is loaded and available when is being executed from tomcat. Just copy your library and drop it inside %TOMCAT_INSTALL%/lib folder, where %TOMCAT_INSTALL% is the folder where your tomcat is installed, so the library will be available for every project (war, jar, etc) that runs in your tomcat installation.

How to create a "FTPS" Mock Server to unit test File Transfer in Java

I have a CreateFTPConnection class which create a FTPS connection. Using this connection, files are transferred. Here is the code of TransferFile class
public class TransferFile
{
private CreateFTPConnection ftpConnection;
private FTPSClient client;
public TransferFile(CreateFTPConnection ftpConnection) {
this.ftpConnection = ftpConnection;
this.client = ftpConnection.getClient();
}
public void transfer(Message<?> msg)
{
InputStream inputStream = null;
try
{
if(!client.isConnected()){
ftpConnection.init();
client = ftpConnection.getClient();
}
File file = (File) msg.getPayload();
inputStream = new FileInputStream(file);
client.storeFile(file.getName(), inputStream);
client.sendNoOp();
} catch (Exception e) {
try
{
client.disconnect();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
finally
{
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have to write jUnit Testcase for this class. For this, I have to create a FTPS Mock Server connection and have to use that connection to test the File Transfer. So can anyone plz give me any idea of how to make FTPS Mock Server and do the test case. I googled on this, but what I get is on FTP or SFTP, not FTPS. Please help me.
You might find this useful MockFTPServer
The issue is that these mock servers don't implement the TLS portion from what I can see. You may need to do a little work to allow connections via TLS.
You should be able to search around and find some articles here on SO about dealing with certificates, (or in some cases, bypassing them) for the sake of your testing.
Here's another Article that goes through the steps of creating a basic FTP server Test.
Short of a full blown FTP server (Apache http w/ mod_ftp add on), there doesn't seem to be anything useful to do this.

How to handle java.rmi.UnknownHostException

I'm working with Eclipse and the code below is the code that I use for RMI initialization.
public void init(String serviceName) throws RemoteException {
try {
String host = InetAddress.getLocalHost().getHostName();
String url = "rmi://"+ host + serviceName;
Naming.rebind(url,this);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
I'm getting an UnknownHostException.
Since I'm new to this issue, the question may be simple, but I could not handle it.
Thanks in advance.
UnknownHostException means it can't find that host at the network level. There's no handling this type of exception because it means something is broken. I'd print out the URL sent to RMI. It should look something like this:
//localhost/ServiceImTryingToAccess
If you didn't put a leading "/" on your service it might be:
//localhostServiceImTryingToAccess
And that certainly would create an UnknownHostException. You really don't need to use InetAddress.getLocalHost() as you could just simply do:
String url = "//localhost" + serviceName;
Also notice I dropped the rmi:// scheme portion of the URL. It's in the docs that's not needed.
http://docs.oracle.com/javase/1.4.2/docs/api/java/rmi/Naming.html

Categories