How to make a connection localhost and my database - database

I'm using NetBeans to make a web application and using pgadmin4 for my database. The problem is when I'm making a connection pool.
This is my database http://prntscr.com/hzwn9h and I think the problem is because I want something like that http://prntscr.com/hzwnj2 but I have this http://prntscr.com/hzwnrw. I have tried a lot of solutions but it doesn't work and I don't know what else I have to do. One of the things I have tried was this https://rivaso.wordpress.com/2012/02/19/how-to-setup-a-new-database-in-postgresql-and-glassfish/ but unfortunately unsuccessful

Following code snippet shows how to establish connection for PostgreSQL using jdbc driver. Make sure to add jdbc driver to libraries.
public Connection DBConnect() {
try {
String host = "localhost";//host
String port = "5432";//db port
String db = "exp";//database name
String user = "root";//database username
String pass = "1234";//password
//connection url
String url = "jdbc:postgresql://" + host + ":" + port + "/" + db;
//initialize jdbc driver for postger sql
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
//return connection
return conn;
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
return null;
}
}
reference : jdbc.postgresql.org

public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/yourdatabasename";
Connection conn = DriverManager.getConnection(url, user,password);
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}

Related

Codename one application is not able to connect with server using https request

We have created codename one application which using https request.
I have not made any changes in code.
Earlier the request could be sent using https but now their is a problem and i am unable to connect to the server using https request but i am able to connect same https url using postman.
The connection code snippet is following please refer it
new APIHandler().PropertiesLoad();
ConnectionRequest req = new ConnectionRequest() {
protected void handleErrorResponseCode(int code, String message) {
if (code != 200) {
// do something
}
}
};
req.setUrl(properties.getProperty("https_url"));
req.setPost(true);
req.setTimeout(Constant.TIMEOUT);
req.addArgument("FirstName", fName;
req.addArgument("SecondName", sName);
req.addArgument("BirthDate", bDate);
req.addArgument("Password", pWord);
NetworkManager.getInstance().addErrorListener((e) -> e.consume());
NetworkManager.getInstance().addToQueueAndWait(req);
byte[] data = req.getResponseData();
if (data == null) {
}
result = new String(data);
} catch (Exception e) {
//get nullpointer exception because result get null
result = "";
}
return result;

Selenium-Extent_Reports: Not able to view the failure screenshots on other Computer/Machine

-Failure Screenshot are visible in Extent_Reports on my local machine. But not able to view the failure screenshot in Extent_Reports on other Computer/Machine.
-When i trigger build from Jenkins, After build successful, Sending email to:Recipient List
To Capture Screenshot
public String captureScreen(String fileName) {
if(fileName =="") {
fileName="Screenshot"; }
File destFile=null;
Calendar calendar =Calendar.getInstance() ;
SimpleDateFormat formater= new SimpleDateFormat("dd_MM_yyy_hh_mm_ss");
File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
String reportDirectory = "/src/main/java/com/test/automation/Demo/screenshot/";
//String reportDirectory= new File(System.getProperty("user.dir")).getAbsolutePath()+"./src/main/java/com/test/automation/Demo/screenshot/";
destFile= new File((String)reportDirectory + fileName +"-" + formater.format(calendar.getTime())+ ".png");
FileUtils.copyFile(srcFile,destFile );
//This will help us to link screen shot in Extent report
Reporter.log("<a href='"+destFile+ "'><img src='" +destFile+"' height='100' width='100'/></a>");
//Reporter.log("<a href='"+destFile.getAbsolutePath()+ "'><img src='" +destFile.getAbsolutePath()+"' height='100' width='100'/></a>");
}
catch(IOException e) {
e.printStackTrace();
}
return destFile.toString();
}
For generating Extent reports with screenshots for Failure test cases
public void getresult(ITestResult result) {
if(result.getStatus()==ITestResult.FAILURE)
{
test.log(LogStatus.ERROR, result.getName()+" Test case FAILED due to below issues: "+result.getThrowable());
String screen = captureScreen("");
test.log(LogStatus.FAIL," Failure Screenshot : "+ test.addScreenCapture(screen));
}}
If You're using remoteWebDriver than it must be augmented before you can use the screenshot capability. Did You try to
WebDriver driver = new RemoteWebDriver();
driver = new Augmenter().augment(driver);
// or for mobile driver
androidDriver.setFileDetector(new LocalFileDetector());
//this is needed when using remoteDriver
Here is how I take screenshot for ExtentReport
File scrFile = driver.getScreenshotAs(OutputType.FILE);
String dest = System.getProperty("user.dir") + "/resources/screenshots/" + dataMethod.getAndroidDriver().getSessionId() + ".png";
File destination = new File(dest);
try {
FileUtils.copyFile(scrFile, destination);
// this is just utility which takes screenshot and copy it to desired destination
dataMethod.setScreenshotPath(destination.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
And on code failure:
#Override
public synchronized void onTestFailure(ITestResult result) {
setTestEndTime(result);
ExtentTest extentTest = methodData.getExtentTest();
extentTest.addScreenCaptureFromPath(methodData.getScreenshotPath());
}
Hope this will help.
I didn't used Extent reports, i have my own implementation for reports. But i am expecting is there is issue with src
<img src='" +destFile+"' height='100' width='100'/></a>");
Here, destFile brings location of image or screenshot which is related to your machine. the same should not be works for others. We have to use relative path, see this
https://www.w3schools.com/html/html_filepaths.asp
And also make sure that when sharing reports, it should contains all requires files and folders also.
Normally, the issue happens as the local files are not allowed to be loaded. So even we put relative or absolute path, that seems not work for many cases.
So I try to take base64screenshot instead, and it displays quite good in Extent Report.
To have the screenshot in folder report, just need to take screenshot as usual.
public static String getBase64Screenshot(WebDriver driver, String screenshotName) throws IOException {
String encodedBase64 = null;
FileInputStream fileInputStream = null;
TakesScreenshot screenshot = (TakesScreenshot) driver;
File source = screenshot.getScreenshotAs(OutputType.FILE);
String destination = windowsPath + "\\FailedTestsScreenshots\\"+screenshotName+timeStamp+".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
try {
fileInputStream =new FileInputStream(finalDestination);
byte[] bytes =new byte[(int)finalDestination.length()];
fileInputStream.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
}catch (FileNotFoundException e){
e.printStackTrace();
}
return encodedBase64;
}
Call it in failure cases:
public synchronized void onTestFailure(ITestResult result) {
System.out.println("==="+methodDes + "=== failed!");
try {
WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver");
String base64Screenshot = ExtentManager.getBase64Screenshot(driver, result.getName());
MediaEntityModelProvider mediaModel = MediaEntityBuilder.createScreenCaptureFromBase64String(base64Screenshot).build();
test.get().fail("image:", mediaModel);
} catch (IOException e) {
e.printStackTrace();
}
test.get().fail(result.getThrowable().getMessage());
}

How to access sqlite database from webserver and insert record using web services in codenameone

I am developing one application in CN1 that has to do with database, I want the user to enter a pin generated for them. once the user entered the valid pin, the apps will be activated for usage. The problem am having now is how to access the database using webservices. I have followed the webservices wizard tutorial, but all my effort was futile.
This is my snippet code.
private static final String DESTINATION_URL = "http://localhost:8085/CBT_PINS/folder/PINS.db";
ConnectionRequest req = new ConnectionRequest(DESTINATION_URL) {
#Override
protected void handleException(Exception err) {
Log.e(err);
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("An error occured while connecting to the server: " + err);
});
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("Error code from the server: " + code + "\n" + message);
});
}
};
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
Please help me out. I dont know what to do next. Thanks
This is because you aren't accessing a webservice. You are trying to open a database with an http URL:
SQLException: path to 'C:\Users\EMMY_OLUWASEGUN.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db'
Triggered by:
Database myDataBase = com.codename1.db.Database.openOrCreate(DESTINATION_URL);
The Database API is local to the device and not remote a webservice is something completely different.
Thanks for your response, Author of CN1. This is the full code below. I am using tomcat server on the local machine to test on the simulator. I am very sure if it works for me on the local machine's server, it will definitely work on the web server
private static final String DESTINATION_URL = "http://localhost:8085/CBT_PINS/folder/PINS.db";
ConnectionRequest req = new ConnectionRequest(DESTINATION_URL) {
#Override
Database myDataBase = com.codename1.db.Database.openOrCreate(DESTINATION_URL);
Cursor c = myDataBase.executeQuery("select pin from PIN_TABLE where id = 1" );
if (c.next()) {
Row r = c.getRow();
String pin = r.getString(0);
Dialog.show("valid pin", pin, "Ok", "Ok");
} else if (!c.next()) {
Dialog.show("Invalid pin", "keep off", "ok", "ok");
}
protected void handleException(Exception err) {
Log.e(err);
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("An error occured while connecting to the server: " + err);
});
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("Error code from the server: " + code + "\n" + message);
});
}
};
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
This is the error code generated for me when I ran the code:
WARNING: Apple will no longer accept http URL connections from applications you tried to connect to http://localhost:8085/CBT_PINS/folder/PINS.db to learn more check out https://www.codenameone.com/blog/ios-http-urls.html
java.sql.SQLException: path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
[Network Thread] 0:0:0,0 - Codename One revisions: 375ed2c938445450f0983f0d18235f61e793a7ee2004
[Network Thread] 0:0:0,0 - Exception: java.io.IOException - path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
Rendering frame took too long 187 milliseconds
at org.sqlite.SQLiteConnection.open(SQLiteConnection.java:156)
at org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:105)
at org.sqlite.JDBC.createConnection(JDBC.java:113)
at org.sqlite.JDBC.connect(JDBC.java:87)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at com.codename1.impl.javase.JavaSEPort.openOrCreateDB(JavaSEPort.java:7548)
at com.codename1.ui.Display.openOrCreate(Display.java:3690)
at com.codename1.db.Database.openOrCreate(Database.java:59)
at com.mycompany.myapp.MyApplication$1.readResponse(MyApplication.java:283)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:483)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.io.IOException: path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
at com.codename1.impl.javase.JavaSEPort.openOrCreateDB(JavaSEPort.java:7554)
at com.codename1.ui.Display.openOrCreate(Display.java:3690)
at com.codename1.db.Database.openOrCreate(Database.java:59)
at com.mycompany.myapp.MyApplication$1.readResponse(MyApplication.java:283)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:483)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

Throw DirectoryServicesCOMException (0x80072020) when try to RefreshCache for DirectoryEntry

I write a very sample test program and run it as local system account in a domain machine. Here is the code look like:
static void Main(string[] args)
{
try
{
System.Console.Out.WriteLine("Test Start");
List<string> temp = new List<string>();
temp.Add(Environment.UserDomainName);
temp.Add("test");
temp.Add("test.com");
temp.Add("dc.test.com");
temp.Add("gc.test.com");
foreach (var i in temp)
{
using (HostingEnvironment.Impersonate())
{
System.Console.WriteLine("LDAP://{0}", i);
DirectoryEntry entry = new DirectoryEntry("LDAP://" + i);
try
{
entry.RefreshCache();
string nativeGuid = entry.NativeGuid;
string path = entry.Path;
string server = entry.Options.GetCurrentServerName();
System.Console.WriteLine("{0} success!", i);
}
catch (Exception e)
{
System.Console.WriteLine("{0}\n {1}", i, e);
}
}
}
System.Console.Out.WriteLine("Test End");
}
catch (Exception e)
{
System.Console.Out.WriteLine("e:Main{0}", e.Message);
}
System.Console.In.ReadLine();
}
The NetBIOS name for the domain is "test", full domain name is "test.com". "dc.test.com" is the DC FQDN and "gc.test.com" is the GC FQDN.
It works fine for "test.com", "dc.test.com"" and "gc.test.com", but it throws DirectoryServicesCOMException (0x80072020) for "test" and "Environment.UserDomainName".
The detail running result is:
Test Start
LDAP://TEST
TEST
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operati
ons error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.RefreshCache()
at ConsoleApplication1.Program.Main(String[] args)
LDAP://test
test
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operati
ons error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.RefreshCache()
at ConsoleApplication1.Program.Main(String[] args)
LDAP://test.com
test.com success!
LDAP://dc.test.com
dc.test.com success!
LDAP://gc.test.com
gc.test.com success!
Test End
It works all fine if I run it as domian admin account. Any idea what cause this? Thanks a lots!
What are you actually trying to do? If you're on a machine joined to the domain, you should just do new DirectoryEntry().
As for your error, when you log on to Windows with a local account, the UserDomainName environment variable is set to the local computer name. If that machine's name is the same as the domain's NetBIOS name, then I wouldn't be surprised if Windows gets confused.

Can't connect to Derby in Eclipse

I am trying to develop a web app with eclipse that uses a derby database and runs on tomcat.
My problem is that I cannot start the derby server with eclipse (it works fine out of CMD) and I cannot get my servlet to establish a connection with the database, each time I try I get the error:
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.Jieren.servlets.Authenticator.testCredentials(Authenticator.java:84)
at com.Jieren.servlets.Authenticator.doPost(Authenticator.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
I do not have any xml files that do anything with the connection (I have seen web.xml and such that manage connections) but from what I have seen a connection should be possible via straight java code (which seemed easier to learn with as I am fairly new).
The code that I use to connect with is as follows.
Connection conn = null;
PreparedStatement prestat = null;
ResultSet pw = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/C:/apache-tomcat-7.0.19/Databases/Jieren;" +
"user=Access;" +
"password=Entry");
prestat = conn.prepareStatement("SELECT password FROM logs WHERE username = ?");
prestat.setString(1, username);
pw = prestat.executeQuery();
if (password.equals(pw.toString())) answer = 1;
pw.close();
pw = null;
prestat.close();
prestat = null;
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
}
finally{
if (pw != null){
try { pw.close();} catch (SQLException e){;}
pw = null;
}
if (prestat != null){
try { prestat.close();} catch (SQLException e){;}
prestat = null;
}
if (conn != null){
try {conn.close();} catch(SQLException e) {;}
conn = null;
}
}
From what I have figured out from looking around, the code should work if everything else is configured correctly. connecting to the database via ij outside eclipse works, so I have a feeling that there is a setting or something that I need to write in eclipse to connect this.
The exception is telling you that your network server is not running. When your connection URL starts jdbc:derby://hostname, then you are telling Derby you wish to run in client-server mode, meaning that your client application will establish a TCP/IP connection to the Network Server. See this doc for how to setup and operate the Network Server: http://db.apache.org/derby/docs/10.8/adminguide/

Resources