Run a java webservice on a server - java

I have a Java Webservice code . Currently I am running it on a localhost. What changes should be made when I run this on another server(with static IP).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
public class RetailerWS {
public String customerData(){
String customerInfo = "";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","chathura");
//Find customer information where the customer ID is maximum
PreparedStatement statement = con.prepareStatement("SELECT * FROM customers WHERE C_ID = (SELECT MAX(C_ID) FROM customers)");
ResultSet result = statement.executeQuery();
while(result.next()){
customerInfo = customerInfo + result.getString("name") + "&" + result.getString("C_ID") + "&"+result.getString("address") + "&"+result.getString("email");
//Here "&"s are added to the return string. This is help to split the string in Android application
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return customerInfo;
}
}

You need not to make any change if database is also hosted on the same server. If DB is on other server then change this line :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","chathura");
to have the ip/address or hostname of your DB server.
Your web service clients need to use the address of you new server where you are hosting the web service, to call its methods.

Related

Cassandra jdbc connection with Authentication

I am trying to connect to the Cassandra using cdata jdbc connector. However, I cannot find how to provide username and password in connection url. Here are my java code.
package com.dremio.exec.store.jdbc.conf;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestConnection {
public static void main(String[] args) throws Exception {
Connection con = null;
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra://localhost:9160");
String query = "SELECT * FROM emp";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("emp_id"));
System.out.println(result.getString("emp_name"));
System.out.println(result.getString("emp_city"));
}
con.close();
}
}
Currently, I am providing url as without Authentication. How can i provide username and password there.
CData's (poor) documentation lists User and Password as available properties to add to a JDBC connection string. You can add these with your username and password to authenticate:
con = DriverManager.getConnection(
"jdbc:cassandra://localhost:9160;User=ayush;Password=yourpwd");
You could also add them as properties, as detailed in their Connecting From Code examples:
Properties prop = new Properties();
prop.setProperty("Port","9042");
prop.setProperty("Server","127.0.0.1");
prop.setProperty("User","ayush");
prop.setProperty("Password","yourpwd");
Connection conn = DriverManager.getConnection("jdbc:cassandra:",prop);
Also, unless you're using an old Cassandra cluster or 3.x cluster with Thrift enabled, 9160 isn't going to work. In fact, the Thrift project hasn't had a pull request in a few years now, so I would suggest moving away from it and using the native binary protocol on 9042.

Java JDBC: Cannot insert Data into Database

I'm coding for hours to insert data into my SQL database, but nothing happens.
I even can't debug Java, because I don't get any output of my console.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author xxx
*/
public class MyServlet extends HttpServlet {
private static final String URL = "jdbc:mysql://localhost:3306/userdata";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final DecimalFormat DF2 = new DecimalFormat("#.##");
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
try {
String myDriver = "com.mysql.jdbc.Driver";
try {
Class.forName(myDriver);
// opening database connection to MySQL server
con = DriverManager.getConnection(URL, USER, PASSWORD);
// getting Statement object to execute query
// the mysql insert statement
String query = "INSERT INTO customers (customer, currency, amount) values ('Name', 'Currency', 100);";
stmt.executeUpdate(query);
// execute the preparedstatement
// executing SELECT query
rs = stmt.executeQuery(query);
con.close();
stmt.close();
rs.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
}
}
What did I wrong, that nothing happens? Even if I use this code for Java-Classes (not Servlets), I only receive an compile error, but without message.
I'm using the IDE Netbeans and mysql DB is the MySQL Workbench. The Java Class is using the main method.
Update:
I've tested following Code with IntelliJ:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/userdata";
String user = "root";
String password = "root";
String query = "Insert into customers (customer, currency, amount) values('Michael Ballack', 'Euro', 500)";
try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement(query)) {
pst.executeUpdate();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
private static class JdbcMySQLVersion {
public JdbcMySQLVersion() {
}
}
I can insert data into the MySQL database.
In Netbeans this code won't work, although I've implemented the MySQLConnector. I don't know why, but Netbeans seems hard to handle.
In the servlet code, I don't see you ever write anything to out. So nothing is being sent back to the browser, even if it compiled. You could write your SQL exception to the out writer you created. To be more precise add this in your exception: out.println(sqlEx.printStackTrace()); That should at least show what exception you are getting back to the browser.
What is the compile error you get outside of a servlet?
This maybe obvious, but to get JDBC stuff to work on your server, you need to have the MySQL server installed, started and configured. The table referenced has to be defined, etc. You could check this outside of the Java servlet environment with the tools provided with MySQL.
your code can not compile, you miss catch exception for second 'try'.
Where do you use this class to run, if you run a java class, this class must contain main() function?
you should use some IDEs like eclipse or IntelliJ to code, it help you detect the error easier.
I found the solution. If you are using Netbeans with the Glassfish-Server and you want your servlet to save data into the database, you have to make sure that Netbeans has installed the Driver of your Database Connector (e.g. MySQL Connector). But you also have to configurate your server (e.g. Glassfish) which will support the DB Connector drivers.
In my case my Server didn't load the DB Connector Driver so the JDBC Code couldn't be executed.
Here's a useful link to configurate the Glassfish Server: https://dzone.com/articles/nb-class-glassfish-mysql-jdbc

NonWritableChannelException when trying to update an Access database

Using UCanAccess for the first time for a project and I am having a lot of trouble inserting a row into one of my database tables (in Microsoft Access).
My code makes sense but once I execute I end up getting the same error every time, even though NetBeans is able to connect to my database.
package Vegan;
import java.sql.Connection;
import java.sql.DriverManager;
public class connectionString {
static Connection connection = null;
public static Connection getConnection()
{
try
{
connection = DriverManager.getConnection("jdbc:ucanaccess://C://MyDatabase1.accdb");
System.out.println("---connection succesful---");
}
catch (Exception ex)
{
System.out.println("Connection Unsuccesful");
}
return connection;
}
package Vegan;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DB {
private static ResultSet rs = null;
private static PreparedStatement ps = null;
private static Connection connection = null;
public DB() {
connection = connectionString.getConnection();
}
public void AddTest() {
try {
String sql = "INSERT INTO CategoryTbl(CategoryName) VALUES (?)";
ps = connection.prepareStatement(sql);
ps.setString(1, "Flours");
ps.executeUpdate();
System.out.println("Inserted");
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage().toString());
}
}
After that, when I execute the the AddTest() method, I get this system output:
run:
---connection succesful---
java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:724)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:297)
UCAExc:::3.0.6 null
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:234)
at com.healthmarketscience.jackcess.impl.TableImpl.writeDataPage(TableImpl.java:1375)
at com.healthmarketscience.jackcess.impl.TableImpl.addRows(TableImpl.java:1624)
at com.healthmarketscience.jackcess.impl.TableImpl.addRow(TableImpl.java:1462)
at net.ucanaccess.converters.UcanaccessTable.addRow(UcanaccessTable.java:44)
at net.ucanaccess.commands.InsertCommand.insertRow(InsertCommand.java:101)
at net.ucanaccess.commands.InsertCommand.persist(InsertCommand.java:148)
at net.ucanaccess.jdbc.UcanaccessConnection.flushIO(UcanaccessConnection.java:315)
at net.ucanaccess.jdbc.UcanaccessConnection.commit(UcanaccessConnection.java:205)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:161)
at net.ucanaccess.jdbc.ExecuteUpdate.execute(ExecuteUpdate.java:50)
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.executeUpdate(UcanaccessPreparedStatement.java:253)
at Vegan.DB.AddTest(DB.java:91)
at Vegan.TestDB.main(TestDB.java:17)
BUILD SUCCESSFUL (total time: 1 second)
With no changes being made to the database when I check on it again Access.
What could be causing this, and what does the error message mean? Thank you
"java.nio.channels.NonWritableChannelException" means that the database file cannot be updated. In your case that was because the database file was in the root folder of the Windows system drive (C:\) and mere mortals have restricted permissions on that folder.
Solution: Move the database file to a folder where you have full write access.

How to take input for a web service in java

I am trying to write a simple web service that must take a number as input and return details corresponding to it.
Here is my code that I have written till now.
package webserviceapp;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.jws.WebMethod;
#WebService
public class WebServiceApp {
/**
* #param args the command line arguments
*/
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.100.66.28:3306/dbname";
// Database credentials
static final String USER = "user";
static final String PASS = "pass";
static Map<Integer, String> map = new HashMap<Integer, String>();
public static void main(String[] args) {
// TODO code application logic here
Connection conn;
Statement stmt;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql = "Select * from table";
ResultSet rs;
rs = stmt.executeQuery(sql);
while(rs.next()){
//do something
}
}catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
#WebMethod(action = "returnDetails")
public static String[] returnDetails(int k) throws notFoundException{
//do the work
//returns String[]
}
private static class notFoundException extends Exception {
public notFoundException(String s) {
System.out.println(s);
System.err.println(s);
}
}
}
I do not know how to take input for the above web service. I have a html page that has a text box and submit button for which I get values through a php code. I want to tunnel this number as input to my web service. Can anyone tell me how can I proceed.
Also, I want the output String[] to be returned to php code so it can be displayed on the html page.
Thanks in advance.
you can pass it in the URL and from the url you can get the values in java
Working off the assumption that you are looking to invoke a RESTful service, there are multiple ways of obtaining input parameters. You can refer to the below article for the ways to achieve this -
http://www.java4s.com/web-services/how-restful-web-services-extract-input-parameters
Code examples for each are available at http://www.java4s.com/web-services/
Another good article you can refer to is - https://vrsbrazil.wordpress.com/2013/08/07/passing-parameters-to-a-restful-web-service/

Android-MysqlConnectivity in eclipse

I am new to android, So i need a basic knowledge,How to connect to the database and Select some of the values from it.
These are all the following steps i have already completed by watching and reading some online tutorials.
Created a New ANDROID Project Named And2.
Created a New JAVA Project named MYSQLConnection which is used to store the database connection.
I have Downloaded mysql-connector-java-5.1.34 file Online and added it.
I have attached the Screen Shot the total overview of my eclipse.
Now i just needed to access the database in And2 and Write a Simple Select Query So that i can make sure that connection is created.
Shown below is the Java file for DB Connection.
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import com.mysql.jdbc.*;
//import com.mysql.jdbc.Connection;
//import com.mysql.jdbc.Statement;
public class Main {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
try
{
String connectionUrl = "jdbc:mysql://localhost:3306/testdatabase";
String connectionUser = "root";
String connectionPassword = "12345";
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
//Statement stmt = conn.createStatement();
// ResultSet reset = stmt.executeQuery("select * from TableName");
//
// //Print the data to the console
// while(reset.next()){
// Log.w("Data:",reset.getString(3));
//
// }
}
catch ( SQLException err )
{
System.out.println("Database connection failed");
}
}
}
Any Help appreciated.

Categories