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

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?

Related

Angular1 : How to pass multiple object as request body?

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?

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.

Jqgrid controller adjustments for search

I have been combing through the wiki for the jqgrid and i can't seem to figure out how to change the logic in my controller for the jqgrid to search.
I assume the search will use the same URL specified in the jqgrid. Here is the action logic called by my jqgrid. I am using spring 3.0 and its a java controller.
#RequestMapping(value = "studentjsondata", method = RequestMethod.GET)
public #ResponseBody String studentjsondata(HttpServletRequest httpServletRequest) {
Format formatter = new SimpleDateFormat("MMMM dd, yyyy");
String column = "id";
if(httpServletRequest.getParameter("sidx") != null){
column = httpServletRequest.getParameter("sidx");
}
String orderType = "DESC";
if(httpServletRequest.getParameter("sord") != null){
orderType = httpServletRequest.getParameter("sord").toUpperCase();
}
int page = 1;
if(Integer.parseInt(httpServletRequest.getParameter("page")) >= 1){
page = Integer.parseInt(httpServletRequest.getParameter("page"));
}
int limitAmount = 10;
int limitStart = limitAmount*page - limitAmount;
List<Person> students = Person.findStudentPeopleOrderByColumn(true, column, orderType, limitStart, limitAmount).getResultList();
long countStudents = Student.countStudents();
double tally = Math.ceil(countStudents/10.0d);
int totalPages = (int)tally;
long records = countStudents;
StringBuilder sb = new StringBuilder();
sb.append("{\"page\":\"").append(page).append("\", \"records\":\"").append(records).append("\", \"total\":\"").append(totalPages).append("\", \"rows\":[");
boolean first = true;
for (Person s: students) {
sb.append(first ? "" : ",");
if (first) {
first = false;
}
sb.append(String.format("{\"id\":\"%s\", \"cell\":[\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"]}",s.getId(), s.getId(), s.getFirstName(), s.getLastName(), formatter.format(s.getDateOfBirth().getTime()), s.getGender(), s.getMaritalStatus()));
}
sb.append("]}");
return sb.toString();
}
and here is my navGrid decleration
$("#studentGrid").jqGrid('navGrid', "#pager", {edit:false,add:false,del:false,search:true},{ },{ },{ },
{
sopt:['eq', 'ne', 'lt', 'gt', 'cn', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}
);
Here is my colModel and colNames
colNames:['id','First Name', 'Last Name', 'Date Of Birth', 'Gender', 'Marital Status'],
colModel:[
{name:'id',index:'id', width:15},
{name:'firstName',index:'firstName', width:30, formoptions:{elmprefix:'(*) '}, editable:true, edittype: 'text', editrules:{required:true}},
{name:'lastName',index:'lastName', width:30, formoptions:{elmprefix:'(*) '}, editable:true, edittype: 'text',editrules:{required:true}},
{name:'dateOfBirth',index:'dateOfBirth', width:30, formoptions:{elmprefix:'(*) '},editrules:{required:true}, editable:true, edittype: 'text',
editoptions: {
dataInit: function(element) {
$(element).datepicker({dateFormat: 'MM dd, yy'})
}
}
},
{name:'gender',index:'gender', width:30, formoptions:{elmprefix:'(*) '}, editable:true, editrules:{required:true}, edittype: 'select',
editoptions:{value:{}}
},
{name:'maritalStatus',index:'maritalStatus', width:30, formoptions:{elmprefix:'(*) '}, editable:true, editrules:{required:true}, edittype: 'select',
editoptions:{value:{}}
}
]
As it is, by default the search uses trhe searchGrid method. In the post array the _search: true and filters: {"groupOp":"AND","rules":[{"field":"firstName","op":"eq","data":"Anil"}]} are present.
The searchField, searchOper and searchString are all empty but present in th epost array.
What do I have to do to get the search working?
Do I have to parse the json into Java using the json parser and the filters array, then change my query by adding a where clause and use the values form the Json object?
Does the jqgrid query its own data object insted of going back to the server and launch a new query ?
I am not too sure what I have to do, please offer some form of guidance.
I am not use Spring myself, but the post seems to me contain the information which you need.
In general if you use Advance Searching dialog (multipleSearch: true) or Toolbar Searching with stringResult: true the jqGrid send to the server additional parameter filters which format described here. The one parameter filters can contain information about multiple filters. So you have to covert JSON string to an object and analyse the object to construct some kine of WHERE part of the SELECT statement. The exact implementation is depend from the technology which you use to assess to the database.

Categories

Resources