I'm working in jaxb with Spring, trying to write a custom unmarshalling process using WebServiceGatewaySupport.
My class is below. The problem is with response, when I call the following method
getWebServiceTemplate().sendSourceAndReceiveToResult
It crashes with message "java.lang.IllegalArgumentException: 'uri' must not be empty". It seems like even though I am using StringResult, it is trying to parse xml and finding a xml/soap response error.
public class WUResultGateway extends WebServiceGatewaySupport{
private WebServiceTemplate webServiceTemplate;
private SourceExtractor ratingResponseExtractor = new WUResponseExtractor();
public WUResultGateway(WebServiceTemplate webServiceTemplate){
this.webServiceTemplate = webServiceTemplate;
}
private Source marshall( SendRDCResults results ) throws IOException{
StringResult resp = new StringResult();
Marshaller marshaller = webServiceTemplate.getMarshaller();
marshaller.marshal( results, resp );
return new ResourceSource( new ByteArrayResource( resp.toString().getBytes() ) );
}
public Object wuResponse( SendRDCResults results) throws IOException{
//StringSource source = new StringSource();
Result result = new StreamResult();
StringResult strResult = new StringResult();
boolean flag = getWebServiceTemplate().sendSourceAndReceiveToResult( marshall( results ), strResult );
return result;
}
}
Without making any change to the response from the server, I want to get values in s String or simple xml format without errors. Can anyone help?
setDefaultUri(webServiceTemplate.getDefaultUri());
finally looks as follows
public Object wuResponse( SendRDCResults results) throws IOException{
//StringSource source = new StringSource();
Result result = new StreamResult();
StringResult strResult = new StringResult();
setDefaultUri(webServiceTemplate.getDefaultUri());
boolean flag = getWebServiceTemplate().sendSourceAndReceiveToResult( marshall( results ), strResult );
return result;
}
Related
I have this method which must be tested:
private void processRequest() {
BulkRequest request = new BulkRequest();
request.add(new IndexRequest("posts").id("1")
.source(XContentType.JSON,"field", "foo"));
request.add(new IndexRequest("posts").id("2")
.source(XContentType.JSON,"field", "bar"));
final BulkResponse bulkResponse = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
}
This is what I'm trying to do from my test class:
RestHighLevelClient restHighLevelClientMock = mock(RestHighLevelClient.class);
final String errorMessage = "error message";
final Exception cause = new Exception("test exception");
final boolean isFailed = true;
final int itemID = 0;
// define the item failure
BulkItemResponse.Failure failure = mock(BulkItemResponse.Failure.class);
when(failure.getCause()).thenReturn(cause);
when(failure.getMessage()).thenReturn(errorMessage);
// define the item level response
BulkItemResponse itemResponse = mock(BulkItemResponse.class);
when(itemResponse.isFailed()).thenReturn(isFailed);
when(itemResponse.getItemId()).thenReturn(itemID);
when(itemResponse.getFailure()).thenReturn(failure);
when(itemResponse.getFailureMessage()).thenReturn("error message");
List<BulkItemResponse> itemsResponses = Collections.singletonList(itemResponse);
// define the bulk response to indicate failure
BulkResponse response = mock(BulkResponse.class);
when(response.iterator()).thenReturn(itemsResponses.iterator());
when(response.hasFailures()).thenReturn(isFailed);
// have the client return the mock response
when(restHighLevelClientMock.bulk(any(BulkRequest.class), RequestOptions.DEFAULT)).thenReturn(response);
I'm getting java.lang.NullPointerException in this line:
when(restHighLevelClientMock.bulk(any(BulkRequest.class), RequestOptions.DEFAULT)).thenReturn(response);
Any idea why this happens? Thanks
I ran into this problem too, which led me to this github request:
https://github.com/elastic/elasticsearch/issues/40534
Elasticsearc's RestHighLevelClient class marked many of the public methods as final, making it impossible to mock.
There is a workaround detailed in the github page about creating a delegate, which is less than ideal but works.
EDIT: after digging around with possible solutions I found this article: see https://www.baeldung.com/mockito-final. I tried it in my own project and got my tests working with junit jupiter.
Add the following to your src/test/resources folder:
mockito-extensions/org.mockito.plugins.MockMaker
add the following line to the org.mockito.plugins.MockMaker file:
mock-maker-inline
While executing Juint4 test. it shows null pointer exception. while using save method in unit test it returns null. Here i am using Mockito Juint4 Testing to mock the method. someone help me out with this.
**Service Method.**
public Result save(Map inputParams){
Result result = new Result();
logger.info("::::::::::::::: save ::::::::::::::::"+inputParams);
try{
String name = inputParams.get("name").toString();
String type = inputParams.get("type").toString();
CoreIndustry coreIndustry = coreIndustryDao.findByName(name);
if(coreIndustry != null){
result.setStatusCode(HttpStatus.FOUND.value());
result.setMessage(Messages.NAME_EXIST_MESSAGE);
result.setSuccess(false);
}else{
CoreIndustry coreIndustryNew = new CoreIndustry();
coreIndustryNew.setName(name);
coreIndustryNew.setType(type);
coreIndustryNew.setInfo(new Gson().toJson(inputParams.get("info")));
System.out.println("CoreIndustry Info is :............:.............:..............:"+coreIndustryNew.getInfo());
CoreIndustry coreIndustryData = coreIndustryDao.save(coreIndustryNew);
System.out.println("Saved Data Is.............::::::::::::::::::::................ "+coreIndustryData.getName()+" "+coreIndustryData.getType()+" "+coreIndustryData.getType());
result.setData(coreIndustryData);
result.setStatusCode(HttpStatus.OK.value());
result.setMessage(Messages.CREATE_MESSAGE);
result.setSuccess(true);
}
}catch (Exception e){
logger.error("::::::::::::::: Exception ::::::::::::::::"+e.getMessage());
result.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
result.setSuccess(false);
result.setMessage(e.getMessage());
}
return result;
}
**Controller**
#PostMapping(path = "/industry/save")
public Result save(#RequestBody Map<String, Object> stringToParse) {
logger.debug("save---------------"+stringToParse);
Result result = industryService.save(stringToParse);
return result;
}
**Unit Test**
#RunWith(SpringRunner.class)
#SpringBootTest
public class IndustryServiceTest {
#MockBean
private CoreIndustryDao coreIndustryDao;
private IndustryService industryService;
#Test
public void getAll() {
System.out.println("::::::: Inside of GetAll Method of Controller.");
// when(coreIndustryDao.findAll()).thenReturn(Stream.of(
// new CoreIndustry("Dilip","Brik","Brik Industry"))
// .collect(Collectors.toList()));
//assertEquals(1,industryService.getAll().setData());
}
#Test
public void save() {
ObjectMapper oMapper = new ObjectMapper();
CoreIndustry coreIndustry = new CoreIndustry();
coreIndustry.setId(2L);
coreIndustry.setName("Dilip");
coreIndustry.setType("Business");
HashMap<String,Object> map = new HashMap();
map.put("name","Retail");
map.put("type","Development");
coreIndustry.setInfo(new Gson().toJson(map));
when(coreIndustryDao.save(any(CoreIndustry.class))).thenReturn(new CoreIndustry());
Map<String, Object> actualValues = oMapper.convertValue(coreIndustry,Map.class);
System.out.println("CoreIndustry Filed values are........ : "+coreIndustry.getName()+" "+coreIndustry.getInfo());
Result created = industryService.save(actualValues);
CoreIndustry coreIndustryValue = (CoreIndustry) created.getData();
Map<String, Object> expectedValues = oMapper.convertValue(coreIndustryValue, Map.class);
System.out.println(" Getting Saved data from CoreIndustry........"+expectedValues);
System.out.println(" Getting Saved data from CoreIndustry........"+coreIndustryValue.getName());
assertThat(actualValues).isSameAs(expectedValues);
}
I am new in this Spring boot Technology.
After Running the source code for save method.
After Debugging my source code..
It will be great please to help me out. Thank you.
I try to configure Gson as my JSON mapper to accept "snake_case" query parameter, and translate them into standard Java "camelCase" parameters.
First of all, I know I could use the #SerializedName annotation to customise the serialized name of each field, but this will involve some manual work.
After doing some search, I believe the following approach should work (please correct me if I am wrong).
Use Gson as the default JSON mapper of Spring Boot
spring.http.converters.preferred-json-mapper=gson
Configuring Gson before GsonHttpMessageConverter is created as described here
Customising the Gson naming policy in step 2 according to GSON Field Naming Policy
private GsonHttpMessageConverter createGsonHttpMessageConverter() {
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
GsonHttpMessageConverter gsonConverter = new GsonHttpMessageConverter();
gsonConverter.setGson(gson);
return gsonConverter;
}
Then I create a simple controller like this:
#RequestMapping(value = "/example/gson-naming-policy")
public Object testNamingPolicy(ExampleParam data) {
return data.getCamelCase();
}
With the following Param class:
import lombok.Data;
#Data
public class ExampleParam {
private String camelCase;
}
But when I call the controller with query parameter ?camel_case=hello, the data.camelCase could not been populated (and it's null). When I change the query parameters to ?camelCase=hello then it could be set, which mean my setting is not working as expected.
Any hint would be highly appreciated. Thanks in advance!
It's a nice question. If I understand how Spring MVC works behind the scenes, no HTTP converters are used for #ModelAttribute-driven. It can be inspected easily when throwing an exception from your ExampleParam constructor or the ExampleParam.setCamelCase method (de-Lombok first) -- Spring uses its bean utilities that use public (!) ExampleParam.setCamelCase to set the DTO value. Another proof is that no Gson.fromJson is never invoked regardless how your Gson converter is configured. So, your camelCase confuses you because the default Gson instance uses this strategy as well as Spring does -- so this is just a matter of confusion.
In order to make it work, you have to create a custom Gson-aware HandlerMethodArgumentResolver implementation. Let's assume we support POJO only (not lists, maps or primitives).
#Configuration
#EnableWebMvc
class WebMvcConfiguration
extends WebMvcConfigurerAdapter {
private static final Gson gson = new GsonBuilder()
.setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES)
.create();
#Override
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new HandlerMethodArgumentResolver() {
#Override
public boolean supportsParameter(final MethodParameter parameter) {
// It must be never a primitive, array, string, boxed number, map or list -- and whatever you configure ;)
final Class<?> parameterType = parameter.getParameterType();
return !parameterType.isPrimitive()
&& !parameterType.isArray()
&& parameterType != String.class
&& !Number.class.isAssignableFrom(parameterType)
&& !Map.class.isAssignableFrom(parameterType)
&& !List.class.isAssignableFrom(parameterType);
}
#Override
public Object resolveArgument(final MethodParameter parameter, final ModelAndViewContainer mavContainer, final NativeWebRequest webRequest,
final WebDataBinderFactory binderFactory) {
// Now we're deconstructing the request parameters creating a JSON tree, because Gson can convert from JSON trees to POJOs transparently
// Also note parameter.getGenericParameterType() -- it's better that Class<?> that cannot hold generic types parameterization
return gson.fromJson(
parameterMapToJsonElement(webRequest.getParameterMap()),
parameter.getGenericParameterType()
);
}
});
}
...
private static JsonElement parameterMapToJsonElement(final Map<String, String[]> parameters) {
final JsonObject jsonObject = new JsonObject();
for ( final Entry<String, String[]> e : parameters.entrySet() ) {
final String key = e.getKey();
final String[] value = e.getValue();
final JsonElement jsonValue;
switch ( value.length ) {
case 0:
// As far as I understand, this must never happen, but I'm not sure
jsonValue = JsonNull.INSTANCE;
break;
case 1:
// If there's a single value only, let's convert it to a string literal
// Gson is good at "weak typing": strings can be parsed automatically to numbers and booleans
jsonValue = new JsonPrimitive(value[0]);
break;
default:
// If there are more than 1 element -- make it an array
final JsonArray jsonArray = new JsonArray();
for ( int i = 0; i < value.length; i++ ) {
jsonArray.add(value[i]);
}
jsonValue = jsonArray;
break;
}
jsonObject.add(key, jsonValue);
}
return jsonObject;
}
}
So, here are the results:
http://localhost:8080/?camelCase=hello => (empty)
http://localhost:8080/?camel_case=hello => "hello"
My webservice receives an xml from a third-party source, which contains a !DOCTYPE declaration. Therefore I must use the second method in my controller to parse the xml document, the first one gives me this exception:
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not unmarshal to [class com.example.MeterBusXml]: null; nested exception is javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 48; DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.]
I have no control over the application which posts the xml, so I must adapt my webservice to parse it with the dtd.
My question is, what is the spring framework's way of injecting the EntityResolver into every XMLReader instance?
#RestController
public class MeterBusDataController {
#RequestMapping (
consumes = APPLICATION_XML_VALUE,
method = POST,
path = "/meterbus1"
)
public void method1(#RequestBody MeterBusXml xml) {
System.out.println(xml);
}
#RequestMapping(
method = POST,
path = "/meterbus2"
)
public void method2(HttpServletRequest rq) throws IOException, ParserConfigurationException, SAXException, JAXBException {
JAXBContext jc = newInstance(MeterBusXml.class);
Unmarshaller um = jc.createUnmarshaller();
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setEntityResolver(new EntityResolver() {
#Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
BufferedReader reader = rq.getReader();
InputSource inputSource = new InputSource(reader);
SAXSource saxSource = new SAXSource(xr, inputSource);
MeterBusXml xml = (MeterBusXml)um.unmarshal(saxSource);
System.out.println(xml);
}
}
See the following document for an example of the mbus.xml I'm trying to unmarshal.
http://prevodniky.sk/products/product_EthMBus_common/download/Ethernet_converters_exports_v1_02_EN.pdf
I've found the root of the problem. First I tried to create and configure a Jaxb2Marshaller bean, but that did not work out. Then I realized, I need a HttpMessageConverter, so I had to override the extendMessageConverters method in the WebMvcConfigurerAdapter class, and set the required properties on Jaxb2RootElementHttpMessageConverter. This message converter does not use a Jaxb2Marshaller, but it's internal workings are very similar.
setSupportDtd(true) is required, to force the parser to accept the !DOCTYPE declaration.
setProcessExternalEntities(false) is required, because if this property is false, then the converter uses a blank EntityResolver, just as I did in method2.
#Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Override
public void extendMessageConverters(List<HttpMessageConverter<Jaxb2RootElementHttpMessageConverter?>> converters) {
for (final Iterator<HttpMessageConverter<?>> iterator = converters.iterator(); iterator.hasNext();) {
HttpMessageConverter<?> next = iterator.next();
if (next instanceof Jaxb2RootElementHttpMessageConverter) {
Jaxb2RootElementHttpMessageConverter jaxbConverter = (Jaxb2RootElementHttpMessageConverter) next;
jaxbConverter.setProcessExternalEntities(false);
jaxbConverter.setSupportDtd(true);
}
}
}
}
Hi Iam Fresher in Jmeter
I have wrote one Java Sampler code. I don't know that is correct or wrong. If I put that URL and parameter in Http Request getting proper result, but if written as a javasampler i didn't get that result, Iam getting Pass result but no response and request data
My Sampler code is:
package org.apache.jmeter.protocol.java.test;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
public class ExampleJavaSampler extends AbstractJavaSamplerClient implements Serializable {
String mySvc = "";
JavaSamplerContext context;
public Arguments getDefaultParameters(){
Arguments arg = new Arguments();
arg.addArgument("url", "http://www.url.com:5252/Switch/Download");
arg.addArgument("e_type", "bank");
arg.addArgument("e_id", "4");
arg.addArgument("b_id", "1");
arg.addArgument("a_id", "0002");
arg.addArgument("link_branch", "");
arg.addArgument("terminal_id", "");
arg.addArgument("version", "10");
arg.addArgument("entity", "100");
System.out.println("inside default");
return arg;
}
public void setupTest(JavaSamplerContext context) {
System.out.println("inside Setup");
}
public SampleResult runTest(JavaSamplerContext context) {
System.out.println("Inside Run test:");
String urls = context.getParameter("url");
String e_type = context.getParameter("e_type");
String e_id = context.getParameter("e_id");
String b_id = context.getParameter("b_id");
String a_id = context.getParameter("a_id");
String l_branch = context.getParameter("e_type");
String t_id = context.getParameter("e_type");
String oion = context.getParameter("e_type");
String entity = context.getParameter("e");
SampleResult result = new SampleResult();
result.getURL();
result.setSampleLabel("Test Result");
result.setDataType(SampleResult.TEXT);
result.sampleStart();
try{
java.net.URL url = new java.net.URL(urls+"?=e_type="+e_type+"&e_id="+e_id+"&b_id="+b_id);
System.out.println(url);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection)url.openConnection(); // have to cast connection
connection.setRequestMethod("POST");
connection.connect();
result.sampleEnd(); // stop stopwatch
result.setSuccessful( true );
result.setResponseMessage( "Successfully performed action" );
result.setResponseCodeOK(); // 200 code
} catch (Exception e) {
result.sampleEnd(); // stop stopwatch
result.setSuccessful( false );
result.setResponseMessage( "Exception: " + e );
// get stack trace as a String to return as document data
java.io.StringWriter stringWriter = new java.io.StringWriter();
e.printStackTrace( new java.io.PrintWriter( stringWriter ) );
result.setResponseData( stringWriter.toString() );
result.setDataType( org.apache.jmeter.samplers.SampleResult.TEXT );
result.setResponseCode( "500" );
}
return result;
}
void teardownTest() {
System.out.println("inside tear Down:");
}
}
After this code I made .jar file and put lib/ext. Then I called in Javarequest and all parameters are diplayed there, then I run this Test plan, getting success message nut no result
This is the right way or we have to add some thing for there for result?
I've already responded here.
You need to call result.setResponseData() inside your try block elsewise you won't see anything on success. "Response Data" piece of "View Results Tree" listener is populated only on error according to your code.