I'm having trouble setting up a connection with my database here and was wondering what I may be doing wrong.
The error is as follows:
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:postgresql://168.16.1.128:5432/dbname
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at sample.DbConnect.getConnection(DbConnect.java:21)
at sample.UserTest.main(UserTest.java:41)
My connecting class looks as follows:
public class DbConnect {
public java.sql.Connection getConnection() throws SQLException,IllegalAccessException, ClassNotFoundException {
java.sql.Connection conn = null;
String url = "jdbc:postgresql://168.16.1.128:5432/dbname";
conn = DriverManager.getConnection(url);
System.out.println("Connected to database");
return conn;
}
}
and heres where it gets called:
public class UserTest {
public static void main(String[] args) throws JSONException, SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
DbConnect db = new DbConnect();
db.getConnection();
}
}
I have a feeling the error may come from the way the url is written and if this is the case can someone please explain to me how to properly write the url?
This database doesnt require a password and username to be connected to. I hope anyone can be so kind as to help me.
Thanks!
Related
I was updating spring boot from 2.5.1 to 2.7 together with the r2dbc and postgres dependencies. I did no change the application.yml or test setup. Before the update my repository tests run fine with testcontainers, but now I see this exception which is thrown by a #AfterEach that tries to clean the DB:
2022-05-29 10:04:52.447 INFO 16673 --- [tainers-r2dbc-0] 🐳 [postgres:13.2] : Container postgres:13.2 started in PT1.244757S
Failed to execute SQL script statement #1 of InputStream resource [resource loaded through InputStream]: DROP SCHEMA public CASCADE; nested exception is io.r2dbc.postgresql.client.ReactorNettyClient$PostgresConnectionClosedException: Cannot exchange messages because the connection is closed
org.springframework.r2dbc.connection.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of InputStream resource [resource loaded through InputStream]: DROP SCHEMA public CASCADE; nested exception is io.r2dbc.postgresql.client.ReactorNettyClient$PostgresConnectionClosedException: Cannot exchange messages because the connection is closed
at org.springframework.r2dbc.connection.init.ScriptUtils.lambda$runStatement$9(ScriptUtils.java:571)
This is my abstract RepositoryTest:
#DataR2dbcTest
#ActiveProfiles("test")
internal abstract class RepositoryTest {
#Autowired
protected lateinit var connectionFactory: ConnectionFactory
#AfterEach
fun clean() {
runSql(
"""
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
"""
)
}
protected fun runSql(sql: String) {
runScript(InputStreamResource(sql.byteInputStream()))
}
protected fun runScript(sqlScript: Resource) {
runBlocking {
val connection = connectionFactory.create().awaitFirst()
ScriptUtils.executeSqlScript(connection, sqlScript)
.block() // <---- throws the said exception, but it worked before the update.
}
}
}
My actual test looks like this:
internal class MyRepoTest : RepositoryTest() {
#Autowired
private lateinit var myRepo: MyRepository
#Test
fun someTest() {
val userId = 3429L
val myEntities = ...
runBlocking { myRepo.saveAll(myEntities).collect() }
val result = myRepo.findAllByUserId(userId).asFlux()
StepVerifier.create(result)
.expectNextMatches { it.userId == userId}
.expectNextMatches { it.userId == userId}
.verifyComplete()
}
}
I guess the way I try to execute the SQL commands is not fine, how should I do it?
val connection = connectionFactory.create().awaitFirst()
ScriptUtils.executeSqlScript(connection, sqlScript)
.block() // <---- throws the said exception, but it worked before the update.
EDIT
I figured out that using ResourceDatabasePopulator works fine:
7protected fun runScript(sqlScript: Resource) {
runBlocking {
ResourceDatabasePopulator(sqlScript).populate(connectionFactory).block()
}
}
But I still would like to understand why the original implementation now fails.
I am facing problem to write test cases for a rest url which calls another URL through Rest Template.
Please find my code below:-
#RestController
public class ParentController{
#Value("${child.url}")
private String childUrl;
#Autowired
private RestTemplateUtil restTemplateUtil;
#RequestMapping(value = "/parent",method = RequestMethod.POST)
public ResponseEntity<Object> callChildController(#RequestBody InputParam inputParam, HttpServletRequest request) {
return restTemplateUtil.templateService(restTemplateUtil.formURL(request, childUrl), HttpMethod.POST,null,inputParam, Object.class);
}}
}
#Service
public class RestTemplateUtil {
RestTemplate restTemplate = new RestTemplate();
public ResponseEntity<Object> templateService(String url, HttpMethod method, HttpHeaders headers, ...............){
logger.info("Rest template service called..");
response = restTemplate.exchange(url,method,entity,responseType);
return response;
}
public String formURL(HttpServletRequest request, String childUrl){
return "http://" + request.getServerName() + ":" + request.getServerPort() + childUrl;
}
}
JUnit Test case written:-
Mockito.when(restTemplateUtil.templateService(Mockito.anyString(),
Mockito.<HttpMethod> eq(HttpMethod.POST),
Mockito.<HttpHeaders> any(),
Mockito.<HttpEntity<?>> any(),
Mockito.<Class<Object>> any())).thenReturn(mockRespEntity);
this.mvc.perform(post("/parent")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(requestObj)))
.andExpect(status().is2xxSuccessful());
I am a newbie to Mockito, so with my meagre knowledge have build the above test case.
Please advise and correct me if I am wrong.
On executing this, I am getting error:-
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:80/child": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
The portno is wrong here.
Please help.
Thanks.
I have written a small application running OrientDB embedded. It works well. I can read and write to the database from the applicatiom using a plocal connection.
Now I am trying to access the same database from a remote OrientDB client (from a another PC).
I am getting a error message telling me that the database is locked and cant be accessed.
Is there a work around for this, or are I doing something wrong?
Using Java and OrienDB 2.2.12
You can try this code for connection:
private static final String dbUrl = "remote:localhost/databaseName";
private static final String dbUser = "admin";
private static final String dbPassword = "admin";
public static void createDBIfDoesNotExist() throws IOException {
OServerAdmin server = new OServerAdmin(dbUrl).connect(dbUser, dbPassword);
if (!server.existsDatabase("plocal")) {
server.createDatabase("graph", "plocal");
}
server.close();
}
public static void connectToDBIfExists() throws IOException {
OServerAdmin server = new OServerAdmin(dbUrl).connect(dbUser, dbPassword);
// some code
server.close();
}
I need help in creating remote connections in Jboss-eap 6.4 HornetQ
I have this code:
import java.util.Hashtable;
import javax.jms.*;
import javax.naming.*;
public class QueueSend {
private final static String JNDI_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private final static String JMS_FACTORY = "jms/RemoteConnectionFactory";
private final static String QUEUE = "jms/queue/test";
private final static String jbossUrl = "remote://localhost:4447";
private static InitialContext getInitialContext() throws NamingException {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, jbossUrl);
env.put(Context.SECURITY_PRINCIPAL, "appuser"); // <-- username
env.put(Context.SECURITY_CREDENTIALS, "appuser_2015"); // <-- password
return new InitialContext(env);
}
public static void main(String[] args) throws Exception {
InitialContext ic = getInitialContext();
QueueConnectionFactory qconFactory =
(QueueConnectionFactory)ic.lookup(JMS_FACTORY);
QueueConnection qcon =
qconFactory.createQueueConnection("appuser","appuser_2015");
QueueSession qsession = qcon.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue)ic.lookup(QUEUE);
QueueSender qsender = qsession.createSender(queue);
qcon.start();
TextMessage msg = qsession.createTextMessage();;
msg.setText("HelloWorld");
qsender.send(msg);
qsender.close();
qsession.close();
qcon.close();
System.out.println("Message Sent!");
}
}
And when I ran this code It displays an error:
Exception in thread "main" javax.naming.NamingException: Failed to create remoting connection [Root exception is java.lang.ExceptionInInitializerError]
at org.jboss.naming.remote.client.ClientUtil.namingException(ClientUtil.java:36)
at org.jboss.naming.remote.client.InitialContextFactory.getInitialContext(InitialContextFactory.java:121)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:197)
at com.wendell.QueueSend.getInitialContext(QueueSend.java:28)
at com.wendell.QueueSend.main(QueueSend.java:32)
Caused by: java.lang.ExceptionInInitializerError
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1.sendVersionHeader(RemoteNamingStoreV1.java:69)
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1.start(RemoteNamingStoreV1.java:64)
at org.jboss.naming.remote.protocol.v1.VersionOne.getRemoteNamingStore(VersionOne.java:45)
at org.jboss.naming.remote.protocol.Versions.getRemoteNamingStore(Versions.java:49)
at org.jboss.naming.remote.client.RemoteContextFactory.createVersionedStore(RemoteContextFactory.java:68)
at org.jboss.naming.remote.client.NamingStoreCache.getRemoteNamingStore(NamingStoreCache.java:60)
at org.jboss.naming.remote.client.InitialContextFactory.getOrCreateCachedNamingStore(InitialContextFactory.java:166)
at org.jboss.naming.remote.client.InitialContextFactory.getOrCreateNamingStore(InitialContextFactory.java:139)
at org.jboss.naming.remote.client.InitialContextFactory.getInitialContext(InitialContextFactory.java:104)
... 6 more
Caused by: java.lang.RuntimeException: Could not find a marshaller factory for river marshalling strategy
at org.jboss.naming.remote.protocol.v1.WriteUtil.<clinit>(WriteUtil.java:50)
... 15 more
I don't know what's the problem here, Did I miss something? Where did I go wrong?
Please help. Thanks
You may be having jboss-marshalling-xxxx.jar but missing the jboss-marshalling-river-xxxx.jar in your client's classpath.
Add jboss-marshalling-river-xxxx.jar jar file to your classpath as well.
In my case, I had jboss-marshalling-1.4.11.Final.jar but was missingjboss-marshalling-river-1.4.11.Final.jar in my classpath.
My client was then able to make remote EJB calls to wildfly.
I got a little help from This link.
Am new to web services. Am trying to generate unique session id for every login that a user does, in web services.
What I thought of doing is,
Write a java file which has the login and logout method.
Generate WSDL file for it.
Then generate web service client(using Eclipse IDE), with the WSDl file which I generate.
Use the generated package(client stub) and call the methods.
Please let me know if there are any flaws in my way of implementation.
1. Java file with the needed methods
public String login(String userID, String password) {
if (userID.equalsIgnoreCase("sadmin")
&& password.equalsIgnoreCase("sadmin")) {
System.out.println("Valid user");
sid = generateUUID(userID);
} else {
System.out.println("Auth failed");
}
return sid;
}
private String generateUUID(String userID) {
UUID uuID = UUID.randomUUID();
sid = uuID.toString();
userSessionHashMap = new HashMap<String, String>();
userSessionHashMap.put(userID, sid);
return sid;
}
public void logout(String userID) {
Set<String> userIDSet = userSessionHashMap.keySet();
Iterator<String> iterator = userIDSet.iterator();
if (iterator.equals(userID)) {
userSessionHashMap.remove(userID);
}
}
2. Generated WSDL file
Developed the web service client from the wsdl.
4. Using the developed client stub.
public static void main(String[] args) throws Exception {
ClientWebServiceLogin objClientWebServiceLogin = new ClientWebServiceLogin();
objClientWebServiceLogin.invokeLogin();
}
public void invokeLogin() throws Exception {
String endpoint = "http://schemas.xmlsoap.org/wsdl/";
String username = "sadmin";
String password = "sadmin";
String targetNamespace = "http://WebServiceLogin";
try {
WebServiceLoginLocator objWebServiceLoginLocator = new WebServiceLoginLocator();
java.net.URL url = new java.net.URL(endpoint);
Iterator ports = objWebServiceLoginLocator.getPorts();
while (ports.hasNext())
System.out.println("ports Iterator size-->" + ports.next());
WebServiceLoginPortType objWebServiceLoginPortType = objWebServiceLoginLocator
.getWebServiceLoginHttpSoap11Endpoint();
String sid = objWebServiceLoginPortType.login(username, password);
System.out.println("sid--->" + sid);
} catch (Exception exception) {
System.out.println("AxisFault at creating objWebServiceLoginStub"
+ exception);
exception.printStackTrace();
}
}
On running the this file, I get the following error.
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.net.ConnectException: Connection refused: connect
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:java.net.ConnectException: Connection refused: connect
Can anyone suggest an alternate way of handling this task ? And what could probably be the reason for this error.
Web services are supposed to be stateless, so having "login" and "logout" web service methods doesn't make much sense.
If you want to secure web services calls unfortunately you have to code security into every call. In your case, this means passing the userId and password to every method.
Or consider adding a custom handler for security. Read more about handlers here.