Jax RS PUT method - junit test - java

I have 3 methods below. The first one calls the second one and the second one calls the third. The junit test fails because all the methods are 'void', and I used an object to test junit.
public class Ids
{
#PUT
#Path("/{otherId}")
#Produces("application/xml")
//First method:
public Response putTag
(
#Context SecurityContext context
, #Context HttpServletRequest req
, #Context HttpServletResponse resp
, #PathParam("otherId") String otherId
, #FormParam("userId") String userId
) {
Map<String, String> obj = new Hashtable<String, String>();
obj.put("userId", userId);
obj.put("otherId", otherId);
putTagMethod(obj);
return ResponseBuilder.buildResponse("Inserted tag records", MediaType.APPLICATION_XML);
}
//Second Method
public void putTagMethod(Map<String, String> obj) {
String userId = obj.get("userId");
String entryId = obj.get("otherId");
try {
updateTag(userId, otherId);
} catch (java.sql.SQLException e) {
LOGGER.error("java.sql.SQLException: ", e);
e.printStackTrace();
}
}
//Third Method
public static void updateTag(String userId, String otherId) throws PersistenceException, {
if (...some condition) {
throw new InvalidParameterException("blah blah blah");
}
SpecialData data = null;
//Update if found, else insert
if (dataList != null && dataList.size() > 0) {
data = dataList.get(0);
update(userId, otherId);
} else {
insert(userId, otherId);
}
How do I write a Junit test to test 'Response putTag' method?
I wrote this (below) junit, but it gives error (
#Test
public void testPutTag() throws Exception
{
Ids tags = new Ids();
Map<String,String> obj = new HashMap<String,String>();
String xml = tags.putTag(obj);
assertTrue("PUT", xml.equals(
"<result>insert</result>"));
}
I'm getting error:
Incompatible types
required: Map<String, String>
found: void
problem is I need to assign 'xml' to a return type but all my methods are void.
How do I solve this?
Anyone please advise...

Related

How to use mockito for elasticSearchClient while updating?

Note client is RestHightLevelClient,
#Override
public void createAlias(final String aliasName, final String indexName, final boolean writable)
throws IOException {
IndicesAliasesRequest request = new IndicesAliasesRequest();
AliasActions aliasAction = new AliasActions(AliasActions.Type.ADD).index(indexName)
.alias(aliasName);
if (writable) {
aliasAction.writeIndex(true);
}
request.addAliasAction(aliasAction);
AcknowledgedResponse response = client.indices().updateAliases(request, RequestOptions.DEFAULT);
}
I tried writing test case for this :
#Test
void testCreateAlias() throws IOException {
AcknowledgedResponse response = AcknowledgedResponse.of(true);
when(client.indices().updateAliases(Mockito.mock(IndicesAliasesRequest.class), RequestOptions.DEFAULT))
.thenReturn(response);
searchManagerService.createAlias("test", "test_idx", true);
}
ERROR : client.indices() is null,
How to resolve this ?
Mock client.indices() to return a mocked instance of IndicesClient. Then mock that IndicesClient updateAliases method to return response.
var mockedIndicesClient = Mockito.mock(IndicesClient.class);
when(client.indices()).thenReturn(mockedIndicesClient);
when(mockedIndicesClient.updateAliases(Mockito.mock(IndicesAliasesRequest.class), RequestOptions.DEFAULT)).thenReturn(response);
Also I believe you want to use matchers in the last line. any(IndicesAliasesRequest.class) instead of Mockito.mock:
when(mockedIndicesClient.updateAliases(any(IndicesAliasesRequest.class), RequestOptions.DEFAULT)).thenReturn(response);

Controller in DGS Netflix Graphql

We are developing a project Using Spring boot with DGS Netflix graphql. We are created all the schemas and datafethers which is working absolutely fine with a default endpoint "/graphql". we would like to expose this app with custom endpoing so we are trying to add a controller with a custom endpoint as below. But When i run the application and send a query, my data fetcher is called twice . first time called from controller and second time i believe from framework it self. Anybody has any thoughts on this why its being called twice and how to avoid it? You help is highly appreciated. Please see the below Datafetcher and Controller.
Controller:
#RestController
#RequestMapping("/sample-information/model")
#Slf4j
public class CustomController {
#Autowired
DgsQueryExecutor dgsQueryExecutor;
#PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE, "application/graphql"})
public Mono<ResponseEntity<Object>> getDetails(#RequestBody String query,
#RequestHeader HttpHeaders headers
) {
GraphQLQueryInput inputs = null;
try {
inputs = ObjectMapperHelper.objectMapper.readValue(query, GraphQLQueryInput.class);
} catch (Exception e) {
log.error("TraceId: {} - Application Error: Error message: Error converting query to GraphQLQueryInput: {} "+ query);
}
if(inputs.getVariables() == null) {
inputs.setVariables(new HashMap<>());
}
if(inputs.getOperationName() == null) {
inputs.setOperationName("");
}
final String que = inputs.getQuery();
final Map<String, Object> var = inputs.getVariables();
final String opn = inputs.getOperationName();
ExecutionInput.Builder executionInput = ExecutionInput.newExecutionInput()
.query(inputs.getQuery())
.operationName(inputs.getOperationName())
.variables(inputs.getVariables());
return Mono.fromCallable(()-> {
return dgsQueryExecutor.execute(que, var, opn);
}).subscribeOn(Schedulers.elastic()).map(result -> {
return new ResponseEntity<>(result, HttpStatus.OK);
});
}
}
Datafetcher:
#DgsComponent
#Slf4j
public class SampleDataFetcher {
#Autowired
SampleBuilder sampleBuilder;
#DgsData(parentType = DgsConstants.QUERY_TYPE, field = DgsConstants.QUERY.SampleField)
public CompletableFuture<StoreDirectoryByStateResponse> getStoreDirectoryByState(#InputArgument String state, DataFetchingEnvironment dfe) throws BadRequestException {
Mono<StoreDirectoryByStateResponse> storeDirectoryResponse = null;
try {
sampleResponse = sampleBuilder.buildResponse(modelGraphQLContext);
} catch (BaseException e) {
}
return sampleResponse.map(response -> {
return response;
}).toFuture();
}
}

ResponseBuilder toString() returns object classes in string, not just the raw response string

I'm presently migrating from the Java ASK-SDK v1 to Java ASK SDK v2.
I'm trying to return a webhook call using the ResponseBuilder class that I built my response up and the data is correct, however when I try to populate the HTTP body with the JSON text, the ResponseBuilder.toString() value doesn't just populate the data with just the string, I get the following:
Optional[class Response {
outputSpeech: class SsmlOutputSpeech {
class OutputSpeech {
type: SSML
playBehavior: null
}
ssml: <speak>Some of the things you can say are What would you like to do?</speak>
}
card: null
reprompt: class Reprompt {
outputSpeech: class SsmlOutputSpeech {
class OutputSpeech {
type: SSML
playBehavior: null
}
ssml: <speak>You can say ..., is that what you want?</speak>
}
}
directives: []
shouldEndSession: false
canFulfillIntent: null
}]
Is there another way to get the string for the body of the response? The BaseSkillResponse has a getResponse() call, however, I cannot figure out how to use the class to generate the String response output.
I was able to get the string with the following in my class:
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
myFunction(){
try{
return toJsonString(responseBuilder.build().get());
} catch(IOException e) {
e.printStackTrace();
}
}
public String toJsonString(Response response)throws IOException {
return OBJECT_MAPPER.writeValueAsString(response);
}
Solve this by doing the following:
public String toJsonString(Response response)throws IOException
{
JacksonSerializer jacksonSerializer = new JacksonSerializer();
constructedResponse = jacksonSerializer.serialize(response);
JSONObject jsonObject = new JSONObject();
jsonObject.put("response",constructedResponse);
}

How to get the request parameters in `#Aspect`?

I was trying to add logs on every request to print IP, time, request parameters, response body, etc. Here is my code:
#Around("execution(* cn.dogchao.carcare.web.controller..*.*(..))")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes)ra;
HttpServletRequest request = sra.getRequest();
// always empty!
inputParamMap = request.getParameterMap();
// uri
requestPath = request.getRequestURI();
fromIP = getIpAddr(request);
//
outputParamMap = new HashMap<>();
Object result = pjp.proceed();//
outputParamMap.put("result", result);
return result;
}
And I had a Controller like this:
#Controller("channelController")
#RequestMapping(value = "/channel")
public class ChannelController {
#Autowired
private ChannelService channelService;
/**
*
* #return
*/
#ResponseBody
#RequestMapping(value = "/salesChannelAdd")
public String salesChannelAdd(#RequestParam Map<String, String> params) {
ChannelVO vo;
try {
vo = JSON.parseObject(JSON.toJSON(params).toString(), ChannelVO.class);
}catch (Exception e){
return JSON.toJSONString(new ResultJson(ErrorCode.INVALID_PARAM, "参数异常:"+e.getCause()).getResultMap());
}
if(!vo.validate()){
return JSON.toJSONString(new ResultJson(ErrorCode.INVALID_PARAM, vo.getErrorMsg()).getResultMap());
}
return JSON.toJSONString(channelService.createChannel(vo));
}
}
Now I print everything except the params. I got a empty parameter map. I don't know why it's empty and how to get all the params.

#PathVariable in spring 3 how to check required value

I have created one method
#RequestMapping(value = "/settings/userSettings/{key}", method = RequestMethod.POST)
#Secured("ROLE_HOME_TAB")
public ModelAndView updateUserSetting(HttpServletRequest request,
#PathVariable("key") String key,
#RequestParam(defaultValue = "") String value) {
Map<Object, Object> model = new HashMap<Object, Object>();
try {
User user = RequestUtils.getUser(request);
UserSettings userSettings = userManager.getUserSettings(user,
key);
if (userSettings == null) {
userSettings = new UserSettings(user, key);
}
userSettings.setValue(value);
userManager.saveObject(userSettings);
} catch (Exception e) {
log.error("", e);
}
return new ModelAndView(new JSONView(
model));
}
But while I am starting server I am getting this error
Superclass has no null constructors but no arguments were given
Could not generate CGLIB subclass of class
In my UserSetting pojo class I am checking not null for key. How to resolve this?
I have to use #PathVariable only, I can't use #RequestParam so please help me
PLease try :
The class you are going to proxy using CGLib has to provide a default constructor.
Source : http://forum.springsource.org/showthread.php?50210-Superclass-has-no-null-constructors-but-no-arguments-were-given

Categories