How to read nested Json file using request methods to create endpoints? - java

I have nested Json file, I would like to read specific objects from Json file using request methods. Mostly to make exacly endpoints I need. I'm trying even to read everything but it doesn't work.
So I need help with this, I mean how to read whole Json file, after that I think I can handle to make endpoints like I need :
/api/category/{categoryName}/books
I arleady tried something like this :
#GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
Object getBeers() {
ClassPathResource resource = new ClassPathResource("static/books.json");
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(resource.getInputStream(), Object.class);
} catch (IOException e) {
e.printStackTrace();
}
return null; //also tried with path here
}
I have results like this:
(java.io.FileNotFoundException: class path resource [static/books.json] cannot be opened because it does not exist)
I tried write path in all other ways. Not working.
So I'm guessing I'm not doin' it right
Here is whole json if someone needs it:
https://pastebin.com/yruFS5SM
Below is part of my Json, after that it's repeating with similar objects.
{
"requestedUrl": "https://www.googleapis.com/books/v1/volumes?q=java&maxResults=40",
"items": [
{
"kind": "books#volume",
"id": "7tkN1CYzn2cC",
"etag": "pfjjxSpetIM",
"selfLink": "https://www.googleapis.com/books/v1/volumes/7tkN1CYzn2cC",
"volumeInfo": {
"title": "A Hypervista of the Java Landscape",
"publisher": "InfoStrategist.com",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781592432172"
},
{
"type": "ISBN_10",
"identifier": "1592432174"
}
],
"readingModes": {
"text": true,
"image": true
},
"printType": "BOOK",
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "1.0.1.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&pg=PP1&dq=java&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&dq=java&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/A_Hypervista_of_the_Java_Landscape.html?hl=&id=7tkN1CYzn2cC"
},
"saleInfo": {
"country": "PL",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "PL",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.pl/books/download/A_Hypervista_of_the_Java_Landscape-sample-epub.acsm?id=7tkN1CYzn2cC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.pl/books/download/A_Hypervista_of_the_Java_Landscape-sample-pdf.acsm?id=7tkN1CYzn2cC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://play.google.com/books/reader?id=7tkN1CYzn2cC&hl=&printsec=frontcover&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
}
}

Related

Create N number of GCP compute instances using Rest api

How to create n number of instances in GCP using rest api.
in AWS java SDK, there is a method withMaxCount where we specify number of ec2 instances.
Similarly is there anything for GCP compute.
You can use REST API in loop to create instances.
Example request will look something like this:
{
"kind": "compute#instance",
"name": "INSTANCE-NAME",
"zone": "projects/PROJECT-NAME/zones/us-central1-a",
"machineType": "projects/PROJECT-NAME/zones/us-central1-a/machineTypes/e2-medium",
"displayDevice": {
"enableDisplay": false
},
"metadata": {
"kind": "compute#metadata",
"items": []
},
"tags": {
"items": []
},
"disks": [
{
"kind": "compute#attachedDisk",
"type": "PERSISTENT",
"boot": true,
"mode": "READ_WRITE",
"autoDelete": true,
"deviceName": "INSTANCE-NAME",
"initializeParams": {
"sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20210122",
"diskType": "projects/PROJECT-NAME/zones/us-central1-a/diskTypes/pd-standard",
"diskSizeGb": "10",
"labels": {}
},
"diskEncryptionKey": {}
}
],
"canIpForward": false,
"networkInterfaces": [
{
"kind": "compute#networkInterface",
"subnetwork": "regions/us-central1/subnetworks/default",
"accessConfigs": [
{
"kind": "compute#accessConfig",
"name": "External NAT",
"type": "ONE_TO_ONE_NAT",
"networkTier": "PREMIUM"
}
],
"aliasIpRanges": []
}
],
"description": "",
"labels": {},
"scheduling": {
"preemptible": false,
"onHostMaintenance": "MIGRATE",
"automaticRestart": true,
"nodeAffinities": []
},
"deletionProtection": false,
"reservationAffinity": {
"consumeReservationType": "ANY_RESERVATION"
},
"serviceAccounts": [
{
"email": "111111111111-compute#developer.gserviceaccount.com",
"scopes": [
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/logging.write",
"https://www.googleapis.com/auth/monitoring.write",
"https://www.googleapis.com/auth/servicecontrol",
"https://www.googleapis.com/auth/service.management.readonly",
"https://www.googleapis.com/auth/trace.append"
]
}
],
"shieldedInstanceConfig": {
"enableSecureBoot": false,
"enableVtpm": true,
"enableIntegrityMonitoring": true
},
"confidentialInstanceConfig": {
"enableConfidentialCompute": false
}
}
Replace it with your own project name and service account, and you can test it here.

Sending field metadata to client in Spring

I want my client to be able to request metadata about a #RequestMapping, like the #Size and #Length values of each field. Does Spring have a way of doing this?
Closest thing might be Spring HATEOAS Affordances for HAL forms.
Spring HATEOAS Affordances
Responses produce output which includes all the metadata about the request model along with validation rules and method.
{
"_embedded": {
"employees": [...]
},
"_links": {
"self": {
"href": "http://localhost:8080/employees"
}
},
"_templates": {
"default": {
"title": null,
"method": "post",
"contentType": "",
"properties":[
{
"name": "firstName",
"required": true
},
{
"name": "id",
"required": true
},
{
"name": "lastName",
"required": true
},
{
"name": "role",
"required": true
}
]
}
}
}

Not able to return one record from controller get by Isbn

I am working with spring and json data I have loaded the json into the spring bean with this config
#Configuration
public class AppConfig {
#Bean
Book books() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(getClass().getClassLoader().getResource("book.json"), Book.class);
}
}
And here is my controller that should return one data when i perform get by ISBN
#GetMapping(value = "items/{isbn}")
public Item getItem(#PathVariable("isbn") String isbn) {
for (Item item : book.getItems()) {
for (IndustryIdentity industryIdentity : item.getVolumeInfo().getIndustryIdentifiers()) {
if (industryIdentity.getIdentifier().equals(isbn)) return item;
}
}
return null;
}
When i test it on postman and curl the result is a bunch of data instead of just the data with such isbn number
Myjson looks like this
{
"requestedUrl": "https://www.googleapis.com/books/v1/volumes?q=java&maxResults=40",
"items": [
{
"kind": "books#volume",
"id": "7tkN1CYzn2cC",
"etag": "pfjjxSpetIM",
"selfLink": "https://www.googleapis.com/books/v1/volumes/7tkN1CYzn2cC",
"volumeInfo": {
"title": "A Hypervista of the Java Landscape",
"publisher": "InfoStrategist.com",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781592432172"
},
{
"type": "ISBN_10",
"identifier": "1592432174"
}
],
"readingModes": {
"text": true,
"image": true
},
"printType": "BOOK",
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "1.0.1.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&pg=PP1&dq=java&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&dq=java&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/A_Hypervista_of_the_Java_Landscape.html?hl=&id=7tkN1CYzn2cC"
},
"saleInfo": {
"country": "PL",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "PL",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.pl/books/download/A_Hypervista_of_the_Java_Landscape-sample-epub.acsm?id=7tkN1CYzn2cC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.pl/books/download/A_Hypervista_of_the_Java_Landscape-sample-pdf.acsm?id=7tkN1CYzn2cC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://play.google.com/books/reader?id=7tkN1CYzn2cC&hl=&printsec=frontcover&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
}
}
This is the curl
curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://localhost:8080/items?isbn=9788131754559

Skip first cycle of loop when 'Categories equals null

I am reading data from json file, And i want to do a get items by categories
public List<Item> getItemsByCategory(String category) {
List<Item> matchingCategory = new ArrayList<>();
for (Item item : books.getItems()) {
List<String> categories1 = item.getVolumeInfo().getCategories();
// categories1 == null for the first item so the below for loop fails
for (String cat : categories1) {
if (cat.equals(category)) {
matchingCategory.add(item);
} else throw new MyResourceNotFoundException(String.format("category with type %s is not found"));
}
}
return matchingCategory;
}
My first item in th json file has no category this is why categories is null in the first loop , How can i skip it and continue in the item in the json file , Instead of getting null pointer exception
I tried using break but it ends the loop without starting next one
This is my json im reading data from here.
{
"requestedUrl": "https://www.googleapis.com/books/v1/volumes?q=java&maxResults=40",
"items": [
{
"kind": "books#volume",
"id": "7tkN1CYzn2cC",
"etag": "pfjjxSpetIM",
"selfLink": "https://www.googleapis.com/books/v1/volumes/7tkN1CYzn2cC",
"volumeInfo": {
"title": "A Hypervista of the Java Landscape",
"publisher": "InfoStrategist.com",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781592432172"
},
{
"type": "ISBN_10",
"identifier": "1592432174"
}
],
"readingModes": {
"text": true,
"image": true
},
"printType": "BOOK",
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "1.0.1.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&pg=PP1&dq=java&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&dq=java&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/A_Hypervista_of_the_Java_Landscape.html?hl=&id=7tkN1CYzn2cC"
},
"saleInfo": {
"country": "PL",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "PL",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.pl/books/download/A_Hypervista_of_the_Java_Landscape-sample-epub.acsm?id=7tkN1CYzn2cC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.pl/books/download/A_Hypervista_of_the_Java_Landscape-sample-pdf.acsm?id=7tkN1CYzn2cC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://play.google.com/books/reader?id=7tkN1CYzn2cC&hl=&printsec=frontcover&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
}
},
{
"kind": "books#volume",
"id": "-SYM4PW-YAgC",
"etag": "dXytGSDckJk",
"selfLink": "https://www.googleapis.com/books/v1/volumes/-SYM4PW-YAgC",
"volumeInfo": {
"title": "The Religion of Java",
"authors": [
"Clifford Geertz"
],
"publisher": "University of Chicago Press",
"publishedDate": "1976-02-15",
"description": "Written with a rare combination of analysis and speculation, this comprehensive study of Javanese religion is one of the few books on the religion of a non-Western people which emphasizes variation and conflict in belief as well as similarity and harmony. The reader becomes aware of the intricacy and depth of Javanese spiritual life and the problems of political and social integration reflected in the religion. The Religion of Java will interest specialists in Southeast Asia, anthropologists and sociologists concerned with the social analysis of religious belief and ideology, students of comparative religion, and civil servants dealing with governmental policy toward Indonesia and Southeast Asia.",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0226285103"
},
{
"type": "ISBN_13",
"identifier": "9780226285108"
}
],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 392,
"printType": "BOOK",
"categories": [
"Religion"
],
"averageRating": 4.0,
"ratingsCount": 4,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "2.1.2.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=-SYM4PW-YAgC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=-SYM4PW-YAgC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.pl/books?id=-SYM4PW-YAgC&printsec=frontcover&dq=java&hl=&cd=2&source=gbs_api",
"infoLink": "http://books.google.pl/books?id=-SYM4PW-YAgC&dq=java&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/The_Religion_of_Java.html?hl=&id=-SYM4PW-YAgC"
},
"saleInfo": {
"country": "PL",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "PL",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.pl/books/download/The_Religion_of_Java-sample-epub.acsm?id=-SYM4PW-YAgC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://play.google.com/books/reader?id=-SYM4PW-YAgC&hl=&printsec=frontcover&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "Written with a rare combination of analysis and speculation, this comprehensive study of Javanese religion is one of the few books on the religion of a non-Western people which emphasizes variation and conflict in belief as well as ..."
}
} etc
As above the first item has no category but the second does so i should be able to get the second it
Here is what i have done , Using continue and break as well, But i had to remove my exception handler,
public List<Item> getItemsByCategory(String category) {
List<Item> matchingCategory = new ArrayList<>();
for (Item item : books.getItems()) {
List<String> categories1 = item.getVolumeInfo().getCategories();
if(categories1 == null) continue;
for (String cat : categories1) {
if (cat.equals(category)) {
matchingCategory.add(item);
} else break; //throw new MyResourceNotFoundException(String.format("category with type %s is not found", category));
}
}
return matchingCategory;
}
How can i put back the throw new Exception
Why can’t you add an condition..?
if(categories1 != null) {
for() {
...
}
}

Jackson databind MismatchedInputException

Using spring configuration to read data from json into spring bean it works for simple type but i am getting the above error when try to read an array
This is my config
#Bean
Container container() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(getClass().getClassLoader().getResource("book.json"), Container.class);
}
I have decided to put in a container as suggested so its ok to have my config look like this ? As i will be using these data to create Some spring controllers.
POJO CLASS
public class Container {
String requestedUrl;
List<Item> items;}
This is the json data ,
{
"requestedUrl": "https://www.googleapis.com/books/v1/volumes?q=java&maxResults=40",
"items": [
{
"kind": "books#volume",
"id": "7tkN1CYzn2cC",
"etag": "pfjjxSpetIM",
"selfLink": "https://www.googleapis.com/books/v1/volumes/7tkN1CYzn2cC",
"volumeInfo": {
"title": "A Hypervista of the Java Landscape",
"publisher": "InfoStrategist.com",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781592432172"
},
{
"type": "ISBN_10",
"identifier": "1592432174"
}
],
"readingModes": {
"text": true,
"image": true
},
"printType": "BOOK",
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "1.0.1.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&pg=PP1&dq=java&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&dq=java&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/A_Hypervista_of_the_Java_Landscape.html?hl=&id=7tkN1CYzn2cC"
},
"saleInfo": {
"country": "PL",
"saleability": "NOT_FOR_SALE",
"isEbook": false
}, //Shortened for brevity
How can edit the config to get it work
You are passing the json object which is bounded by {} but trying to convert it to array. With this json you should convert to another class like
public class Container {
private String requestedUrl;
private List<Item> items;
// getters/setters
}

Categories

Resources