Error 501 on Heroku - java

I have craeted a Web Application that can be deployed on Heroku by maven eclipse.
Group Id: org.glassfish.jersey.archetypes
Artifact Id: jersey-heroku-webapp
version: 2.17
then I followed this guide(1.5) to push it to Heroku.
https://jersey.java.net/documentation/latest/getting-started.html#heroku-webapp
I can not access my apple class from the http link- like this:
https://salty-refuge-2027.herokuapp.com/apple
and I am getting the error 500
I have tested it before without the JDBC procedure and I got the output Hello, from apple class therefore I guess it depends on the my implementation for the Heroku Postgres
https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-java
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("apple")
public class Apple {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
try {
getConnection();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Hello, from apple class";
}
private static Connection getConnection() throws URISyntaxException, SQLException {
//I have modified my orginal ingredients.
URI dbUri = new URI(System.getenv("postgres://mglfe545z6ixsgk:yf8gyK1hBh3jknzqepLnajWRLv#
ec2-60-16-433-222.compute-1.amazonaws.com:5432/d5kal1r7jtavr9"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':'
+ dbUri.getPort() + dbUri.getPath();
Connection con = DriverManager.getConnection(dbUrl, username, password);
System.out.println("It works");
return con;
}
}
I appreciate any help.

You should call System.getenv("DATABASE_URL"). You are calling getenv with the value of the env var, which will return null.

Related

How can I add username and password at runtime for Tomcate Datasource with Oracle UCP

I was trying to create a Datasource in tomcat with Oracle UCP and my requirement was not add the password at server.xml , I need to add that at server runtime, I have tried in many ways but didn't work.
Here is my code samples
server.xml in tomcat
<Resource
name="testds"
connectionPoolName="testds"
auth="Container"
factory="com.test.tomcat.datasorceEncrypt.CustomizeOracleUCPDataSource"
type="oracle.ucp.jdbc.PoolDataSource"
connectionFactoryClassName="com.test.tomcat.datasorceEncrypt.CustomizeOracleUCPDataSource2"
jmxEnabled="true"
initialPoolSize="10"
minPoolSize="10"
maxPoolSize="300"
fastConnectionFailoverEnabled="true"
url="jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=localhost)(PORT=3203))(CONNECT_DATA=
(SERVICE_NAME=employee)))"
sqlForValidateConnection="select 1 from DUAL" />
CustomizeOracleUCPDataSource .java
package com.test.tomcat.datasorceEncrypt;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import oracle.ucp.jdbc.PoolDataSourceImpl;
public class CustomizeOracleUCPDataSource extends PoolDataSourceImpl {
/* public CustomizeOracleUCPDataSource() {
Properties dbProperties = null;
try {
this.setPassword("pass");
this.setUser("user");
System.out.println(this.getUser() + "-------" + this.getPassword());
} catch (Exception e) {
}
}*/
#Override
public Connection getConnection() throws SQLException {
try {
this.setPassword("pass");
this.setUser("user");
System.out.println(this.getUser() + "-------" + this.getPassword());
} catch (Exception e) {
}
return super.getConnection(username, password);
}
#Override
public Connection getConnection(String username, String password) throws SQLException {
// TODO Auto-generated method stub
return super.getConnection(username, password);
}
#Override
protected void createPoolWithDefaultProperties() throws SQLException {
try {
this.setPassword("pass");
this.setUser("user");
System.out.println(this.getUser() + "-------" + this.getPassword());
} catch (Exception e) {
}
super.createPoolWithDefaultProperties();
}
}
CustomizeOracleUCPDataSource2.java
package com.test.tomcat.datasorceEncrypt;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import oracle.jdbc.pool.OracleDataSource;
public class CustomizeOracleUCPDataSource2 extends OracleDataSource {
public CustomizeOracleUCPDataSource2() throws SQLException {
super();
this.setPassword("pass");
this.setUser("user");
}
#Override
public Connection getConnection() throws SQLException {
this.setPassword("pass");
this.setUser("user");
return super.getConnection(username, password);
}
#Override
public Connection getConnection(String username, String password) throws SQLException {
return super.getConnection(username, password);
}
}
Nothing is working out my user name and passwords were printed in console, but couldn't able to set to the datasource.
I am getting below log info while datasource was getting created.
19-Dec-2019 19:34:35.763 FINE [http-nio-8080-exec-1] oracle.ucp.logging.ClioSupport._log oracle.ucp.jdbc.PoolDataSourceImpl:createPoolWithDefaultProperties:oracle.ucp.jdbc.PoolDataSourceImpl#6b938ce5:Connection pool instance is
19-Dec-2019 19:34:35.803 FINE [http-nio-8080-exec-1] oracle.ucp.logging.ClioSupport._log oracle.ucp.jdbc.PoolDataSourceImpl:createPool:oracle.ucp.jdbc.PoolDataSourceImpl#6b938ce5:Connection pool instance is created
With the details aI am not able to create a datasource I am getting below Error :
Error occurred while establishing connection to the Test database
Any help could be greatly appreciated.
I am using Ojdbc8.jar,ucp.jar
Finally I achieved encryption and decryption of password in tomcat , this solution will work for all your password problems please go to this link for more details.
Tomcat support for password encryption and deryption

Execute jar file using PLSQL

I have a a standalone java program and it read the data from REST end point and insert data into table in Server.
package com.test.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.test.connectdb.ConDataBase;
import com.test.entity.User;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/todos/");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
System.out.println("DONE2");
int responsecode = conn.getResponseCode();
String inline = "";
if(responsecode == 200){
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println("JSON data in string format");
System.out.println(inline);
sc.close();
}else{
throw new RuntimeException("HttpResponseCode:" +responsecode);
}
//-----------------------------------------------------------------------
Connection con = new ConDataBase().buildConnection();
User[] userList = new Gson().fromJson(inline, User[].class);
System.out.println(userList.length);
for (User user : userList) {
//System.out.println(user.getCompleted());
String insert_date = "insert into XX_USER "
+ "(USER_ID)"
+ "VALUES"
+"('"+user.getCompleted()+"')";
try {
PreparedStatement ps_data = con.prepareStatement(insert_date);
ps_data.executeUpdate();
con.commit();
System.out.println("Successfully Inserted");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I need to run this jar file using PLSQL. That means I have transferred this jar file into Linux server path (/home/rest). Oracle database is installed in server. I need to run this jar using PLSQL. Is it possible?
Use the LOADJAVA utility to load the jar file and all other jar dependencies into Oracle's internal classpath (this is different from the operating system's class path).
You will probably also want to change your code to a static method without arguments (rather than main with a string array argument) as it will make invoking the method much simpler.
// package and imports
public class Main {
public static void yourMethodName() {
// your code
}
}
Then you need to use something like:
CREATE PROCEDURE get_todos_from_rest_service AS
LANGUAGE JAVA NAME 'com.test.main.Main.yourMethodName()';
To create a procedure wrapper around the java method which you can then invoke in PL/SQL.
A more detailed example can be found here: Database Java Developer's Guide - Java Stored Procedures Application Example

java how to connect to a MySQL database in OpenShift

package library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class conexion {
private String server = "jdbc:mysql://" + System.getenv("OPENSHIFT_MYSQL_DB_HOST") + ":" + System.getenv("OPENSHIFT_MYSQL_DB_PORT") + "/" + System.getenv("OPENSHIFT_APP_NAME") + "";
private String user = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
private String pass = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
private Connection conn;
public Connection conectar() throws ClassNotFoundException, SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
this.conn = DriverManager.getConnection(server, user, pass);
} catch (Exception ex) {
Logger.getLogger(conexion.class.getName()).log(Level.SEVERE, null, ex + ex.getMessage());
}
return this.conn;
}
}
I have a java application lodged in OpenShift but when I try to connect it to the cartridge mysql nothing happens when you connect. only it stays in the servlet and takes no other action
Depending on what type of java server you are running on OpenShift, try reading through one of these articles, which should help you get your database connection up and running:
Tomcat: https://developers.openshift.com/en/tomcat-ds.html
JBoss AS: https://developers.openshift.com/en/jbossas-ds.html
JBoss EAP: https://developers.openshift.com/en/jbosseap-ds.html
WildFly: https://developers.openshift.com/en/wildfly-ds.html

JDBC to hive connection fails on invalid operation isValid()

I have followed this doc to try to set up a jdbc connection to hive. But eclipse shows this error. Not seem to figure out what it exactly means and the connection with appropriate password and username works in beeline so its not the problem of authentication.Below is the error i'm facing:
> 15/11/27 13:15:41 INFO jdbc.Utils: Supplied authorities: localhost:10000
> 15/11/27 13:15:41 INFO jdbc.Utils: Resolved authority: localhost:10000
> 15/11/27 13:15:41 INFO jdbc.HiveConnection: Will try to open client transport with JDBC Uri: jdbc:hive2://localhost:10000/default
> Exception in thread "main" java.sql.SQLException: Method not supported
at org.apache.hive.jdbc.HiveConnection.isValid(HiveConnection.java:1026)
at HiveJDBC.main(HiveJDBC.java:21)
here is the code:
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveJDBC {
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "hive", "PASSWORD");
if(con.isValid(0)){
System.out.println("success");
}else{
System.out.println("fail");
}
Statement stmt = con.createStatement();
String tableName = "tabledriver";
//stmt.executeQuery("create database " + tableName);
}
}
Your call to
if(con.isValid(0)){
is legal - but not implemented by the Hive JDBC Driver.
See Hive Source:
#Override
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
throw new SQLException("Method not supported");
}
Replace the check with a simple if(con != null) and you'll be fine.

Java - DriverManager.getConnection Access

i have the following code to test a link to a access database on a new server, everything works with the existing server and i am able to access the folder. !if.exists returns true and i can open the data base using Runtime.getRuntime().exec("run......... + f); so i know it can see the database. im unable to get a reason for the fail but its 100% failing at Connection conn = de.....
can anyone help me.
running gives following output - Java result: -1073741811
package testing;
import connections.LocalProperties;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewClass {
public static void main(String[] args) {
try {
File f = new File("\\\\***\\***\\****\\***.accdb");
if (!f.exists()) {
System.out.println("file does not exist" + f.getAbsolutePath());
return;
} else {
System.out.println("file does exist" + f.getAbsolutePath());
}
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getAbsolutePath();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String m_URLString = url;
String m_UserName = System.getProperty("user.name");
String m_Password = "*******";
Connection conn = DriverManager.getConnection(m_URLString, m_UserName, m_Password);
conn.close();
} catch (SQLException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When running i get the following popups:
Java.exe
If you were in the middle of something, the information might be lost, for more information click here
Error signature
App name:java.exe appver 7.0.30.5 modname:msvcr80.dll
I think you are missing this line-
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Categories