Angular1 : How to pass multiple object as request body? - java

I am using angular1 with java, spring-mvc framework. And from frontend service/controller , I need to pass 2 different types of object to the java-backend-controller. For example, say my 2 objects are:
self.basicBean = {id: null, name: self.fileInfo.fileLocation};
self.delimiterToChk = {name:'', value:self.delimiter}
My current javascript controller which is seeing error at this point is :
return $http.post( 'submenu/layout/guess/' + clientId + '/' + maxColumns + "/" + origin ,
delimiterObj,
folderPathBean)
.then(
function( response )
{
return response.data;
},
function( errResponse )
{
console.error( 'Error while guessFieldLayout' );
return $q.reject( errResponse );
}
);
My backend java-controller looks like :
#RequestMapping( value = "/layout/guess/{clientId}/{maxColumns}/{origin}", method = RequestMethod.POST )
public ResponseEntity<?> guessFieldLayout( #PathVariable( "clientId" ) long clientId,
#PathVariable( "maxColumns" ) int maxColumns,
#RequestBody Delimiter delimiterObj,
#PathVariable( "origin" ) String origin,
#RequestBody BasicBean basicBeanFolderPath )
{
try{}
}
I am seeing 400 error and guessing it is because I am not suppose to send the objects as 2 Request body. However, how to put it in one request body and how to map that at java controller end? Any example available?

Related

Angular1 : not able to pass the param to the back end

I am working with angular1 on java-spring MVC framework. I have a backend java service as :
#RequestMapping( value = "/layout/guess/{id}/{maxColumns}/{origin}", method = RequestMethod.POST )
public ResponseEntity<?> guessLayout( #PathVariable( "id" ) long id,
#PathVariable( "maxColumns" ) int maxColumns,
#RequestParam( value = "delimeter", required = true) String delimiter,
#PathVariable( "luckyOrigin" ) String origin )
{
try
{
//do something with delimiter
}
}
Now from frontend javascript controller/service I am calling the above service as (inside a function):
return $http.post( 'submenu/layout/guess/' + id + '/' + maxColumns + "/" + origin,
delimiter)
.then(
function( response )
{
return response.data;
},
function( errResponse )
{
console.error( 'Error while guessFieldLayout' );
return $q.reject( errResponse );
}
);
And always getting an error as :
Required String parameter 'delimeter' is not present
I can not use the "delimiter" as part of the URL. Any insight on what I am doing wrong?

how to pass a optional param into spring controller and jpql query

this is my repository:
#Query( "SELECT new com.app.gsc.entities.ListeBI(lm.listeDeCriteres.designation,count(*) as totalNumber,lm.ficheDeMission.dateEtHeurDeDepart) from ListeDeControleDetailsMission lm where lm.boolDepart=false OR lm.ficheDeMission.codeDeFicheDeMission=:CodeMission GROUP BY lm.listeDeCriteres.designation,DATE(lm.ficheDeMission.dateEtHeurDeDepart)" )
List<ListeBI> getIncidentDepart( #Param( "CodeMission" ) Integer missId );
and heres my controller :
#RequestMapping( value = "admin/dashboard/getIncidentDepart/{codeMission}", method = RequestMethod.GET )
public Reponse getIncidentDepart( HttpServletResponse response, #PathVariable Integer codeMission ) { // entĂȘtes
CorsController.getIncidentDepart( response, codeMission );
if ( messages != null ) {
return new Reponse( -1, messages );
}
List<ListeBI> listeBIs = null;
try {
listeBIs = application.getIncidentDepart( codeMission );
} catch ( Exception e ) {
return new Reponse( 5, Static.getErreursForException( e ) );
}
return new Reponse( 0, Static.getMapForMissionIncidents( listeBIs ) );
}
My problems are: this first problem i want to pass the codeMission as choosen variable, i dont how i can put that but i will explain, if i passe the codeMission variable in the controller the request should work, and if i dont passe the codeMission variable in the controlle the request also should work, how i can do that please, and also i'm not sure if the condition in the request works level is fine:
where lm.boolDepart=false OR lm.ficheDeMission.codeDeFicheDeMission=:CodeMission
About JPQL question
Here :
where lm.boolDepart=false OR lm.ficheDeMission.codeDeFicheDeMission=:CodeMission
If your :CodeMission param is not null valued, your filter works as expected but if it has null value, it filters on :codeMission==null condition and it is not what you wish.
To address both cases (null :CodeMission param and not null :CodeMission param) , try that :
where lm.boolDepart=false OR
(:CodeMission is null OR lm.ficheDeMission.codeDeFicheDeMission=:CodeMission)
Concretely :
If it is filled with for example 100 as value for :CodeMission, it results in :
where lm.boolDepart=false OR
(lm.ficheDeMission.codeDeFicheDeMission=:100)
If it is filled with null as value for :CodeMission, it results in :
where lm.boolDepart=false OR
(null is null)
About Rest configuration question
If you use Spring 4 and Java 8, you can make codeMission optional :
#RequestMapping( value = "admin/dashboard/getIncidentDepart/{codeMission}", method = RequestMethod.GET )
public Reponse getIncidentDepart( HttpServletResponse response, #PathVariable Optional<Integer> codeMission ) {
...
}
Otherwise, create two methods with two distinct paths.

java neo4j check if a relationship exist

excluse if this is a duplicate, although I did not find the answer so far.
I have an application that creates nodes and relationships via cypher statement against the REST-API. I create relationships with the below code:
public URI createRelationship(GraphNodeTypes sourceType, URI sourceNode,
GraphNodeTypes targetType, URI targetNode,
GraphRelationshipTypes relationshipType, String[] jsonAttributes) {
URI relationShipLocation = null;
String cypherArt = getNodeIdFromLocation(sourceNode)+"-[:"+relationshipType+"]->"+getNodeIdFromLocation(targetNode);
logger.info("creating relationship ({}:{}) -[:{}]-> ({}:{})",
sourceType,
getNodeIdFromLocation(sourceNode),
relationshipType,
targetType,
getNodeIdFromLocation(targetNode));
try {
URI finalUrl = new URI( sourceNode.toString() + "/relationships" );
String cypherStatement = generateJsonRelationship( targetNode,
relationshipType,
jsonAttributes );
logger.trace("sending CREATE RELATIONSHIP cypher as {} to endpoint {}", cypherStatement, finalUrl);
WebResource resource = Client.create().resource( finalUrl );
ClientResponse response = resource
.accept( MediaType.APPLICATION_JSON )
.type( MediaType.APPLICATION_JSON )
.entity( cypherStatement )
.post( ClientResponse.class );
String responseEntity = response.getEntity(String.class).toString();
int responseStatus = response.getStatus();
logger.trace("POST to {} returned status code {}, returned data: {}",
finalUrl, responseStatus,
responseEntity);
// first check if the http code was ok
HttpStatusCodes httpStatusCodes = HttpStatusCodes.getHttpStatusCode(responseStatus);
if (!httpStatusCodes.isOk()){
if (httpStatusCodes == HttpStatusCodes.FORBIDDEN){
logger.error(HttpErrorMessages.getHttpErrorText(httpStatusCodes.getErrorCode()));
} else {
logger.error("Error {} sending data to {}: {} ", response.getStatus(), finalUrl, HttpErrorMessages.getHttpErrorText(httpStatusCodes.getErrorCode()));
}
} else {
JSONParser reponseParser = new JSONParser();
Object responseObj = reponseParser.parse(responseEntity);
JSONObject jsonResponseObj = responseObj instanceof JSONObject ?(JSONObject) responseObj : null;
if(jsonResponseObj == null)
throw new ParseException(0, "returned json object is null");
//logger.trace("returned response object is {}", jsonResponseObj.toString());
try {
relationShipLocation = new URI((String)((JSONObject)((JSONArray)((JSONObject)((JSONArray)((JSONObject)((JSONArray)jsonResponseObj.get("results")).get(0)).get("data")).get(0)).get("rest")).get(0)).get("self"));
} catch (Exception e) {
logger.warn("CREATE RELATIONSHIP statement did not return a self object, returning null -- error was {}", e.getMessage());
relationShipLocation = null;
}
}
} catch (Exception e) {
logger.error("could not create relationship ");
}
return relationShipLocation;
}
private static String generateJsonRelationship( URI endNode,
GraphRelationshipTypes relationshipType, String[] jsonAttributes ) {
StringBuilder sb = new StringBuilder();
sb.append( "{ \"to\" : \"" );
sb.append( endNode.toString() );
sb.append( "\", " );
sb.append( "\"type\" : \"" );
sb.append( relationshipType.toString() );
if ( jsonAttributes == null || jsonAttributes.length < 1 ){
sb.append( "\"" );
} else {
sb.append( "\", \"data\" : " );
for ( int i = 0; i < jsonAttributes.length; i++ ) {
sb.append( jsonAttributes[i] );
if ( i < jsonAttributes.length - 1 ){
// Miss off the final comma
sb.append( ", " );
}
}
}
sb.append( " }" );
return sb.toString();
}
My problem is that I would like to check if a given relationship of given type already exists between two nodes PRIOR creating it.
Can someone tell me, how to query for a relationship???
With nodes I do a MATCH like this:
MATCH cypher {"statements": [ {"statement": "MATCH (p:SOCIALNETWORK {sn_id: 'TW'} ) RETURN p", "resultDataContents":["REST"]} ] }
against the endpoint
http://localhost:7474/db/data/transaction/<NUMBER>
How would I construct the statement to check for a relationship, say between node 6 and 5 or whatever?
Thanks in advance,
Chris
You might want to consider doing this through cypher, and using the MERGE/ON CREATE/ON MATCH keywords.
For example, you could do something like this:
create (a:Person {name: "Bob"})-[:knows]->(b:Person {name: "Susan"});
MATCH (a:Person {name: "Bob"}), (b:Person {name: "Susan"})
MERGE (a)-[r:knows]->(b)
ON CREATE SET r.alreadyExisted=false
ON MATCH SET r.alreadyExisted=true
RETURN r.alreadyExisted;
This MATCH/MERGE query that I provide here will return true or false, depending on whether the relationship already existed or not.
Also, FWIW it looks like the code you're using to accumulate JSON via StringBuilder objects is likely to be ponderous and error prone. There are plenty of good libraries like Google GSON that will do JSON for you, so you can create JSON objects, arrays, primitives, and so on -- then let the library worry about serializing it properly to a string . This tends to make your code a lot cleaner, easier to maintain, and when you mess something up about your JSON formatting (we all do), it's way easier to find than when you accumulate strings like that.
In Java
Relationship getRelationshipBetween(Node n1, Node n2) { // RelationshipType type, Direction direction
for (Relationship rel : n1.getRelationships()) { // n1.getRelationships(type,direction)
if (rel.getOtherNode(n1).equals(n2)) return rel;
}
return null;
}

How to remove hash parameters from URL in GWT application

For example i have below url:
http://server:port/?parameter#token;ID=com.test;args=one&two&three
Here if i want to remove ID and args from the URL without reloading the page then how to do it.
Note:Right now i am doing it with below code and i am looking for the better option
PlaceRequest currentPlaceRequest = placeManager.getCurrentPlaceRequest();
final String counts= currentPlaceRequest.getParameter( "args", null );
String id = currentPlaceRequest.getParameter( "ID", null );
String url = Window.Location.getHref();
if( counts!= null && !counts.isEmpty() )
{
if( id!= null && !id.isEmpty() )
{
String counts= ";" + "args" + "=" + counts;
String urlToReplace = url.replace( counts, "" );
Window.Location.replace( urlToReplace );
}
You can retrieve the current token using History.getToken, process it and then set it using History.newItem. Note that depending on your setup (using Activities and Places or mvp4g/gwtp, etc) this could trigger another activity in your application.

Neo4j Executing cypher query via rest

Good Morning,
I set up a local Neo4j database and want to model a graph of maven dependencies.
When I execute the following statement via the webconsole, everything works fine:
start root = node(1)
create unique root -[:ROOT]-> (n{groupId:'fancyStuff',artifactId:'somewhat', version:'1.4'})
return n
(note: rootnode is there for debugging purposes, will be replaced by actual structure later)
So, here everything works fine, no matter of how much whitespaces I take or replacing ' with "
In my java application i have the following function:
private static URI getOrCreate(Artifact artifact){
String cypherUri = SERVER_ROOT_URI + "cypher";
String cypherStatement="{\"query\" : \"start x = node(1) " +
"create unique x -[:ROOT]-> (artifact{groupId:\"" + artifact.getGroupID() +
"\", artifactId:\"" + artifact.getArtifactID() +
"\", version: \"" + artifact.getVersion() +
"\"}) return artifact ,\"params\" : {}}";
WebResource resource = Client.create()
.resource( cypherUri );
ClientResponse response = resource.accept( MediaType.APPLICATION_JSON_TYPE )
.type( MediaType.APPLICATION_JSON_TYPE )
.entity( cypherStatement )
.post( ClientResponse.class );
System.out.println( String.format( "POST to [%s], status code [%d]",
cypherUri, response.getStatus() ) );
response.close();
return response.getLocation();
}
so basically I post a json file looking like
{"query" : "start root = node(1) create unique root-[:ROOT]->(artifact{groupId:'{"query" : "start root = node(1) create unique root-[:ROOT]->(artifact{groupId:'lol',artifactId:'somewhat',version:'1.4'}) return artifact","params" : {}}
also no matter what whitespacing or "/' I use I get an http 500 error, saying the first - of the relationship -[:ROOT]-> is invalid.
Posting new nodes directly via
final String nodeEntryPointUri = SERVER_ROOT_URI + "node";
WebResource resource = Client.create().resource( nodeEntryPointUri );
ClientResponse response = resource.accept( MediaType.APPLICATION_JSON_TYPE )
.type( MediaType.APPLICATION_JSON_TYPE )
.entity( /*some json*/)
.post(ClientResponse.class);
(Disclaimer: I will move the params to the right place asap this version works ;) )
I could bet it's some totally trivial error, but I'm staring at this for over half a workday right now and none of my variations want to work.
Would be awesome if somebody knows an answer.
Greetings,
Florian Rohm
The problem is you have invalid JSON. You repeat query twice. If you delete the part between stars, does it work?
**{"query" :
"start root = node(1)
create unique root-[:ROOT]->(artifact{groupId:'**
{"query" : "start root = node(1)
create unique root-[:ROOT]->(artifact{groupId:'lol',artifactId:'somewhat',version:'1.4'})
return artifact",
"params" : {}
}
Ok, i don't know what's different with this statement but this works (I tried the param split in the above code, too):
String cypherUri = SERVER_ROOT_URI + "cypher";
JSONObject jObject = new JSONObject();
try {
Map<String, String> params = new HashMap<String, String>();
params.put("groupId", artifact.getGroupID());
params.put("artifactId", artifact.getArtifactID());
params.put("version", artifact.getVersion());
String query = "start x = node(1) create unique x-[:ROOT]->(n{groupId:{groupId},artifactId:{artifactId},version:{version} }) return n";
jObject.put("query", query);
jObject.put("params", params);
} catch (Exception e) {
e.printStackTrace();
}
WebResource resource = Client.create()
.resource( cypherUri );
ClientResponse response = resource.accept( MediaType.APPLICATION_JSON_TYPE )
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(jObject.toString())
.post(ClientResponse.class);
But anyways, the second attempt is nicer and I won't complain :D
It just bugs me not to know what's going on there...

Categories

Resources