I have a requirement to transform the source JSON to a target JSON structure; for this, I am experimenting with GraphQL.
Below is my Java Code
String schema = "type Query{AuthToken: String}";
SchemaParser schemaParser = new SchemaParser();
TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
DataFetcher<LinkedHashMap<Object, Object>> dataFetcher = environment -> {
String json = "{\"AuthToken\":\"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJjdXJyZW50QmF0Y2hOdW1iZXIiOiIxODk3MTczIiwidGVybWluYWxJZCI6InhucFByb2R1Y3QtT25saW5lIiwidXNlck5hbWUiOiJ4bnBVc2VyMSIsInBhc3N3b3JkIjoiQ24zdDNXaDlUZjlHYXBkT2RCamdNQTgrM1NZPSIsImVuYyI6InRydWUiLCJhdXRoVHlwZSI6IkJBU0lDIiwidG9rZW5UeXBlIjoieG5wX2F1dGhfdG9rZW4iLCJuYmYiOjE2NjI2NTIzMDMsImV4cCI6MTY2MjY1MjkwMywiaWF0IjoxNjYyNjUyMzAzLCJpc3MiOiJodHRwczovL3F3aWtjaWx2ZXIuY29tLyJ9.tiYe88waCpiWKAmYCkFyxxBCmuyFgLas_XsobFWxDrqfI9jzbrqQ1ZNiPdsovULd6xk1_0553aVOPJap15GE6Q\",\"ResponseMessage\":\"Transactionsuccessful.\"}";
TypeReference<LinkedHashMap<Object, Object>> typeReference = new TypeReference<>() {
};
return mapper.readValue(json, typeReference);
};
RuntimeWiring runtimeWiring = newRuntimeWiring()
.type("Query", builder -> builder.defaultDataFetcher(dataFetcher))
.build();
SchemaGenerator schemaGenerator = new SchemaGenerator();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
ExecutionResult executionResult = build.execute("{token: AuthToken}");
log.info("GraphQL response {}", executionResult.getData().toString());
However, when this code is executed, GraphQL returns the complete JSON and not just the property AuthToken.
Also, the expected response is of structure
{token: 'the token from the input json' }
however, below response is received
{token={AuthToken=eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJjdXJyZW50QmF0Y2hOdW1iZXIiOiIxODk3MTczIiwidGVybWluYWxJZCI6InhucFByb2R1Y3QtT25saW5lIiwidXNlck5hbWUiOiJ4bnBVc2VyMSIsInBhc3N3b3JkIjoiQ24zdDNXaDlUZjlHYXBkT2RCamdNQTgrM1NZPSIsImVuYyI6InRydWUiLCJhdXRoVHlwZSI6IkJBU0lDIiwidG9rZW5UeXBlIjoieG5wX2F1dGhfdG9rZW4iLCJuYmYiOjE2NjI2NTIzMDMsImV4cCI6MTY2MjY1MjkwMywiaWF0IjoxNjYyNjUyMzAzLCJpc3MiOiJodHRwczovL3F3aWtjaWx2ZXIuY29tLyJ9.tiYe88waCpiWKAmYCkFyxxBCmuyFgLas_XsobFWxDrqfI9jzbrqQ1ZNiPdsovULd6xk1_0553aVOPJap15GE6Q, ResponseMessage=Transactionsuccessful.}}
Related
public PartsServiceCombineModelDTO getServicePartsByModel(String model) {
ServiceInstance instance = loadBalancer.choose("PARTS_APP");
if (instance == null || instance.getUri() == null) {
throw new NoInstanceExistException("Part App Instance Not Available ");
}
String url = instance.getUri().toString();
ParameterizedTypeReference<List<PartsDTO>> responseType = new ParameterizedTypeReference<List<PartsDTO>>() {
};
HttpEntity<String> entity = new HttpEntity<>(new HttpHeaders());
ResponseEntity<List<PartsDTO>> response = restTemplate.exchange(url + properties.getPartModel() + model, HttpMethod.GET, entity, responseType);
List<CarService> service = repository.findAllByModel(model);
List<ServiceDTO> carsDto;
if (service.isEmpty()) {
throw new NoSuchCarExistException("Car Service Not Available");
} else {
carsDto = new ArrayList<>();
for (CarService car : service) {
ServiceDTO carDto = new ServiceDTO();
BeanUtils.copyProperties(car, carDto);
carsDto.add(carDto);
}
}
PartsServiceCombineModelDTO partsServiceCombineModelDTO = new PartsServiceCombineModelDTO(response.getBody(), carsDto);
return partsServiceCombineModelDTO;
}
Mutation Test Report
Here my test method which is not able to to mutate below topics
void getServicePartsByModel() {
when(properties.getPartModel()).thenReturn("/parts/model/");
ServiceInstance instance = mock(ServiceInstance.class);
when(instance.getUri()).thenReturn(URI.create("http://localhost:8080"));
when(loadBalancerClient.choose(eq("PARTS_APP"))).thenReturn(instance);
PartsDTO partsDTO = new PartsDTO();
partsDTO.setId("42");
partsDTO.setManufacturer("Manufacturer");
partsDTO.setMaterial("Material");
partsDTO.setModel("Model");
partsDTO.setPartName("Part Name");
partsDTO.setPartNumber("42");
partsDTO.setPrice(1);
partsDTO.setStock(1);
partsDTO.setWarranty("Warranty");
partsDTO.setYear(1);
PartsDTO partsDTO1 = new PartsDTO();
partsDTO1.setId("42");
partsDTO1.setManufacturer("Manufacturer");
partsDTO1.setMaterial("Material");
partsDTO1.setModel("Model");
partsDTO1.setPartName("Part Name");
partsDTO1.setPartNumber("42");
partsDTO1.setPrice(1);
partsDTO1.setStock(1);
partsDTO1.setWarranty("Warranty");
partsDTO1.setYear(1);
List<PartsDTO> parts = new ArrayList<>();
parts.add(partsDTO1);
parts.add(partsDTO);
ResponseEntity<List<PartsDTO>> partsResponse = ResponseEntity.ok(parts);
when(restTemplate.exchange(any(String.class), eq(HttpMethod.GET), any(HttpEntity.class), eq(new ParameterizedTypeReference<List<PartsDTO>>() {
}))).thenReturn(partsResponse);
List<CarService> carServices = new ArrayList<>();
CarService carService = new CarService();
carService.setCertified(true);
carService.setDealershipTrained(true);
carService.setId("42");
carService.setModel("Model");
carService.setOemParts(true);
carService.setServiceKM(1);
carService.setServiceMileage(1);
carService.setServiceName("Service Name");
carService.setServiceType(1);
carServices.add(carService);
when(serviceRepository.findAllByModel(eq(carService.getModel()))).thenReturn(carServices);
assertNotNull(carService);
verify(beanUtils, atLeastOnce());
BeanUtils.copyProperties(new CarService(),new ServiceDTO());
PartsServiceCombineModelDTO result = carServiceImpl.getServicePartsByModel(partsDTO.getModel());
}
Which throwing error :
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
-> at com.example.carserviceapp.service.CarServiceImplTest.getServicePartsByModel(CarServiceImplTest.java:728)
-> at com.example.carserviceapp.service.CarServiceImplTest.getServicePartsByModel(CarServiceImplTest.java:731)
-> at com.example.carserviceapp.service.CarServiceImplTest.getServicePartsByModel(CarServiceImplTest.java:763)
-> at com.example.carserviceapp.service.CarServiceImplTest.getServicePartsByModel(CarServiceImplTest.java:778)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.
org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Can Anyone Please help me in mutating the above method
BeanUtils.copyProperties(car, carDto); and
throw new NoSuchCarExistException("Car Service Not Available");
I am using java and Jest (https://github.com/searchbox-io/Jest) as a client for elastic search cluster.
Trying to create and index with the below structure in http://localhost:9200/myindex/mytype
{
"doc": {
"_content": "mycontent",
"_name": "mypdf.pdf",
"_content_type": "application/pdf"
}
}
And below is my java code,
XContentBuilder docObject = jsonBuilder().startObject().field("_content", doc).field("_name", name).field("_content_type", contentType)
.field("title", title).field("author", author).endObject();
index1 = new Index.Builder(docObject).build();
source = jsonBuilder()
.startObject()
.field("doc", docObject.string())
.endObject().string();
Index index = new Index.Builder(source).index(baseIndexName).type(ElasticConstants.BASE_TYPE).build();
But when this gets executed , the source is not passed as a Json and value for the key "doc" is passed as a string literal because of which the index is not getting created . How do I pass nested json objects to the Index.Builder using Jest ?
//Instantiate JEST Client
JestClientFactory factory = new JestClientFactory();
HttpClientConfig config = new HttpClientConfig.
Builder("http://localhost:9201")
.multiThreaded(true).build();
factory.setHttpClientConfig(config);
JestClient jestClient = factory.getObject();
//create index
jestClient.execute(new CreateIndex.Builder("so4index").build());
//create index mapping
RootObjectMapper.Builder rootObjMapBuilder1 = new RootObjectMapper.Builder("so1type");
RootObjectMapper.Builder rootObjMapBuilder = new RootObjectMapper.Builder("doc");
rootObjMapBuilder.add(new StringFieldMapper.Builder("_content").store(true));
rootObjMapBuilder.add(new StringFieldMapper.Builder("_name").store(true));
rootObjMapBuilder.add(new StringFieldMapper.Builder("_content_type").store(true));
rootObjMapBuilder1.add(rootObjMapBuilder);
DocumentMapper docMapper = new DocumentMapper.Builder("so4index", null, rootObjMapBuilder1).build(null);
String source = docMapper.mappingSource().toString();
PutMapping putMapping = new PutMapping.Builder("so4index", "so1type", source).build();
JestResult mappingResult = jestClient.execute(putMapping);
//Insert Document Content
String doc="mycontent";
String name="mypdf.pdf";
String contentType = "application/pdf";
XContentBuilder docObject = jsonBuilder()
.startObject()
.startObject("doc").field("_content", doc)
.field("_name", name)
.field("_content_type", contentType)
.endObject()
.endObject();
Index index = new Index.Builder(docObject.string()).index("so4index").type("so1type").build();
JestResult jestResult= jestClient.execute(index);
jestClient.shutdownClient();
I am trying to serialize a list of (ValidationAttribute) as shown below:
RequiredAttribute tRequired = new RequiredAttribute();
List<ValidationAttribute> ValidationList = new List<ValidationAttribute>();
ValidationList.Add(tRequired);
XmlSerializer tXMLSerializer = new XmlSerializer(typeof(List<ValidationAttribute>));
MemoryStream tMemStream = new MemoryStream();
StreamWriter tStreamWriter = new StreamWriter(tMemStream);
tXMLSerializer.Serialize(tStreamWriter, ValidationList);
When the (Serialize) function execute, the following exception will be thrown:
The type System.ComponentModel.DataAnnotations.RequiredAttribute was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically
I have figured it out. I needed to pass the type of (RequiredAttribute) to the XMLSerializer:
RequiredAttribute tRequired = new RequiredAttribute();
List<ValidationAttribute> ValidationList = new List<ValidationAttribute>();
ValidationList.Add(tRequired);
Type[] tExtraTypes = new Type[] { typeof(RequiredAttribute) };
XmlSerializer tXMLSerializer = new XmlSerializer(typeof(List<ValidationAttribute>),tExtraTypes );
I have the following:
final duration = (jsonBuilder()
.startObject()
.field('start', new DateTime(testResult.startTime, dateTimeZone))
.field('end', new DateTime(testResult.endTime, dateTimeZone))
.endObject())
client.prepareIndex('builds', 'test')
.setSource(jsonBuilder()
.startObject()
.field("duration", duration)
.endObject())
SearchResponse searchResponse = client.prepareSearch('builds')
.setQuery(boolQuery()
.must(termQuery('_type', 'test')))
.execute()
.actionGet()
final source = searchResponse.hits.hits[0].source as Map<String, Object>
How do I retrieve the values of duration.start and duration.end from here?
Try 1..!
SearchHit[] searchHits = searchResponse.getHits().getHits();
Map<String, Object> s=searchHits[0].sourceAsMap();
Map<String, Date> duration=(Map<String, Date>) s.get("duration");
Date start=duration.get("start");
Date end=duration.get("end");
Try 2..!
SearchHit[] searchHits = searchResponse.getHits().getHits();
StringBuilder builder = new StringBuilder();
int length = searchHits.length;
builder.append("[");
for (int i = 0; i < length; i++) {
if (i == length - 1) {
builder.append(searchHits[i].getSourceAsString());
} else {
builder.append(searchHits[i].getSourceAsString());
builder.append(",");
}
}
builder.append("]");
String result= builder.toString();
it will return a string and its a valid JSON array use JSON parser and fetch values as normal json process..!
The problem is that field() doesn't recognize XContentBuilder as a value despite what http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/index_.html implies. From the source code for XContentBuilder, it's unclear to me how to use field with XContentBuilder.
It's easy enough to use a Map as a value, though.
final duration = [
'start': new DateTime(testResult.startTime, dateTimeZone),
'end': new DateTime(testResult.endTime, dateTimeZone)]
client.prepareIndex('builds', 'test')
.setSource(jsonBuilder()
.startObject()
.field("duration", duration)
.endObject())
SearchResponse searchResponse = client.prepareSearch('builds')
.setQuery(boolQuery()
.must(termQuery('_type', 'test')))
.execute()
.actionGet()
final source = searchResponse.hits.hits[0].source
assertThat(source.duration.start, equalTo('1970-01-01T00:00:00.001Z'))
assertThat(source.duration.end, equalTo('1970-01-01T00:00:00.002Z'))
I'm using GSON for a project. In particular I use this code to generate JSON strings:
Gson gs = new Gson();
JsonObject cmdobj = new JsonObject();
cmdobj.addProperty("cmd", cmd);
cmdobj.add("arg", args);
String cmdstr = cmdobj.toString();
which produces something like:
{"cmd":"HANDSHAKE","arg":{"protocol":"syncmanager","serverName":"12345678910"}}
then on a client machine this reads the json data:
String cmdstr = readCommand(this.is);
Gson gs = new Gson();
JsonObject jsobj = gs.fromJson(cmdstr, JsonObject.class);
JsonElement cmd = jsobj.get("cmd");
JsonObject args = jsobj.get("arg").getAsJsonObject();
the problem is that jsobj that should contain the parsed object doesn't contain anything ( if I do toString() prints {} ). Why this? I just want the JSonObject tree that I had on the other side, not an object serialization. Any clues?
JsonObject jsobj = new Gson().fromJson(cmdstr, JsonObject.class)
will try and build a type of JsonObject from the string - which your string clearly isn't.
I think what you want to do is get the raw parse tree - which you can do like this:
JsonObject jsobj = new JsonParser().parseString(cmdstr);
See this for more details.