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

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.

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?

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?

Testing a method with JUnit and Mockito to enhance branch coverage

I am writing a JUnit to enhance the line and branch coverage of a method. There is only one line left in method under test that I am trying to cover but somehow it is not being covered. I've tried to use Mockito to make it simpler but still if( o != null ) comes as red in Cobertura Report.
Method under test:
public String handleParams( Map<String, Object> params ) {
StringBuilder sb = new StringBuilder();
if( params != null ) {
Set<String> keys = params.keySet();
for( String s : keys ) {
Object o = params.get( s );
if( o != null ) {
if( sb.length() > 0 ) {
sb.append("," );
}
sb.append( s + "-" + o.toString() );
}
}
}
return sb.toString();
}
JUnit test:
#Test
public void testHandleParams() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("Object1", new Object());
params.put("Object2", new Object());
TestWSAuditHandler handler = new TestWSAuditHandler();
String handle = handler.handleParams(params);
assertNotNull(params);
assertEquals(2, params.size());
assertTrue(handle instanceof String);
// Null Condition
params = null;
handler = new TestWSAuditHandler();
handle = handler.handleParams(params);
assertNull(params);
assertEquals(null, params);
assertTrue(handle instanceof String);
// Mocking params
params = Mockito.mock(Map.class);
Mockito.when(params.get(Mockito.anyString())).thenReturn(null);
handler = new TestWSAuditHandler();
handle = handler.handleParams(params);
}
Want to know how will I make o == null
Thanks in advance
How about:
params.put("Object3", null);
before your call to handleParams?
This way, when you will call params.get("Object3") in handleParams, you will get the value associated to the key Object3, which in this case is null.

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.

Categories

Resources