About inserting dynamic data into the static content at run time - java

I have a template like this in properties file: Dear xxxxxx, you are payment is succesfull.
After loading this template from properties file, I want to replace that "xxxxxx" with dynamic data in Java class.
Please help me on this.

I used Message.format("template",object array which is having dynamic data);

Try this way
placeholderReplacementMap is map that contain your static value and dynamic value key pair
Map<String, Object> placeholderReplacementMap = new HashMap<>();
StrSubstitutor substitutor = new StrSubstitutor(placeholderReplacementMap);
placeholderReplacementMap.put("xxxxxx", dynamicValue);
String newString = substitutor.replace("Dear xxxxxx","you are payment is succesful");

Related

Query Json Objects using Hazelcast SqlPredicate

I'm using hazelcast in memory in my application.
Can anyone please explain how to query JSON objects using hazelcast..
map(String, new(HazelcastJsonValue());
In the value i'm storing entire JSON.
Storing JSON one by one in value:-
{"id":"01","name":"abc"}
{"id":"02","name":" data"}
{"id":"03","name":"abc"}
query:- name='abc'
Selecting based on the name
query:- name='abc'
Expecting output:-
{"id":"01","name":"abc"}
{"id":"03","name":"abc"}
how to do this using hazelcast?
Thank you.
This link (sent by #Neil) is good. In your case, it will look like this:
HazelcastInstance instance = Hazelcast.newHazelcastInstance();
String item1 = "{\"id\":\"01\",\"name\":\"abc\"}";
String item2 = "{\"id\":\"02\",\"name\":\" data\"}";
String item3 = "{\"id\":\"03\",\"name\":\"abc\"}";
IMap<String, HazelcastJsonValue> map = instance.getMap("jsonValues");
map.put("1", new HazelcastJsonValue(item1));
map.put("2", new HazelcastJsonValue(item2));
map.put("3", new HazelcastJsonValue(item3));
Collection<HazelcastJsonValue> selected = map.values(Predicates.equal("name", "abc"));
System.out.println(selected);

Convert IniPreferences to Map?

How would I convert IniPreferences to a Map in Java?
I currently have
public static Map<String, String> configMap;
Ini ini = new Ini(configIni);
java.util.prefs.Preferences prefs = new IniPreferences(ini);
configMap = new HashMap<>();
configMap.put("Version", prefs.node("Settings").get("Version", null));
However this would require me to insert the key for anything added to the ini making it a pain to maintain.
The prefs.node will always be settings however preferably they would be combined into configMap.
How would I automate this?

how to manipulate HTTP json response data in Java

HttpGet getRequest=new HttpGet("/rest/auth/1/session/");
getRequest.setHeaders(headers);
httpResponse = httpclient.execute(target,getRequest);
entity = httpResponse.getEntity();
System.out.println(EntityUtils.toString(entity));
Output as follows in json format
----------------------------------------
{"session":{"name":"JSESSIONID","value":"5F736EF0A08ACFD7020E482B89910589"},"loginInfo":{"loginCount":50,"previousLoginTime":"2014-11-29T14:54:10.424+0530"}}
----------------------------------------
What I want to know is how to you can manipulate this data using Java without writing it to a file?
I want to print name, value in my code
Jackson library is preferred but any would do.
thanks in advance
You may use this JSON library to parse your json string into JSONObject and read value from that object as show below :
JSONObject json = new JSONObject(EntityUtils.toString(entity));
JSONObject sessionObj = json.getJSONObject("session");
System.out.println(sessionObj.getString("name"));
You need to read upto that object from where you want to read value. Here you want the value of name parameter which is inside that session object, so you first get the value of session as JSONObject using getJSONObject(KeyString) and read name value from that object using function getString(KeyString) as show above.
May this will help you.
Here's two ways to do it without a library.
NEW (better) Answer:
findInLine might work even better. (scannerName.findInLine(pattern);)
Maybe something like:
s.findInLine("{"session":{"name":"(\\w+)","value":"(\\w+)"},"loginInfo":{"loginCount":(\\d+),"previousLoginTime":"(\\w+)"}}");
w matches word characters (letters, digits, and underscore), d matches digits, and the + makes it match more than once (so it doesnt stop after just one character).
Read about patterns here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
OLD Answer:
I'm pretty sure you could use a scanner with a custom delimiter here.
Scanner s = new Scanner(input).useDelimiter("\"");
Should return something like:
{
session
:{
name
:
JSESSIONID
,
value
:
5F736EF0A08ACFD7020E482B89910589
And so on. Then just sort through that list/use a smarter delimiter/remove the unnecessary bits.
Getting rid of every other item is a pretty decent start.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html has info on this.
I higly recomend http-request built on apache http api.
private static final HttpRequest<Map<String, Map<String, String>>> HTTP_REQUEST = HttpRequestBuilder.createGet(yourUri, new TypeReference<Map<String, Map<String, String>>>{})
.addDefaultHeaders(headers)
.build();
public void send(){
ResponseHandler<Map<String, Map<String, String>>> responseHandler = HTTP_REQUEST.execute();
Map<String, Map<String, String>> data = responseHandler.get();
}
If you want use jackson you can:
entity = httpResponse.getEntity();
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, String>> data = mapper.readValue(entity.getContent(), new TypeReference<Map<String, Map<String, String>>>{});

Rendering a filled form in the template

I'm using Play! framework 20 on a java project and I have a problem with passing a form to the view.
In the controller I have the following code:
Filter filter = new Filter();
//add some state to the filter object
Form<Filter> filterForm = form(Filter.class).fill(filter);
Logger.info("FilterForm: " + filterForm.get().toString()); // So far so good
return ok(filterView.render(filterForm));
And in the template:
#filterForm.hasErrors() // renders false
#filterForm.data().isEmpty() // renders true!!
#* #filterForm.get().toString() *# throws an Exception: No Value
I also get the same error if in the controller I fill the filter state via a Map:
filterForm = filterForm.bind(aMapWithTheState);
This behaviour is only when filling the filter in code. when I do filterForm.bindFromRequest() in other methods all works fine.
Thanks!!
Solved.
I had to use the form's bind method using a map with the state as I did before. But the correct way is to also pass the properties name:
Map<String, String> formState = new HashMap<String, String>();
formState.put("name", name);
formState.put("birthDate", birthDate);
formState.put("address", address);
filterForm = filterForm.bind(formState, "name", "birthDate", "address");
Despite that the documentation says that the property names are not mandatory.

Java ArrayList into Name value pair

In a java class, am using an arraylist say reports containing list of all the reports which have reportid, reportname, reporttype etc which i want to add into NameValuePair and send a Http postmethod call to a particular url.
I want to add the arraylists - reportname into name value pair(org.apache.commons.httpclient.NameValuePair) and then use the http client post method to submit the name value pair data to a particular url.
Here is my name value pair
if (validateRequest()) {
NameValuePair[] data = {
new NameValuePair("first_name", firstName),
new NameValuePair("last_name", lastName),
new NameValuePair("email", mvrUser.getEmail()),
new NameValuePair("organization", mvrUser.getOrganization()),
new NameValuePair("phone", mvrUser.getPhone()),
new NameValuePair("website", mvrUser.getWebsite()),
new NameValuePair("city", mvrUser.getCity()),
new NameValuePair("state", mvrUser.getState()),
new NameValuePair("country", mvrUser.getCountry()),
new NameValuePair(**"report(s)", reports**.)
};
please suggest me how to add the reports arraylist reportname into reports field of NameValuePair.
--
thanks
# adarsh
can I use with generics something like this?
reportname = "";
for (GSReport report : reports) {
reportname = reportname + report.getReportName();
reportname += ",";
}
and then add in namevalue pair as
new NameValuePair("report(s)", reportname)
for name value pair use map like things... eg. Hastable(it is synchronized) , u can use other
implementation of Map which are not synchronized.
I suggest to serialize your reports ArrayList into a JSON formatted String.
new NameValuePair("reports", reportsAsJson)
You can build your reportsAsJson variable using any of the JSON serialization libraries (like the one at http://json.org/java/). It will have approximatively this format :
reportsAsJson = "[{reportid:'1',reportname:'First Report',reporttype:'Type 1'}, {reportid:'2',reportname:'Seond Report',reporttype:'Type 2'}]";
Well, you cannot do that. NameValuePair takes in String arguments in the constructor. It makes sense as it is used for HTTP POST.
What you can do is come up with a way to serialize the Report object into String and send this string as a string parameter. One way of doing this maybe is to delimit the parameters of the Report class.
reports=reportName1|reportName2|reportName3
Assuming reports is your ArrayList,
String reportsStr = "";
for(int i = 0; i < reports.size(); i++) {
reportStr += reportName;
if(i != reports.size() - 1) {
reportsStr += "|";
}
}
NameValuePair nvPair = new NameValuePair("reports", reportsStr);

Categories