ElasticSearch Multiget issue in Java - 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();
...

Related

How to access an object attribute from a String in Java?

I have a String that tells me what attribute I should use to make some filtering. How can I use this String to actually access the data in the object ?
I have a method that returns a List of strings telling me how to filter my List of objects. Such as:
String[] { "id=123", "name=foo" }
So my first idea was to split the String into 2 parts with:
filterString.split("=") and use the first part of the String (e.g. "id") to identify the attribute being filtered.
Coming for a JS background, I would do it like this:
const attr = filterString.split('=')[0]; // grabs the "id" part from the string "id=123", for example
const filteredValue = filterString.split('=')[1]; // grabs the "123" part from the string "id=123", for example
items.filter(el => el[`${attr}`] === filteredValue) // returns an array with the items where the id == "123"
How would I be able to do that with Java ?
You can use reflections to get fields of class by dynamic name.
#Test
void test() throws NoSuchFieldException, IllegalAccessException {
String[] filters = {"id=123", "name=foo"};
List<Item> list = newArrayList(new Item(123, "abc"), new Item(2, "foo"), new Item(123, "foo"));
Class<Item> itemClass = Item.class;
for (String filter : filters) {
String key = StringUtils.substringBefore(filter, "=");
String value = StringUtils.substringAfter(filter, "=");
Iterator<Item> iterator = list.iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
Field field = itemClass.getDeclaredField(key);
field.setAccessible(true);
Object itemValue = field.get(item);
if (!value.equals(String.valueOf(itemValue))) {
iterator.remove();
}
}
}
assertEquals(1, list.size());
}
But I agree with comment from sp00m - it's slow and potentially dangerous.
This code should work :
//create the filter map
Map<String, String> expectedFieldValueMap = new HashMap<>();
for (String currentDataValue : input) {
String[] keyValue = currentDataValue.split("=");
String expectedField = keyValue[0];
String expectedValue = keyValue[1];
expectedFieldValueMap.put(expectedField, expectedValue);
}
Then iterate over input object list ( have used Employee class with id and name fields & prepared a test data list with few Employee objects called inputEmployeeList which is being iterated ) and see if all filters passes, using reflection, though slow, is one way:
for (Employee e : inputEmployeeList) {
try {
boolean filterPassed = true;
for (String expectedField : expectedFieldValueMap.keySet()) {
String expectedValue = expectedFieldValueMap.get(expectedField);
Field fieldData = e.getClass().getDeclaredField(expectedField);
fieldData.setAccessible(true);
if (!expectedValue.equals(fieldData.get(e))) {
filterPassed = false;
break;
}
}
if (filterPassed) {
System.out.println(e + " object passed the filter");
}
} catch (Exception any) {
any.printStackTrace();
// handle
}
}

Return records in 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.

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.

.equal in strings from json?

I'm trying some code where I want to compare strings i've grabbed from json to certain values. However the if statements never trigger. I have confirmed the values of the instances are set properly, and can be printed out.
//MAKING CLASSES
Collection collection = new ArrayList();
Event ev = new Event();
ev.name = "sven";
ev.source = "src10";
Event2 ev2 = new Event2();
ev2.name = "type";
ev2.data = "somedata";
collection.add(ev);
collection.add(ev2);
//MAKING A BUNCH OF CLASSES TO JSON
Gson gson = new Gson();
String json = gson.toJson(collection);
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();
//JSON TO JAVA
for (int i = 0; i < array.size(); i++) {
JsonObject nameObject = array.get(i).getAsJsonObject();
String nameString = nameObject.get("name").toString();
if (nameString.equals("sven")) {
System.out.println("this is sven");
Event event = gson.fromJson(array.get(i), Event.class);
}
else if (nameString.equals("type")) {
System.out.println("this is type");
Event2 event2 = gson.fromJson(array.get(i), Event2.class);
}
else{
System.out.println("nothing");
}
}
According Gson API your call to 'nameObject.get("name")' will return JsonElement. This means you should use 'getAsString()' method instead of 'toString()':
String nameString = nameObject.get("name").getAsString();
'toString()' method is designed (in general) for debugging purposes. And should be used very carefully in program logic.
You need to know that the implementation of toString() in JsonElement class is such that it will return the String inclusive of "".
To make it easier to understand look into the following code
JsonObject json = new JsonObject();
json.addProperty("hello", "tata");
System.out.println(json.get("hello").toString()); // Prints "tata"
System.out.println(json.get("hello").getAsString()); // Prints tata
so internally your code is comparing "sven" and sven which will return not equal

Simplest way to strip an int out of a URL in Java?

I have a String containing a URL. I want to get just one piece of data out of it: an int that should be showing up in the query string.
So if the url is:
http://domain.tld/page.html?iVar=123
I want to get "123" into an int.
What's the most elegant way you know to do this?
You could try matching just that parameter in the URL string:
public static Integer getIVarParamValue(String urlStr) {
Pattern p = Pattern.compile("iVar=(\\d+)");
Matcher m = p.matcher(urlStr);
if (m.find()) {
return Integer.parseInt(m.group(1));
}
return null;
}
It seems you want to obtain get parameters and parse them. I have this method here (got it from somewhere on SO, I guess):
public static Map<String, List<String>> getQueryParams(String url) {
try {
Map<String, List<String>> params = new HashMap<String, List<String>>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
}
return params;
} catch (UnsupportedEncodingException ex) {
throw new AssertionError(ex);
}
}
So:
String var = WebUtils.getQueryParams(url).get("iVar");
int intVar = Integer.parseInt(var);
You can use the URL class.
i.e.:
URL myUrl = new URL("http://domain.tld/page.html?iVar=123");
String query = myUrl.getQuery(); //this will return iVar=123
//at this point you can either parse it manually (i.e. use some of the regexp in the other suggestions, or use something like:
String[] parts = query.split();
String variable = parts[0];
String value = parts[1];
This will work only for this case though and won't work if you have additional params or no params.
There are a number of solution that will split it into a param map online, you can see some here.
If it's really as simple as you describe: There is only 1 int in your URL and all you want is that int, I'd go for a regular expression. If it is actually more complicated see the other answers.
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher("http://domain.tld/page.html?iVar=123");
if (m.find())
System.out.println(m.group());
This also could do the work :
public static int getIntParam(HttpServletRequest request, String name, int defaultValue) {
String value = request.getParameter(name);
try {
if (value != null) {
return Integer.valueOf(value);
}
} catch (NumberFormatException e) {
}
return defaultValue;
}
Hope it helps!
If the query string part of the URL is always the same (so if it was always iVar) you could use urlAsString.indexOf("iVar=") to find iVar= and then knowing the number is after that, extract the number. That is admittedly not the least brittle approach.
But if you're looking for all the query strings then Bozho's answer is much better.

Categories