How to pass parameters to a cypher using IN operator? - java

We are using Neo4j 2.0 RC1 embedded in our java server. We parametrize the variables in our cyphers. One of our cyphers uses IN clause e.g.
MATCH (a) WHERE a.name IN ["Peter", "Tobias"] RETURN a
So i tried something like this:
String cypher = "MATCH (a) WHERE a.name IN {names} RETURN a";
Map<String, Object> params = new HashMap<>();
List<String> names = new ArrayList<>();
//add some names to the names list
params.put("names", names);
ExecutionResult result = engine.execute(cypher, params);
Its obviously not working, how do i parametrize IN operator ?

neo4j rocks !!
Things work as expected / desired. I got a bug elsewhere in the code otherwise the following snippet works just fine:
String cypher = "MATCH (a) WHERE a.name IN {names} RETURN a";
Map<String, Object> params = new HashMap<>();
List<String> names = new ArrayList<>();
//add some names to the names list
params.put("names", names);
ExecutionResult result = engine.execute(cypher, params);

Related

Handling data return types with Mybatis SQL Builder

I am relatively new to Java MyBatis. I came across SQL Builder class in MyBatis. However, I don't understand how to handle the result of the SELECT SQL query, especially if the columns are going to be different in each case while using SQL Builder. Is there an example which can help me understand how to write this?
Usually, I use Mapper XML files with ResultMap to retrieve the output of an SQL statement.
I figured out the way to get it to work. I am not sure if it is the correct way.
In the XML I made the following entry
<select id="readSignals" resultType="map">
${query}
</select>
The ${query} is passed from a QueryBuilder class and the resultType is set to "map". This cause myBatis to return a List> where each Map in the list is a row. The String contains the column name and Object contains the data.
I use the following code to convert the List> into JSON.
public static JSONObject convertToJSON(List<Map<String, Object>> queryData) {
JSONObject queryJSONOutput = new JSONObject();
JSONArray outputArray = new JSONArray();
queryData.stream().forEach(d -> {
JSONObject jsonObject = new JSONObject();
for (String key: d.keySet()) {
jsonObject.put(key, d.get(key));
}
outputArray.put(jsonObject);
});
queryJSONOutput.put("data", outputArray);
return queryJSONOutput;
}

MultiList not displaying all result from webservice (Codename One)

Im trying to display some json records using a MultiList. I followed what was done here https://www.codenameone.com/manual/graphics.html but mine is returning only one record (Please see this image). The response came from this webservice
Below is my code. Please kindly show me where i'm wrong.
#Override
protected void beforeFormA(Form f) {
Style s = UIManager.getInstance().getComponentStyle("Button");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 4), false);
getattractive();//fetch results from webservice and store inside response variable
ArrayList arr = (ArrayList) response.get("results");
for (Object m:arr){
Map ma = (Map)m;
address =(String) ma.get("formatted_address");
name=(String)ma.get("name");
icon=(String)ma.get("icon");
ArrayList<Map<String, Object>> data = new ArrayList<>();
data.add(createListEntry(name,address,icon));
DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
MultiList ml = new MultiList(model);
ml.getUnselectedButton().setIconName("icon_URLImage");
ml.getSelectedButton().setIconName("icon_URLImage");
ml.getUnselectedButton().setIcon(placeholder);
ml.getSelectedButton().setIcon(placeholder);
f.add(BorderLayout.CENTER, ml);
}
}
private Map<String, Object> createListEntry(String name, String addr, String coverURL) {
Map<String, Object> entry = new HashMap<>();
entry.put("Line1", name);
entry.put("Line2", addr);
entry.put("icon_URLImage", coverURL);
entry.put("icon_URLImageName", name);
return entry;
You should fix the indentation. The for loop encapsulates everything so you are looping over all the elements and for X elements you are adding X multi lists.
This is something you would instantly see if you step over the code with a debugger...
done. I moved the line below out of the method and place it inside the class.
ArrayList> data = new ArrayList<>();

Scan and filter on nested map attributes in DynamoDB with Java SDK

I have a JSON document stored in an attribute called doc that looks something like this:
{
doc:
{
"foo":
{
"bar": "baz"
}
}
}
I'd like to be able to do a table scan and filter/search on data.foo.bar == "baz". I'm using the Java SDK and have tried the following code but it doesn't seem to work for a sub-map of a document:
String filterExpression = "#d.#f.#b = :val";
Map<String, String> nameMap = new HashMap();
nameMap.put("#d", "doc");
nameMap.put("#f", "foo");
nameMap.put("#b", "bar");
Map valueMap = new HashMap();
valueMap.put(":val", "baz");
ItemCollection<ScanOutcome> items = table.scan(
new ScanSpec()
.withFilterExpression(filterExpression)
.withNameMap(nameMap)
.withValueMap(valueMap));
EDIT - I have found that this works:
String filterExpression = "#d.foo.bar = :val";
Where I only have a single ExpressionAttributeNames for the first attribute it works. Any thoughts why it doesn't work with 3 ExpressionAttributeNames? What if by some chance I needed 3, i.e. they were reserved words?
Any help or suggestions greatly appreciated. Thanks.

Get parameter names collection from Java/Android url

It's absolutely strange, but I can't find any Java/Android URL parser that will be compatible to return full list of parameters.
I've found java.net.URL and android.net.Uri but they are can't return parameters collection.
I want to pass url string, e.g.
String url = "http://s3.amazonaws.com/?AWSAccessKeyId=123&Policy=456&Signature=789&key=asdasd&Content-Type=text/plain&acl=public-read&success_action_status=201";
SomeBestUrlParser parser = new SomeBestUrlParser(url);
String[] parameters = parser.getParameterNames();
// should prints array with following elements
// AWSAccessKeyId, Policy, Signature, key, Content-Type, acl, success_action_status
Does anyone know ready solution?
There is way to get collection of all parameter names.
String url = "http://domain.com/page?parameter1=value1&parameter2=value2";
List<NameValuePair> parameters = URLEncodedUtils.parse(new URI(url));
for (NameValuePair p : parameters) {
System.out.println(p.getName());
System.out.println(p.getValue());
}
This static method builds map of parameters from given URL
private Map<String, String> extractParamsFromURL(final String url) throws URISyntaxException {
return new HashMap<String, String>() {{
for(NameValuePair p : URLEncodedUtils.parse(new URI(url), "UTF-8"))
put(p.getName(), p.getValue());
}};
}
usage
extractParamsFromURL(url).get("key")
Have a look at URLEncodedUtils
UrlQuerySanitizer added in API level 1
UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(url_string);
List<UrlQuerySanitizer.ParameterValuePair> list = sanitizer.getParameterList();
for (UrlQuerySanitizer.ParameterValuePair pair : list) {
System.out.println(pair.mParameter);
System.out.println(pair.mValue);
}
The urllib library will parse the query string parameters and allow you to access the params as either a list or a map. Use the list if there might be duplicate keys, otherwise the map is pretty handy.
Given this snippet:
String raw = "http://s3.amazonaws.com/?AWSAccessKeyId=123&Policy=456&Signature=789&key=asdasd&Content-Type=text/plain&acl=public-read&success_action_status=201";
Url url = Url.parse(raw);
System.out.println(url.query().asMap());
for (KeyValue param : url.query().params()) {
System.out.println(param.key() + "=" + param.value());
}
The output is:
{Policy=456, success_action_status=201, Signature=789, AWSAccessKeyId=123, acl=public-read, key=asdasd, Content-Type=text/plain}
AWSAccessKeyId=123
Policy=456
Signature=789
key=asdasd
Content-Type=text/plain
acl=public-read
success_action_status=201

How to search string LIKE 'something%' with Java Spring Framework?

I've got a MySQL table with Foos. Each Foo has a numeric non-unique code and a name. Now I need to find if any Foo with one of certain codes happens to have a name that starts with a given string. In normal SQL this would be trivial:
select * from FOO where CODE in (2,3,5) and NAME like 'bar%';
But how would I properly do this in Spring now? Without the need for the 'like' operator I'd do it like this:
public List<Foo> getByName(List<Integer> codes, String namePart) {
String sql = "select * from FOO where CODE in (:codes) and NAME=:name"
Map<String,Object> params = new HashMap<String,Object>();
params.put("codes", codes);
params.put("name", namePart);
return getSimpleJdbcTemplate().query(sql, new FooRowMapper(), params);
}
However, with 'like' nothing seems to work: NAME like :name%, NAME like ':name%', or NAME like ?% when using the placeholders instead of named parameters.
I could be brutal and enter it as
String sql = "select * from FOO where CODE in (:codes) and NAME like '"+namePart+"%'";`
but obviously it would be more than nice if Spring would sanitize the input parameters properly etc, you know...
You'd think Spring would support this somehow but I cannot figure it out.
Wait, of course I had to "try one more final thing" before calling it a day, and lo and behold, all my unit tests suddenly pass:
public List<Foo> getByName(List<Integer> codes, String namePart) {
String sql = "select * from FOO where CODE in (:codes) and NAME like :name"
Map<String,Object> params = new HashMap<String,Object>();
params.put("codes", codes);
params.put("name", namePart+"%");
return getSimpleJdbcTemplate().query(sql, new FooRowMapper(), params);
}
I didn't think of entering the "%" in the parameter, I was certain Spring would automatically escape it. I wonder if I'm doing it right?
For named parameters to work, you need to use NamedParameterJdbcTemplate
params.put("name", "Joe%");
jdbcTemplate.query("select * from FOO where CODE in (:codes) and NAME like :name"
In another form, I encountered the same problem, and I tried to solve it via this manner:
public List<MyEntity> getMyEntityValuesBySearchText(String searchText) {
String query = "SELECT * FROM MY_ENTITY_TABLE WHERE NAME LIKE ?";
return this.getJdbcTemplate().query(query, new String[] { "%" + searchText + "%" },
(rs, rowNum) -> new MyEntity(rs.getLong("PK"), rs.getString("NAME")));
}
There is a problem with the code above. The code structure is correct but there is a problem in mapping the variable. You will get the error message as "Index Out of Bound" SQL Exception error.
To avoid that error we map our variable properly using the class "MySqlParameterSource". We needed to create an object for that class and pass our variable inside to map out variables.
Follow this as an example.
public List<Products> getParticular2(#RequestParam String charc){
String sql ="select * from products where name like :name";
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", charc+"%");
MapSqlParameterSource param = new MapSqlParameterSource(params);
List <Products> list = template.query(sql, param, new
BeanPropertyRowMapper<>(Products.class));
return list;
}

Categories

Resources