Orientdb: Import database in memory and use it as graph - java

This is my Java DB class in which I open database and import database export file in memory graph database, where I define all database schema information for testing cases.
Operation going well but how can I access the imported database as graph instance and not document instance of database?
I try so many things but I have failed...
Error :
The Person class exist in my schema so something else is going wrong.
Caused by:
> com.orientechnologies.orient.core.exception.OCommandExecutionException:
> Class 'PERSON' was not found in current database
Code:
import com.orientechnologies.orient.core.db.tool.ODatabaseExportException;
import com.orientechnologies.orient.core.db.tool.ODatabaseImport;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import lombok.Getter;
import java.io.IOException;
public class Db {
#Getter private static OrientGraphFactory factory;
#Getter private static OrientGraphNoTx graph;
static public void main(String[] args){
open("memory","database");
importDB("/schemas/diary-11202016.gz");
try {
seed();
} catch (InterruptedException e) {
e.printStackTrace();
}
closeDB();
}
public static void open(String dbType, String dbUrl) {
String dbInfo = dbType + ":" + dbUrl;
System.out.println(dbInfo);
factory = new OrientGraphFactory(dbInfo, "root", "root").setupPool(1, 10);
graph = factory.getNoTx();
}
public static void importDB(String path) {
try {
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), Db.class.getResourceAsStream(path), (iText) -> {
System.out.print(iText);
});
importDb.setMerge(true);
importDb.importDatabase();
importDb.close();
System.out.println("\nImporting database: OK");
} catch (ODatabaseExportException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void seed() throws InterruptedException {
System.out.println("Starting to seed...");
for (Vertex v : (Iterable<Vertex>) graph.command( new OCommandSQL("select from Person")).execute()) {
System.out.println("- Bought: " + v.getProperty("name"));
}
System.out.println("Finish to seed...");
}
public static void closeDB() {
factory.close();
}
}

Replace the following piece of code
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), Db.class.getResourceAsStream(path), (iText) -> {
System.out.print(iText);
});
importDb.setMerge(true);
with
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), path, (iText) -> {
System.out.print(iText);
});
// importDb.setMerge(true);

Related

Trying to print JSON results from a webservice using hibernate and Spring

I have two projects defined 1) GeneralOrm which is used for general purpose web services and 2)CompanyWS which includes company specific webservices.
I am using Spring and Hibernate 4 version
I am writing a GET request to pull information based on two parameters namely, employeeID and informationID. There can only be one employeeID and multiple
informationID. Based on a employeeID and Information ID, I want to display the employeeID, INFORMATION_ID, VALUE_DISPLAY_NAME and value_emp_ID in my JSON result.
My table EMP_METADATA in the database looks like the following:
column_Name Data_Type
EMPLOYEE_ID NUMBER
INFORMATION_ID NUMBER
VALUE_DISPLAY_NAME VARCHAR2(30 BYTE)
VALUE_EMP_ID NUMBER
Inside CompanyWS project, I have the GET request defined inside a controller in the following manner:
Inside package CompanyWS : edu.abc.company.controller
#RequestMapping(value="/get_em_metadata", method=RequestMethod.GET)
public String getEmpMetaData
(
#RequestParam(value="employee_id", defaultValue="0") Integer employeeID_,
#RequestParam(value="information_id", defaultValue="0") Integer informationID_
)
{
List<EmployeeMetaData> cvmetadata = null;
GetEmployeeResult result = new GetEmployeeResult();
try{
EmployeeMetaDataDao rmDao = (EmployeeMetaDataDao)context.getBean("EmployeeMetaDataDao");
List<EmployeeMetaData> rm = rmDao.findByEmpAndInfoId(employeeID_, informationID_);
if(rm != null) && (!rm.isEmpty()){
System.out.println("Checking Aug 31:"+rm); // This works and print outs on the console
}
} catch(Throwable th) {
th.printStackTrace();
result.setWebServiceStatus(th.getMessage(), false);
}
//return result.toJSON();
}
I am assuming that since my System.out.print statement is printing the following on the console after running the webservice,
Checking Aug 31:[edu.abc.company.orm.EmployeeMetaData#5963b830]
I am half way through and I just need to print the result in the JSON format. In order to print the result, I have defined GetEmployeeResult which is as follows and extending the WebServiceResult class. I am wondering do I need to use GetEmployeeResult and extend WebserviceResult class or I can directly use WebServiceResult class inside my controller to
print the results in JSON format? Any idea how should I proceed with the code for printing JSON inside controller. I have't used Hibernate before. Thanks in advance.
package edu.abc.company.json;
import java.util.List;
import edu.abc.company.domain.CvMetaDataList;
import edu.abc.company.domain.companyMetaDataList;
import edu.abc.company.util.WebServiceResult;
public class GetEmployeeResult extends WebServiceResult {
}
And here is the WebServiceResult class which is defined as follows:
package edu.abc.company.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import edu.abc.company.domain.StatusMessage;
import edu.abc.company.json.Views;
// A generic object that can be used to return data and a standardized status message from a web service.
public class WebServiceResult {
protected StatusMessage webservice_status;
// C-tor
public WebServiceResult() {}
// C-tor
public WebServiceResult(StatusMessage webserviceStatus_) {
webservice_status = webserviceStatus_;
}
// Web service status
public StatusMessage getWebServiceStatus() {
return webservice_status;
}
public void setWebServiceStatus(String message_, boolean success_) {
webservice_status = new StatusMessage();
if (success_) {
webservice_status.setStatus(Constants.SUCCESS); // Constants is another class which has messages defined, not including here
webservice_status.setMessage(message_);
} else {
webservice_status.setStatus(Constants.ERROR);
webservice_status.setMessage(message_);
}
}
// Export the object's contents as JSON.
public String toJSON(boolean pretty_) {
String json = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, pretty_);
// Convert the object to JSON.
json = objectMapper.writerWithView(Views.Normal.class).writeValueAsString(this);
}
catch(Exception e) {
e.printStackTrace();
}
return json;
}
public String toJSON() {
return toJSON(true);
}
}
The following are just for reference purpose in case someone is interested in looking at it:
I have defined the EmployeeMetaData inside the GeneralOrm project as follows:
Inside package GeneralOrm : edu.abc.company.orm
package edu.abc.company.orm;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="EMP_METADATA")
public class EmployeeMetaData
{
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public int getInformationId() {
return informationId;
}
public void setInformationId(int informationId) {
this.informationId = informationId;
}
public String getValueDisplayName() {
return valueDisplayName;
}
public void setValueDisplayName(String valueDisplayName) {
this.valueDisplayName = valueDisplayName;
}
public int getValueempId() {
return valueempId;
}
public void setValueEmpId(int valueempId) {
this.valueempId = valueempId;
}
#Id
#Column(name="EMPLOYEE_ID")
private int employeeId;
#Column(name="INFORMATION_ID")
private int informationId;
#Column(name="VALUE_DISPLAY_NAME")
private String valueDisplayName;
#Column(name="VALUE_EMP_ID")
private int valueempId;
}
I have defined the EmployeeMetaDataDao inside the GeneralOrm project as follows:
Inside project GeneralOrm : edu.abc.company.orm.dao
package edu.abc.company.orm.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.abc.company.orm.EmployeeMetaData;
import edu.abc.company.orm.dao.EmployeeMetaDataDao;
import edu.abc.company.util.Util;
public class EmployeeMetaDataDaoImpl implements EmployeeMetaDataDao {
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public List<EmployeeMetaData> list() {
logger.debug("Starting EmployeeMetaDataDaoImpl.list() .....");
Session session = null;
List<EmployeeMetaData> EmployeeMetaData = null;
try {
session = this.sessionFactory.openSession();
EmployeeMetaData = session.createQuery("FROM EmployeeMetaData").list();
} catch(Exception ex) {
ex.printStackTrace();
} finally {
session.close();
}
logger.debug("Completed EmployeeMetaDataDaoImpl.list() .....");
return EmployeeMetaData;
}
public List<EmployeeMetaData> findByEmpAndInfoId(int employee_id, int information_id) {
List<EmployeeMetaData> EmployeeMetaData = null;
Session session = null;
try {
session = this.sessionFactory.openSession();
EmployeeMetaData = session.createQuery("FROM EmployeeMetaData WHERE information_id = '" + information_id + "'" + " AND company_id = '" + employee_id + "'").list();
} catch(Exception ex) {
ex.printStackTrace();
} finally {
session.close();
}
return EmployeeMetaData;
}
// Main method goes here
public static void main(String[] args)
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
try{
EmployeeMetaDataDao rpcDao = (EmployeeMetaDataDao)context.getBean("EmployeeMetaDataDao");
List<EmployeeMetaData> EmployeeMetaData = rpcDao.list();
if ((EmployeeMetaData != null) && EmployeeMetaData.size() > 0) {
for (int i=0;i<EmployeeMetaData.size();i++) {
EmployeeMetaData re = EmployeeMetaData.get(i);
}
}
context.close();
} catch(Throwable th) {
th.printStackTrace();
} finally {
context.close();
}
}
private SessionFactory sessionFactory;
private static final Logger logger = LoggerFactory.getLogger(EmployeeMetaDataDaoImpl.class);
}

An example in Java using Embedded Cassandra Server to test a Cassandra-Spark job

I am new to Cassandra and Spark. I am trying to set up a test for my Spark job, which does the following:
Loads data from table A into DataFrames
Does some filtering, grouping and aggregating on these DataFrames
Loads the result into table B
I want to use Embedded Cassandra Server to run the test rather than having it connecting to a local instance of the Cassandra database. Has anyone done this before? If so, could someone point me to a good example please? Thanks for your help in advance!
this code does
package cassspark.clt;
import java.io.*;
import javafx.application.Application;
import java.util.concurrent.Executors ;
import java.util.concurrent.ExecutorService;
import org.apache.cassandra.service.CassandraDaemon;
import com.datastax.driver.core.exceptions.ConnectionException;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;
import org.apache.spark.sql.SparkSession;
public class EmbeddedCassandraDemo extends Application {
private ExecutorService executor = Executors.newSingleThreadExecutor();
private CassandraDaemon cassandraDaemon;
public EmbeddedCassandraDemo() {
}
public static void main(String[] args) {
try {
new EmbeddedCassandraDemo().run();
}
catch(java.lang.InterruptedException e)
{
;
}
}
#Override public void start(javafx.stage.Stage stage) throws Exception
{
stage.show();
}
private void run() throws InterruptedException, ConnectionException {
setProperties();
activateDeamon();
}
private void activateDeamon() {
executor.execute( new Runnable() {
#Override
public void run() {
cassandraDaemon = new CassandraDaemon();
cassandraDaemon.activate();
SparkSession spark = SparkSession .builder().master("local").appName("ASH").getOrCreate();
}
});
}
private void setProperties() {
final String yaml = System.getProperty("user.dir") + File.separator +"conf"+File.separator+"cassandra.yaml";
final String storage = System.getProperty("user.dir") + File.separator +"storage" + File.separator +"data";
System.setProperty("cassandra.config", "file:"+ yaml );
System.setProperty("cassandra.storagedir", storage );
System.setProperty("cassandra-foreground", "true");
String log4JPropertyFile = "./conf/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
} catch (IOException e) {
System.err.println("./conf/log4j.properties not found ");
System.exit(1);
;
}
}
}

How to Upload a file into web browser using Winium?

I know I can upload file to browser with many ways such as: AutoIt, Robot Class, and other ways(I tried them all and they worked most of time).
I got introduced to Winium and I would like to make the same test case with it, that is, upload a file to a browser using it, but I did not know what to do to switch between web driver to winium driver. Please help because I searched a lot for this trick but could not find any result
package testUtilities;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.winium.WiniumDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class WiniumWeb
{
WebDriver driver;
#BeforeClass
public void setUp() throws IOException
{
driver = new FirefoxDriver();
driver.navigate().to("http://the-internet.herokuapp.com/upload");
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\Resources\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists())
{
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try
{
driver = new WiniumDriver(new URL("http://localhost:9999"), null);
} catch (MalformedURLException e)
{
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException
{
String file = System.getProperty("user.dir") + "\\Resources\\TestData.csv";
WebElement window = driver.findElement(By.className("File Upload"));
window.findElement(By.className("#32770")).sendKeys(file);
Thread.sleep(2000);
}
}
if you are still finding solution.I am sharing my script which worked for me.
public class FileUpload extends BaseClass {
static WiniumDriver d;
#BeforeClass
public void setUp() throws IOException {
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
LaunchLocalBrowser("chrome","http://the-internet.herokuapp.com/upload");//use your own code to launch browser
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\lib\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try {
d = new WiniumDriver(new URL("http://localhost:9999"),options);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException {
String file = System.getProperty("user.dir") + "\\lib\\Testdata.txt";
d.findElementByName("File name:").sendKeys(file);
d.findElementByXPath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']").click();
driver.findElement(By.id("file-submit")).click();
}
}
File upload using WiniumDriverService by referring to port- 9999. Creating winium instance using free port having issues. Below code is intended for sample implementation of Browser factory to facilitate web and desktop instances.
public class FactoryManager {
public static ClientFactory getIndividualProduct(EnumProductLists product) {
ClientFactory factory = null;
if (null != product) {
switch (product) {
case CHROME:
factory = new ProductChromeClient();
break;
case DESKTOP:
factory = new ProductWiniumClient();
break;
default:
break;
}
}
return factory;
}
}
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
public class ProductWiniumClient extends ClientFactory {
private WiniumDriverService service;
#Override
protected void startService() {
if (null == service) {
service = new WiniumDriverService.Builder()
.usingDriverExecutable(
new File(System.getProperty("user.dir") + "/WiniumFolder/Winium.Desktop.Driver.exe"))
.usingPort(9999).withVerbose(true).buildDesktopService();
try {
service.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void createService() {
startService();
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
deskClient = new WiniumDriver(service, options);
}
#Override
protected void stopService() {
if (null != service && service.isRunning()) {
service.stop();
}
}
}
public class TestCase1 {
WebDriver webClient;
WiniumDriver deskClient;
ClientFactory lists;
#BeforeTest
public void beforeTest() {
lists = FactoryManager.getIndividualProduct(EnumProductLists.CHROME);
webClient = (WebDriver) this.lists.getClient(WebDriver.class.getTypeName());
lists = FactoryManager.getIndividualProduct(EnumProductLists.DESKTOP);
deskClient = (WiniumDriver) this.lists.getClient("");
}
#Test
public void f() {
if (null != webClient) {
try {
webClient.manage().window().maximize();
webClient.get("https://uploadfiles.io/");
webClient.findElement(By.id("upload-window")).click();
String file = System.getProperty("user.dir") + "\\files\\upload.txt";
deskClient.findElement(By.name("File name:")).sendKeys(file);
deskClient.findElement(By.xpath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']")).click();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Client Instance is Null!");
}
}
#AfterTest
public void afterTest() {
}
}

Parameterized runner class with 2 arguments in constructor

I wish to use a Parameterized Junit class to read from a .csv file. I want to:-
Read a 'placeID' (a String) and append it to a base url to form a webpage
Assert that the Place name 'name' (a String) is as I expect it to be for the place
The tab delimited .csv file contains 2 records as follows (will have 100's records eventually):
132
The Big House
I'm currently getting an Illegal argument exception. What's a slicker way of achieving this? I guess having the relative URL and then test data in seperate files would be better.
My code:
#RunWith(Parameterized.class)
public class PlaceTest {
public static WebDriver driver;
private String placeId;
private String name;
private PropertyPage propertyPage;
public PlaceTest(String page, String name) {
this.placeId = page;
this.name = name;
}
#Parameterized.Parameters
public static Collection data() {
return csvFileAsCollectionOfStringArrays(
System.getProperty("user.dir") +
"/src/test/resources/" +
"place_ids.csv");
}
private static Collection<String[]> csvFileAsCollectionOfStringArrays(String csvFileName) {
List<String[]> csvRows = new ArrayList<String[]>();
String rawCSVRow;
BufferedReader csvFileReader = null;
String delimiter = "\t";
System.out.println("Reading data from " + csvFileName);
try {
csvFileReader = new BufferedReader(new FileReader(csvFileName));
} catch (FileNotFoundException e) {
System.out.println("Could not find file " + csvFileName);
e.printStackTrace();
}
int rowNumber = 1;
try {
if (csvFileReader != null) {
while ((rawCSVRow = csvFileReader.readLine()) != null) {
String delimitedItems[] = rawCSVRow.split(delimiter);
csvRows.add(delimitedItems);
rowNumber++;
}
}
} catch (IOException e) {
System.out.println("Error reading row number " + rowNumber);
e.printStackTrace();
}
try {
assert csvFileReader != null;
csvFileReader.close();
} catch (IOException e) {
System.out.println("Error closing file " + e.getMessage());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return csvRows;
}
#BeforeClass
public static void startDriver() {
driver = Driver.get();
}
#Before
public void getNextPage() {
propertyPage = new PropertyPage(driver);
driver.get(TestWebApp.getURL() + this.placeId);
}
#Test
public void checkNamePresent() {
WebElement placeName = propertyPage.checkName();
assertEquals("Expected match on name", this.name, placeName.getText());
}
#AfterClass
public static void quitDriver() {
driver.quit();
}
}
Try this:
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import au.com.bytecode.opencsv.CSVReader;
#RunWith(Parameterized.class)
public class PlaceTest {
private String placeId;
private String name;
public PlaceTest(String page, String name) {
this.placeId = page;
this.name = name;
}
#Parameterized.Parameters
public static Collection<String[]> data() {
CSVReader reader = new CSVReader(new InputStreamReader(PlaceTest.class.getResourceAsStream("place_ids.csv")));
List<String[]> lines;
try {
lines = reader.readAll();
return lines;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ArrayList<String[]>();
}
#Test
public void checkNamePresent() {
System.out.println(this.placeId + " " + this.name);
}
}
The place_ids.csv has to be in: \src\test\resources\<your package>\place_ids.csv
Update your pom with CSVReader dependency:
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.3</version>
</dependency>
Update:
csv file:
132, Some text
133, Other text
Your example above has one word per line. The code above was compile and tested.

How to access and ArrayList inside another class inside multiple try's?

I have a homework to retrieve a myqsl query and save it to a ArrayList , and then to link it to another class and then serialize it and send it through http,
In a scheme it would be
class Server{static class a {try{try{ try{arraylist1} }}}}
class b {var1,var2,link_to(arraylist1)}
then serialize class b and send it
i managed to take the sql query and save the objects in the ArrayList (objects created from class "Personat") through
if (rs != null) {
List<Personat> perList = new ArrayList<Personat>();
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("var1"));
per.setName(rs.getString("var2"));
per.setAmount(rs.getInt("var3"));
perList.add(per);
}
}
Where rs=ResultSet object
but i cant access the ArrayList from class b so i can serialize it. I have tried to make it static (nothing ,it cant be linked).I have tried to make a getter (yet nothing eclipse wont let me as i automatically generate them).
So i don't know what i should do ! Can someone help me ? Or does anyone have any idea?
i have tried to search google for this but as you can see is a little too specific so no results until now ....
here is my Server.java
package server2;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server {
private static List<Personat> perList = new ArrayList<Personat>();
//need to access this in the SendRes class
public List<Personat> getPerList() {
return perList;
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
}
static public class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
ObjectInputStream ios = new ObjectInputStream(t.getRequestBody());
//
final String url = "jdbc:mysql://localhost/httpServer";
final String user = "root";
final String password = "";
try {
Send oin = (Send) ios.readObject();
int id = oin.getId();
String emri = oin.getName();
int amount = oin.getAmount();
int paid = oin.getPaid();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user,
password);
try {
PreparedStatement s = con
.prepareStatement("INSERT INTO person(ID,Name,Amount,Paid) VALUES (?,?,?,?)");
s.setInt(1, id);
s.setString(2, emri);
s.setInt(3, amount);
s.setInt(4, paid);
s.executeUpdate();
ResultSet rs = s.executeQuery("SELECT * "
+ "from personat ORDER BY EmpId");
if (rs != null) {
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("ID"));
per.setName(rs.getString("Name"));
per.setAmount(rs.getInt("Amount"));
perList.add(per);
}
}
//here i need to send an SendRes object with the ArrayList inside it
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
class SendResponse implements Serializable {
String gabim;
String gabimNr;
//link the arraylist from class server here
}
class Personat {
int ID;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
String Name;
int Amount;
}
Objects of type B can only access the public members of type A. To get access to your list you need to make it a public member of A. The typical way to do this is to use a private field and a public getter.
class A
{
private List<Personat> personList;
public List<Personat> getPersonList() { return personList; }
public void handle(HttpExchange t) throws IOException
{
// ...
personList = ...;
// ...
}
}
Note that by giving public access to your list you are also allowing clients to modify the contents of the list. You may prefer to give them a copy of the list if this is not desirable.
On a slightly unrelated note, if you three nested try blocks in a single method then that method is probably too complex and should be refactored into smaller methods.

Categories