configuration file inb mongoDB - java

i have problem
I'm using jelastic to host java and mongoDB app. And I have problem for the connection between my app and their mongoDB provide by Jelasctic.
Their config file look like this :
public class MongoManager {
static String host, dbname, user, password;
public void addData(int repeats) {
try {
DBCollection dbc = null;
Properties prop = new Properties();
prop.load(new FileInputStream(System.getProperty("user.home") + "/mydb.cfg"));
host = prop.getProperty("host").toString();
dbname = prop.getProperty("dbname").toString();
user = prop.getProperty("user").toString();
password = prop.getProperty("password").toString();
System.out.println("host: " + host + "\ndbname: " + dbname + "\nuser: " + user + "\npassword: " + password);
Mongo m = new Mongo(host, 27017);
DB db = m.getDB(dbname);
if (db.authenticate(user, password.toCharArray())) {
System.out.println("Connected!");
} else {
System.out.println("Connection failed");
}
try {
db.getCollection("mycollection");
} catch (Exception e) {
db.createCollection("mycollection", null);
} finally {
System.out.println("Repeats: " + repeats);
for (int i = 1; i <= repeats; i++) {
BasicDBObject data = new BasicDBObject("data", new Date());
db.getCollection("mycollection").save(data);
System.out.println("INFO: row added " + data);
}
}
} catch (IOException ex) {
}
}
and mine
public class MongodbUtil {
private static Mongo mongo = null;
private static Morphia morphia = null;
private static Datastore ds = null;
private MongodbUtil() {};
public static synchronized DB getDB(String str) throws Exception {
if(mongo == null) {
mongo = new Mongo();
}
return mongo.getDB(str);
}
public static synchronized Mongo getMongo() throws Exception {
if(mongo == null) {
mongo = new Mongo("localhost", 27017);
}
return mongo;
}
public static synchronized Morphia getMorphia() throws Exception {
if(morphia == null) {
mongo = getMongo();
morphia = new Morphia();
morphia.mapPackage("com.sogeti.simulator.entity");
}
return morphia;
}
public static synchronized Datastore getDataStore(){
if(ds == null){
try {
morphia = getMorphia();
ds = morphia.createDatastore(mongo, "Simulator");
} catch (Exception e) {
e.printStackTrace();
}
}
return ds;
}
IS that same file or not ?
How can i put in my config file properties like host ? password ? and others ?!
My MongoDB.cfg.xml looks like this but i think this is bad because i don't use SPRING OR MAVEN :
i don'T see any example of a simple MongoDB.cfg.xml in the web.
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd;">
<dependency>
<groupId>com.morphia.Morphia</groupId>
<artifactId>morphia</artifactId>
<version>0.99</version>
</dependency>
<dependency>
<groupId>com.mongodb.Mongo</groupId>
<artifactId>mongo</artifactId>
<version>2.10.1</version>
</dependency>

It seems to me that similar problem was asked at Jelastic community here.
The problem is resolved for that user, please pay your attention to the suggestions stated at that thread.

Related

File corrupted while reading record: null - Spring boot java

I'm doing a simple API, and i'm getting the next error:
File corrupted while reading record: null. Possible solution: use the recovery tool [90030-200]
this is the code of the controller that i'm using
#PostMapping("/save")
public ResponseEntity saveDentist(#RequestBody Dentist data) {
DentistService dentistService = new DentistService(new DentistDaoH2());
if(data == null) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
return ResponseEntity.status(200).body(dentistService.save(data));
}
this is the code of the DAO for the operations of the database(i'm using H2):
#Override
public Dentist save(Dentist data) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
Class.forName(JDBC_DRIVER_H2);
connection = DriverManager.getConnection(URL,USER,PASSWORD);
preparedStatement = connection.prepareStatement("INSERT INTO dentist values(?,?,?,?)");
preparedStatement.setString(1,data.getName());
preparedStatement.setString(2,data.getLastName());
preparedStatement.setInt(3,data.getAge());
preparedStatement.setString(4,data.getProfessionalCard());
preparedStatement.executeUpdate();
preparedStatement.close();
System.out.println("its saved");
logger.info("the user was registered with success");
} catch (SQLException e) {
logger.error(e.getMessage());
} catch (ClassNotFoundException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
return data;
}
the code of the service:
public Dentist save(Dentist dentist) {
if(dentist == null) {
return null;
}
return this.daoService.save(dentist);
}
the repository layer have the next configuration for h2:
private static final String JDBC_DRIVER_H2 = "org.h2.Driver";
private final static String USER = "sa";
private final static String PASSWORD = "";
private final static String URL = "jdbc:h2:~/test";
In the file application.properties have :
spring.datasource.url= jdbc:h2:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled = true

User already has more than 'max_user_connections' active connections using HikariCP

I'm trying to use HikariCP for a Java EE app for school, but I don't understand why it doesn't work properly.. I'm making an API, and I'm using a MySQL Server with a Payara Server for my app.
I can call my API like 4 times before I get this error msg: http://prntscr.com/v7eopd The only way I found for solving is to restart Payara Server completely (even redeploy doesn't work)
I followed the HikariCP doc and configured my mysql.properties file as follow:
jdbcUrl = jdbc:mysql://mysql.iutrs.unistra.fr/devservweb?serverTimezone=UTC&useLegacyDatetimeCode=false
dataSource.user = user
dataSource.password = pwd
dataSource.cachePrepStmts=true
dataSource.prepStmtCacheSize=250
dataSource.prepStmtCacheSqlLimit=2048
dataSource.useServerPrepStmts=true
dataSource.useLocalSessionState=true
dataSource.rewriteBatchedStatements=true
dataSource.cacheResultSetMetadata=true
dataSource.cacheServerConfiguration=true
dataSource.elideSetAutoCommits=true
dataSource.maintainTimeStats=false
I did a DAO Pattern so, here is my DAOFactory for MySQL
public class MySQLDAOFactory extends DAOFactory {
private static final String PROPERTIES_FILE = "mysql.properties";
public Connection getConnection() throws SQLException, DAOConfigurationException {
Properties properties = new Properties();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream propertiesFile = classLoader.getResourceAsStream(PROPERTIES_FILE);
if(propertiesFile == null) {
throw new DAOConfigurationException("File " + PROPERTIES_FILE + " not found");
}
try {
properties.load(propertiesFile);
} catch (IOException e) {
throw new DAOConfigurationException("MySQL properties file could not be loaded " + PROPERTIES_FILE, e);
}
HikariConfig config = new HikariConfig(properties);
config.setDriverClassName("com.mysql.cj.jdbc.Driver");
HikariDataSource ds = new HikariDataSource(config);
return ds.getConnection();
}
#Override
public FlightDAO getFlightDAO() {
return new MySQLFlightDAO(this);
}
#Override
public UserDAO getUserDao() {
return new MySQLUserDAO(this);
}
}
public abstract class DAOFactory {
public static DAOFactory getInstance(Persistence target) {
DAOFactory daoF = null;
switch (target) {
case MySQL:
daoF = new MySQLDAOFactory();
break;
}
return daoF;
}
public abstract FlightDAO getFlightDAO();
public abstract UserDAO getUserDao();
}
#Override
public User findByUsername(String username) throws DAOException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = dao.getConnection();
preparedStatement = initPreparedStatement(connection,
"SELECT user_id, username, password " +
"FROM user " +
"WHERE username = ?",
false,
username);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()) {
user = map(resultSet);
}
} catch(SQLException e) {
throw new DAOException(e);
} finally {
closes(resultSet, preparedStatement, connection); // I'm using connection.close, statement.close and resultset.close inside this method
}
return user;
Before using HikariCP I used the default JDBC for getting connection and my code worked properly.
I can't find how to solve it because I though HikariCP manage pool automatically...
I'm in a hurry because I have to send it to my professor at the end of the week, so if someone can help me please, I do not find any help on google :( !
Thanks !

Run a Cypher query from Spring to Neo4j

I have uploaded a CSV file and already have nodes and relationship defined on Neo4j. I've tried to create a program base on an example that basically run a cypher query from Spring that would generate the output from neo4j. However, I'm encountering this error:
Exception in thread "main" java.lang.NoSuchMethodError:org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(Ljava/io/File;)Lorg/neo4j/graphdb/GraphDatabaseService;
at org.neo4j.connection.Neo4j.run(Neo4j.java:43)
at org.neo4j.connection.Neo4j.main(Neo4j.java:37)
I'm wondering what could possibly be the error?
Here is my code:
public class Neo4j{
public enum NodeType implements Label{
Issues, Cost, Reliability, Timeliness;
}
public enum RelationType implements RelationshipType{
APPLIES_TO
}
String rows = "";
String nodeResult;
String resultString;
String columnString;
private static File DB_PATH = new File("/Users/phaml1/Documents/Neo4j/default.graphdb/import/");
public static void main(String[] args){
Neo4j test = new Neo4j();
test.run();
}
void run()
{
clear();
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
try(Transaction tx1 = db.beginTx();
Result result = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e"))
{
while(result.hasNext())
{
while ( result.hasNext() )
{
Map<String,Object> row = result.next();
for ( Entry<String,Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
}
rows += "\n";
}
}
try (Transaction something = db.beginTx();
Result result1 = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e"))
{
Iterator<Node> n_column = result.columnAs("n");
for(Node node: Iterators.asIterable(n_column))
{
nodeResult = node + ": " + node.getProperties("Description");
}
List<String> columns = result.columns();
columnString = columns.toString();
resultString = db.execute("MATCH(b:Business)-[:APPLIES_TO]->(e:Time) RETURN b,e").resultAsString();
}
db.shutdown();
}
}
private void clear(){
try{
deleteRecursively(DB_PATH);
}
catch(IOException e){
throw new RuntimeException(e);
}
}
}
It looks like a Neo4j version conflict.
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
has a String as the argument in Neo4j 2x (https://neo4j.com/api_docs/2.0.3/org/neo4j/graphdb/factory/GraphDatabaseFactory.html#newEmbeddedDatabase(java.lang.String))
but a File in Neo4j 3x (http://neo4j.com/docs/java-reference/current/javadocs/org/neo4j/graphdb/factory/GraphDatabaseFactory.html#newEmbeddedDatabase-java.io.File-)
SDN is probably pulling in Neo4j 2.3.6 as a dependency- please check your dependency tree and override the Neo4j version

Why is java.sql.DriverManager.getConnection(...) hanging?

I am attempting to get a connection to my University's MySQL DB but the connection is hanging.
import java.sql.*;
public class ConnectToDB {
public static void main(String args[]){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://db.cs.myUniversity.com/dbName";
System.out.println("BEFORE");
Connection con = DriverManager.getConnection(url,"me", "password");
System.out.println("AFTER");
...
This call: time java ConnectToDB prints (after I eventually kill it):
Copyright 2004, R.G.Baldwin
BEFORE
AFTER
real 3m9.343s
user 0m0.316s
sys 0m0.027s
I just downloaded MySQL Connector/J from here. I am not sure if that is part of the problem. I followed the directions fairly precisely.
I can also connect to mysql on the command line like this:
$ mysql -u me -h db.cs.myUniversity.com -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 882328
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use dbName;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SHOW tables;
+-------------------+
| Tables_in_dbName |
+-------------------+
| classics |
+-------------------+
1 row in set (0.00 sec)
Possible Problems:
The Java code I wrote
How I installed MySQL Connector/J
Some kind of network problem blocking the connection
Question: What should I do to solve this problem? Why is the getConnection call hanging?
I was following this tutorial
The output you provide is not helpful.
I see BEFORE and AFTER being printed, so the connection was made. The code doesn't show what those timings encompass, so I can't tell what they mean.
If you're suggesting that your code had to killed because the connection was never made, it's probably because your username, password, and client IP have not been GRANTed permissions that are needed.
Could be:
your university network; find a network engineer to ask about firewalls.
permission in the MySQL database; find the DBA and ask.
your code; you didn't post enough to tell. Post the whole class.
What's up with that copyright? I'd lose that.
This code works. Modify it so the pertinent parameters match your problem. (Mine uses MySQL 5.1.51 and a table named Party.) When I run it on my local machine, I get a wall time of 641 ms.
package persistence;
import java.sql.*;
import java.util.*;
/**
* DatabaseUtils
* User: Michael
* Date: Aug 17, 2010
* Time: 7:58:02 PM
*/
public class DatabaseUtils
{
/*
private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
private static final String DEFAULT_USERNAME = "pgsuper";
private static final String DEFAULT_PASSWORD = "pgsuper";
*/
private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
private static final String DEFAULT_USERNAME = "party";
private static final String DEFAULT_PASSWORD = "party";
public static void main(String[] args)
{
long begTime = System.currentTimeMillis();
String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);
Connection connection = null;
try
{
connection = createConnection(driver, url, username, password);
DatabaseMetaData meta = connection.getMetaData();
System.out.println(meta.getDatabaseProductName());
System.out.println(meta.getDatabaseProductVersion());
String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
connection.setAutoCommit(false);
String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
List parameters = Arrays.asList( "Foo", "Bar" );
int numRowsUpdated = update(connection, sqlUpdate, parameters);
connection.commit();
System.out.println("# rows inserted: " + numRowsUpdated);
System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
}
catch (Exception e)
{
rollback(connection);
e.printStackTrace();
}
finally
{
close(connection);
long endTime = System.currentTimeMillis();
System.out.println("wall time: " + (endTime - begTime) + " ms");
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
{
return DriverManager.getConnection(url);
}
else
{
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement st)
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
{
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try
{
if (rs != null)
{
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next())
{
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i)
{
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
}
finally
{
close(rs);
}
return results;
}
public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException
{
List<Map<String, Object>> results = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters)
{
ps.setObject(++i, parameter);
}
rs = ps.executeQuery();
results = map(rs);
}
finally
{
close(rs);
close(ps);
}
return results;
}
public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException
{
int numRowsUpdated = 0;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters)
{
ps.setObject(++i, parameter);
}
numRowsUpdated = ps.executeUpdate();
}
finally
{
close(ps);
}
return numRowsUpdated;
}
}

Cannot connect to Oracle DB from Java - ORA-12560: TNS:protocol adapter error

This is my first Java application I am creating (using Eclipse IDE) and the second Oracle based app (I'm a .NET/MSSQL guy for years). The first Oracle app I wrote in .NET did not have any issues, and I'm trying to connect to the same server.
I have installed:
'Java 2 Platform, Enterprise Edition 1.4 SDK'
'Java DB `10.5.3.0'
-'Java(TM) 6 Update 21
'Java(TM) SE Development Kit 6 update 21
'Oracle IRM Client' (11g)
Oracle 11g Release 2 JDBC Drivers (ojdbc6.jar)
My code is very simple. Here it is:
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:oci:#");
ods.setUser("username");
ods.setPassword("password");
ods.setServerName("servername");
ods.setPortNumber(1549);
ods.setServiceName("foo.myservice.com");
Connection conn = ods.getConnection();
I get below exception:
Exception in thread "main" java.sql.SQLException: ORA-12560: TNS:protocol adapter error
at oracle.jdbc.driver.T2CConnection.checkError(T2CConnection.java:737)
at oracle.jdbc.driver.T2CConnection.logon(T2CConnection.java:401)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:531)
at oracle.jdbc.driver.T2CConnection.<init>(T2CConnection.java:148)
at oracle.jdbc.driver.T2CDriverExtension.getConnection(T2CDriverExtension.java:53)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:503)
at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:280)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:207)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:157)
at Select.GetScalar(Select.java:47)
at Job.Run(Job.java:20)
at Main.main(Main.java:19)
I have google'd the hack out of this.. I've tried adding a 'TNS entry to the tnsnames.ora file'. I've tried adding '##NAMES.DIRECTORY_PATH = (TNSNAMES, EZCONNECT)' to the sqlnet.ora file. I've tried various other things but nothing is working.
Has anyone experienced this before and has any clue on how to get this to work?? Am I using the wrong version? Server is remote (I don't have Oracle server installed locally, just client). Maybe I have wrong version of Java SDK or the wrong version of the JDBC .jar file?? I just need to connect to Oracle and run a single simple query! Thanks much for any help.
Try using the type IV JDBC driver instead of OCI if you can. The thin url looks like this:
jdbc:oracle:thin:#host[:port]/service
I'd try code that looked more like this (fill in your defaults for the driver, URL, username, and password):
package persistence;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DatabaseUtils
{
private static final String DEFAULT_DRIVER = "";
private static final String DEFAULT_URL = "";
private static final String DEFAULT_USERNAME = "";
private static final String DEFAULT_PASSWORD = "";
public static void main(String[] args)
{
String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);
Connection connection = null;
try
{
connection = createConnection(driver, url, username, password);
DatabaseMetaData meta = connection.getMetaData();
System.out.println(meta.getDatabaseProductName());
System.out.println(meta.getDatabaseProductVersion());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
close(connection);
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
{
return DriverManager.getConnection(url);
}
else
{
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement st)
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
{
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try
{
if (rs != null)
{
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next())
{
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i)
{
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
}
finally
{
close(rs);
}
return results;
}
}
If you want something simple, you should try using the THIN client instead of OCI client.
Don't forget to include the right jar (ojdbc5.jar for Java 5, ojdbc6.jar for Java 6).
Is the ServiceName you specified the service name of the Oracle instance you're trying to connect to? You're sure the port is correct?

Categories