Return records in java - java

I need to return multiple records in to a variable, in below mention code with in while loop I am getting all the records but while return result I am getting only one record I don't know how to do
public String feed()
{
String projectname=null;
String claintid=null;
String projectstatus=null;
String prjstartdate=null;
String prjenddate=null;
String lastmodified=null;
String prjpinurl=null;
String patientDetails=null;
try
{
Connection conn = getMySqlConnection();
String simpleProc = "{ call Sp_RetPrjvals () }";
CallableStatement cs = conn.prepareCall(simpleProc);
ResultSet rs=(ResultSet) cs.executeQuery();
while(rs.next()){
projectid=rs.getString(1);
projectname=rs.getString(2);
claintid=rs.getString(3);
projectstatus=rs.getString(4);
prjstartdate=rs.getString(5);
prjenddate=rs.getString(6);
lastmodified=rs.getString(7);
prjpinurl=rs.getString(8);
patientDetails=projectid+"|"+projectname+"|"+claintid+"|"+projectstatus+"|"+prjstartdate+"|"+prjenddate+"|"+lastmodified+"|"+prjpinurl;
//here i am getting two values before:::2|Sample project 2|1|WIP|2015-08-01 00:00:00.0|2016-08-01 00:00:00.0|2015-08-24 16:40:10.0|http://hcup-us.ahrq.gov/toolssoftware/ccs/ccs.jsp
before:::1|Sample project 1|1|WIP|null|null|2015-08-24 16:38:39.0|http://hcup-us.ahrq.gov/toolssoftware/ccs/ccs.jsp
}
conn.close();
} catch (Exception e)
{
}
return patientDetails;
// here i am getting only After:::1|Sample project 1|1|WIP|null|null|2015-08-24 16:38:39.0|http://hcup-us.ahrq.gov/toolssoftware/ccs/ccs.jsp
}

The problem is that you override your String. You have to add it to a list or an array.
For example: List<String> al = new ArrayList<String>()
and then you have to add the String you build on every while step into this array and retrun this array:
al.add(patientDetails);
your return statement follows this: return al;
your function header is then:
public List<String> feed(){

patientDetails is a `String` Object.
If you expet to be able to retun a list of striong, then you should use an array of String objects in that case.
Something like:
String[] patientDetails
Then in your code you should add each returned record to your array
Something like:
patientDetails[i] = projectid+"|"+projectname+"|"+claintid+"|"+projectstatus+"|"+prjstartdate+"|"+prjenddate+"|"+lastmodified+"|"+prjpinurl;
i ++; //Initialize this *i* variable outside the while
Also change the signature of your method as:
public String[] feed()

Because you don't know your result size, you need a dynamic structure, like a list:
List<String> pacients = new ArrayList<>();
while(results.next()){
...
String patientDetails = ....;
pacients.add(patientDetails);
}
After this code you will have alist of pacient details. But I would advise you to keep their data in an object, not a String;
class PatientDetails {
String projectname; // you don't have to initialize with null, it's done by default
String claintid;
String projectstatus;
String prjstartdate;
String prjenddate;
String lastmodified;
String prjpinurl;
String patientDetails;
// getters & setters
#Override
public String toString(){
return projectid+"|"+projectname+"|"+claintid+"|"+ ...;
}
}
Now when you will want to print a PatientDetails you will get same result as your string representation.
And you would return a List<PatientDetails> holding your query results.

Related

Passing dynamic method name to another method as parameter in java

I have a calling method as genJsonPayload(). Inside this method I am calling a replace() method to replace some string with randomly generated values. I want to call the replace() by passing another method as parameter. My sample code below.
public static StringBuffer replace(String jsonparam, StringBuffer jsondata, String replacedWith) {
int start = 0;
int last = 0;
while (jsondata.indexOf(jsonparam)!= jsondata.lastIndexOf(jsonparam)) {
start = jsondata.indexOf(jsonparam);
last = start + jsonparam.length();
jsondata = jsondata.replace(start,last,replacedwith);
}
start = jsondata.indexOf(jsonparam);
last = start + jsonparam.length();
jsondata = jsondata.replace(start,last,replacedwith);
return jsondata;
}
public String genJSONPayload(String jsonpayload) {
StringBuffer sbuffer = new StringBuffer(jsonpayload);
try {
jsondata = replace("expectedAreaCode",jsondata, CreateRandom.createAreaCDRandom());
}
catch (Exception e) {
....
}
try {
jsondata = replace("expectedextensionNo",jsondata, CreateRandom.createExtensionNumberRandom());
}
catch (Exception e) {
....
}
}
Json payload as below :
{
...
...
"phonenumber": [
{
"areaCode": "expectedAreaCode",
"extensionNo": "expectedextensionNo",
...
}
{
"areaCode": "expectedAreaCode",
"extensionNo": "expectedextensionNo",
...
}
{
"areaCode": "expectedAreaCode",
"extensionNo": "expectedextensionNo",
...
}],
...
...
}
Note :
CreateRandom.createAreaCDRandom() return a random String.
Problem statement :
My requirement is to replace "expectedAreaCode" of json file with randomly generated area code using the replace() method. But as I am executing the CreateRandom.createAreaCDRandom() from genJSONPayload() only once so replacedWith in replace() method is getting store with fixed area code and for all the area code in the json array phonenumber, I am getting the same areacode.
Question :
Instead of passing the replacedWith String to the replace() method, can I pass the createAreaCDRandom() static method as parameter and instead of executing createAreaCDRandom() method from genJSONPayload, then I will execute it inside replace method multiple times inside the while loop. I have more than 5 such random mentods, basically for different json parameters.
How can I pass the createAreaCDRandom(), createExtensionNumberRandom(), etc methods as the parameter in the repace() method?
Use Supplier class as a method parameter (https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html).
Then You can pass lambda or method reference to provide value generating logic.
public static StringBuffer replace(String jsonparam, StringBuffer jsondata, Supplier<String> supplier) {
int start = 0;
int last = 0;
while (jsondata.indexOf(jsonparam) != jsondata.lastIndexOf(jsonparam)) {
start = jsondata.indexOf(jsonparam);
last = start + jsonparam.length();
jsondata = jsondata.replace(start, last, supplier.get());
}
start = jsondata.indexOf(jsonparam);
last = start + jsonparam.length();
jsondata = jsondata.replace(start, last, supplier.get());
return jsondata;
}
public String genJSONPayload(String jsonpayload) {
StrignBuffer sbuffer = new StrignBuffer(jsonpayload);
try{
jsondata = replace("expectedAreaCode",jsondata, CreateRandom::createAreaCDRandom);
}
catch(Exception e){
....
}
try{
jsondata = replace("expectedextensionNo",jsondata, CreateRandom::createExtensionNumberRandom);
}
catch(Exception e){
....
}
}

How to access and read the values of child objects of an object?

Here is how I am constructing an Object inside a method:
//right after creating the class
public static ArrayList<Object> old_devicelist = new ArrayList<Object>();
//inside a method
Date date = new Date();
long time = date.getTime();
Integer opened = 0;
String deviceId = "";
String dev_rssi = "";
Object[] MyObject = new Object[]{time, opened, deviceId, dev_rssi};
old_devicelist.add(MyObject);
Now, I would like to loop through that ArrayList and access some elements (note that deviceId might at some point contain an object and I would like to access id field of it) inside it, then I would like to use them like this, for ex. :
if(device.id == 33){
//do something...
}
You're using an array with type Object and then you're storing these object arrays into a list. This makes it hard to retrieve the information later.
Consider this instead:
public static List<Device> DEVICES = new ArrayList<>();
class Device {
Date date;
long time;
Integer opened;
String deviceId;
String deviceRssi
Device(Date date, Integer opened, String deviceId, String deviceRssi) {
this.date = date;
this.time = date.getTime();
this.opened = opened;
this.deviceId = deviceId;
this.deviceRssi = deviceRssi;
}
}
Device first = new Device(
new Date(),
0,
"",
"");
DEVICES.add(first);
System.out.println(DEVICES.get(0).deviceId);
...
for (Device device : DEVICES) {
if (device.deviceId.equals("33)) {
// ...
}
}
I'd recommend not using too many static/global variables and reading about the Java Naming Convention.
I guess you should create new class instead of using Object.
public class DeviceSpecification { //or any other name
long time;
Integer opened;
String deviceId;
String dev_rssi;
public DeviceSpecification(long time, Integer opened, String deviceId, String dev_rssi) {
this.time = time;
this.opened = opened;
this.deviceId = deviceId;
this.dev_rssi = dev_rssi;
}
}
Create a list with specific type:
public static List<DeviceSpecification> oldDeviceCollection = new ArrayList<>();
Create an instance of a class
DeviceSpecification device = new DeviceSpecification(new Date().getTime(), 0, "", "")
Add the instance to a list
oldDeviceCollection.add(device);
Use it in query - we can use streams from Java 8
oldDeviceCollection.stream()
.forEach(
device -> {
if(device.id.equals("33")) {
// do something
}
);
First of all your Arraylist takes Objects and you are trying to add an Object array so if your goal is to keep object arrays with the device_id you should change your Arraylist to
public static ArrayList<Object[]> old_devicelist = new ArrayList();
Taking that in mind you can access any deviceid by typing
old_devicelist.get(i)[2]
where i is the element you want and 2 because you have setted device_id to be the 3rd element of your Object array!
Hope this helps!

ElasticSearch Multiget issue in Java

I am new to Java programming and need some help here.
I am running below code and getting appropriate response i.e.
{"name1":"Name2","date1":"2016-05-13","message1":"Message2"}
{"name1":"Name0","date1":"2016-05-13","message1":"Message0"}
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa").get();
for(MultiGetItemResponse itemResponse: multiGetItemResponses){
GetResponse response2 = itemResponse.getResponse();
if(response2.isExists()){
String json2 = response2.getSourceAsString();
System.out.println(json2);
}
}
however, when i am trying to parameterise the search text, its not returning any value. Can anyone please guide what might be going wrong here? I have checked that variable abc is returning correct value i.e. "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa"
public static boolean getData(String ids){
String idAry[] = ids.split(",");
ArrayList<String> idStr = new ArrayList<String>();
for (String id:idAry){
idStr.add('"'+id+'"');
}
String abc = idStr.toString().replace("[", "").replace("]", "");
System.out.println(abc);
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", abc).get();
// MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
// .add("loc", "message", "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa").get();
//
for(MultiGetItemResponse itemResponse: multiGetItemResponses){
GetResponse response2 = itemResponse.getResponse();
if(response2.isExists()){
String json2 = response2.getSourceAsString();
System.out.println(json2);
}
}
return true;
}
You don't need the abc variable, i.e. you don't need to transform your list to string. You simply need to construct your query like this, by passing idList to your add() call as this call will take the index, the type and an Iterable<String>, so the idList already fits the job.
public static boolean getData(String ids){
String idAry[] = ids.split(",");
List<String> idList = Arrays.asList(idAry);
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", idList).get();
...

java foreach database List value

data is selecte all users in database
it will print out:
[com.test.abc.user.domain.User#b22379c, com.test.abc.user.domain.User#364b96e5, com.test.abc.user.domain.User#1c9fb03c, com.test.abc.user.domain.User#37eb41d2]
I want to know how can I get the value in it .
I want to make it to json string like str so that the front end can get it
Please help me !!
#ResponseBody
public String getList() {
List<User> data = memberObj.getCurrentMembers() ;
System.out.println(data);
//data to string
String str = "{\"data\": [{\"id\": \"1\",\"account\": \"a#gmail.com\",\"name\": \"sky\",\"nick\": \"abc\"}]}";
return str;
}
Use google gson library
List<User> list = new ArrayList<User>();
list.add(new User());
list.add(new User());
String json = new Gson().toJson(list);
You need to give your User class a toString() method.
class User {
String name;
#Override
public String toString() {
return name;
}
}
When you printout data with
System.out.println(data)
you just print out the structure, not the objects in it.
Additionaly, you do the same here:
String str = "{\"data\": [{\"id\": \"1\",\"account\": \"a#gmail.com\",\"name\": \"sky\",\"nick\": \"abc\"}]}";
you just return an object not a value, you have to do this with a for or while loop.

Passing data to an object

I'll list my code at the bottom, but here's the deal.
I have a parser class with a process method. This method scrapes data from a web page. I want to take each line of the scrape, split the string into an array and add the values to an object, then add the object to an ArrayList. As the loop iterates, new values from each line of the scrape are added to an ArrayList via the object. The relevent method in this code is public ArrayList process()
I'm getting the following compile errors:
The constructor Flight(String) is undefined
Syntax error on token "[", Expression expected after this token
The method add(String) in the type ArrayList is not applicable for the arguments (Flight)
What am I doing wrong here, and how do if fix it?
public class HtmlParser {
public String url;
public String airline;
public static String lastFlight;
static ArrayList<String> capture = new ArrayList<String>();
public HtmlParser(Properties config) throws IOException{
url = config.getProperty("url");
airline = config.getProperty("airline");
print("Fetching.........%s" , url);
}
public ArrayList<String> process() throws IOException{
Document doc = Jsoup.connect(url).get();
Elements tableRow = doc.getElementsByTag("tr");
for(Element tr : tableRow){
if(tr.text().contains(airline)){
String delims = "[ ]+";
String singleRowArray[] = tr.text().split(delims);
Flight f = new Flight(singleRowArray[]);
capture.add(f);
}
}
return capture;
}
Here's my flight Class.
public class Flight {
public Flight(String singleRowArray[]) {
String origin = singleRowArray[0];
String airline1 = singleRowArray[1];
String airline2 = singleRowArray[2];
String flightNo = singleRowArray[3];
String date = singleRowArray[4];
String ArrTime = singleRowArray[5];
String status = singleRowArray[6];
}
}
"The constructor Flight(String) is undefined Syntax error on token "[", Expression expected after this token"
Try switching the brackets to the type, not the variable: String[] singleRowArray
"The method add(String) in the type ArrayList is not applicable for the arguments (Flight)"
You have a List<String> where you want to input an object of type Flight, so you should change the list type to List<Flight>.
static ArrayList<String> capture = new ArrayList<String>();
You can't add the Flight class object in capture list which can only contain element in String type.
Flight f = new Flight(singleRowArray[]);
capture.add(f); // Issue
-----------------^

Categories