RestTemplate returning null when serialized to POJO - java

I was following the start-up guide of at spring website https://spring.io/guides/gs/consuming-rest/.
I am not following the exact tutorial in the sense that I am using another endpoint: http://www.omdbapi.com?s=rush.
I am having an issue with JSON conversion to POJO. I am not getting any error or exceptions. Could someone point out where am I going wrong?
You can find the complete code here
Here are my POJOs:
package com.sample.restapi.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResponse {
private List<Search> search;
private String totalResults;
private String response;
public SearchResponse() {
}
public List<Search> getSearch() {
return search;
}
public void setSearch(List<Search> search) {
this.search = search;
}
public String getTotalResults() {
return totalResults;
}
public void setTotalResults(String totalResults) {
this.totalResults = totalResults;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#Override
public String toString() {
return "SearchResponse [search=" + search + ", totalResults=" + totalResults + ", response=" + response + "]";
}
}
Here is the Search.java
package com.sample.restapi.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class Search {
private String title;
private String year;
private String imdbID;
private String type;
private String poster;
public Search() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getImdbID() {
return imdbID;
}
public void setImdbID(String imdbID) {
this.imdbID = imdbID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
#Override
public String toString() {
return "Search [title=" + title + ", year=" + year + ", imdbID=" + imdbID + ", type=" + type + ", poster="
+ poster + "]";
}
}
Here is the driver class.
package com.sample.restapi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
import com.sample.restapi.model.SearchResponse;
#SpringBootApplication
public class ConsumerApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumerApplication.class);
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
SearchResponse searchResponse = restTemplate.getForObject("http://www.omdbapi.com?s=rush", SearchResponse.class);
log.info(searchResponse.toString());
}
}
The console output is :
14:34:12.941 [main] INFO com.sample.restapi.ConsumerApplication - SearchResponse [search=null, totalResults=344, response=null]

You are missing correct identifiers for the properties in the json, there are differences in the response and your classes in the Capital and lower case letters. Use #JsonProperty in your classes.
#JsonProperty("Search")
private List<Search> search = new ArrayList<Search>();
private String totalResults;
#JsonProperty("Response")
private String response;
you should also add #JsonProperty annotations in the Search class.

Related

Spring Boot Postman 404 and Not Found Error

I am trying to create a Spring Boot program where I can save different products that a business may have for sale. I am saving the products into MongoDB.
Currently, I am trying to use PostMan to save a product into the database. However, PostMan keeps giving me this error, and I was wondering what I am doing wrong (this is the URL I am inputting into PostMan: "http://localhost:8080/mdb-spring-boot-product-organizer/api/addProduct"):
{
"timestamp": "2022-12-07T22:56:33.866+00:00",
"status": 404,
"error": "Not Found",
"path": "/mdb-spring-boot-product-organizer/api/addProduct"
}
Project Explorer
Controller Code
package com.example.mdbspringbootproductorganizer.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.mdbspringbootproductorganizer.model.Product;
import com.example.mdbspringbootproductorganizer.repository.ProductRepository;
#RestController
#RequestMapping("/api")
public class ProductController {
#Autowired
private ProductRepository repository;
#PostMapping("/addProduct")
public String saveProduct(#RequestBody Product product) {
repository.save(product);
return "Added product with id : " + product.getId();
}
#GetMapping("/findAllProducts")
public List<Product> getProducts() {
return repository.findAll();
}
#GetMapping("/findAllProducts/{id}")
public Optional<Product> getProduct(#PathVariable int id) {
return repository.findById(id);
}
#DeleteMapping("/delete/{id}")
public String deleteBook(#PathVariable int id) {
repository.deleteById(id);
return "Product deleted with id: " + id;
}
}
Repository
package com.example.mdbspringbootproductorganizer.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.example.mdbspringbootproductorganizer.model.Product;
public interface ProductRepository extends MongoRepository<Product, Integer> {
}
POJO
package com.example.mdbspringbootproductorganizer.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "ProductInventory")
public class Product {
#Id
private int id;
private String name;
private double listedPrice;
private double purchasePrice;
private String condition;
private String brand;
private char shelf;
private int bin;
public Product(int id, String name, double listedPrice, double purchasePrice, String condition, String brand,
char shelf, int bin) {
super();
this.id = id;
this.name = name;
this.listedPrice = listedPrice;
this.purchasePrice = purchasePrice;
this.condition = condition;
this.brand = brand;
this.shelf = shelf;
this.bin = bin;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getListedPrice() {
return listedPrice;
}
public void setListedPrice(double listedPrice) {
this.listedPrice = listedPrice;
}
public double getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(double purchasePrice) {
this.purchasePrice = purchasePrice;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public char getShelf() {
return shelf;
}
public void setShelf(char shelf) {
this.shelf = shelf;
}
public int getBin() {
return bin;
}
public void setBin(int bin) {
this.bin = bin;
}
#Override
public String toString() {
return "Product [idNumber=" + id + ", name=" + name + ", listedPrice=" + listedPrice + ", purchasePrice="
+ purchasePrice + ", condition=" + condition + ", brand=" + brand + ", shelf=" + shelf + ", bin=" + bin
+ "]";
}
}
Main class
package com.example.mdbspringbootproductorganizer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#SpringBootApplication
#EnableMongoRepositories
public class MdbSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MdbSpringBootApplication.class, args);
}
}````
I have been trying to add different annotations or rename my packages, but none of that has worked.
I don't think mdb-spring-boot-product-organizer should be part of the URL.
Try making a POST to http://localhost:8080/api/addProduct.
Try adding #ComponentScan to your Spring boot application class.
#SpringBootApplication
#EnableMongoRepositories
#ComponentScan(basePackages={"com.example.mdbspringbootproductorganizer.controller","com.example.mdbspringbootproductorganizer.repository"})
public class MdbSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MdbSpringBootApplication.class, args);
}
}
This error comes usually when your spring boot application cannot find the URL (since it is defined in different package than one with #SpringBootApplication class) despite defined in Controller!

Vaadin grid.setItems not working in propertyChange methode

I have created a vaadin application using vaadin 14, i have a class accordion that passes an object HandlerTest to class Grid using a propertyChange listener. The object do pass to the grid class but when i try to use grid.setItems to show it it doesn't work. grid.setItems does add the object if i add it from the constructer but don't if i add it from the propertyChange methode.
Here is the code i used for bothe classes and the main class:
the Grid class:
`
package org.vaadin.example;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
#Route("grid")
public final class GridClass extends VerticalLayout implements PropertyChangeListener {
HandlerTest ht = new HandlerTest();
List<HandlerTest> list = new ArrayList<>();
Grid<HandlerTest> grid = new Grid<>();
public GridClass() {
grid.addColumn(HandlerTest::getPattern).setHeader("Pattern");
grid.addColumn(HandlerTest::getModuleName).setHeader("Module");
grid.setItems(list);
grid.getDataProvider().refreshAll();
grid.setAllRowsVisible(true);
grid.setHeight("480px");
add(grid);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
HandlerTest newHandler = (HandlerTest) evt.getNewValue();
ht = newHandler;
list.add(ht);
Notification.show("Value of obj :" + evt.getNewValue());
grid.getDataProvider().refreshAll();
}
}
`
here is the HandlerTest class:
`
package org.vaadin.example;
public class HandlerTest implements java.io.Serializable{
private String moduleName;
private String pattern;
private String method;
private String sourceType;
private String itemsPerPage;
private String mimesAllowed;
private String comments;
private String pSource;
public HandlerTest(String moduleName, String pattern, String method, String sourceType, String itemsPerPage, String mimesAllowed, String comments, String pSource) {
this.moduleName = moduleName;
this.pattern = pattern;
this.method = method;
this.sourceType = sourceType;
this.itemsPerPage = itemsPerPage;
this.mimesAllowed = mimesAllowed;
this.comments = comments;
this.pSource = pSource;
}
public HandlerTest() {
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getItemsPerPage() {
return itemsPerPage;
}
public void setItemsPerPage(String itemsPerPage) {
this.itemsPerPage = itemsPerPage;
}
public String getMimesAllowed() {
return mimesAllowed;
}
public void setMimesAllowed(String mimesAllowed) {
this.mimesAllowed = mimesAllowed;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getpSource() {
return pSource;
}
public void setpSource(String pSource) {
this.pSource = pSource;
}
#Override
public String toString() {
return moduleName + "/" + pattern + "/" + method + "/" + sourceType + "/" + itemsPerPage + "/" + mimesAllowed
+ "/" + comments + "/" + pSource ;
}
public HandlerTest createHandlerFromString(HandlerTest h){
String[] handlerText = (h.toString()).split("/");
HandlerTest handler = new HandlerTest(handlerText[0], handlerText[1], handlerText[2], handlerText[3],
handlerText[4], handlerText[5], handlerText[6], handlerText[7]);
return handler;
}
}
`
i was expecting the grid to be refreshed and the item is added but nothing happened. The notification shows the object to display but the grid don't add it.

How to get the covid info of a country with java, JSON

I am making a java file in which you enter the country and then it shows you the covid-19 info of that country. The site which I am using is https://covid19.mathdro.id/api/countries/
here i want it such that the user enter the country and it adds the countries name to the website eg if the user entered India it should do this
https://covid19.mathdro.id/api/countries/India
Any help would be neccessary, Thanks
You can use Retrofit to call the APIs
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.Response;
public class Retrofit_Example {
public static void main(String[] args) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://covid19.mathdro.id/")
.addConverterFactory(GsonConverterFactory.create())
.client(client.build())
.build();
Service service = retrofit.create(Service.class);
Call<Response1> responseCall = service.getData("India");
try {
Response<Response1> response = responseCall.execute();
Response1 apiResponse = response.body();
System.out.println(apiResponse);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You will have to create POJOs from the JSON response coming from the api first and also the retrofit client.
POJO for respone
public class Response1 {
private Confirmed confirmed;
private Deaths deaths;
private String lastUpdate;
private Recovered recovered;
public Confirmed getConfirmed() {
return confirmed;
}
public void setConfirmed(Confirmed confirmed) {
this.confirmed = confirmed;
}
public Deaths getDeaths() {
return deaths;
}
public void setDeaths(Deaths deaths) {
this.deaths = deaths;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Recovered getRecovered() {
return recovered;
}
public void setRecovered(Recovered recovered) {
this.recovered = recovered;
}
#Override
public String toString() {
return "Response1{" +
"confirmed=" + confirmed +
", deaths=" + deaths +
", lastUpdate='" + lastUpdate + '\'' +
", recovered=" + recovered +
'}';
}
}
public class Recovered {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Recovered{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Deaths {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Deaths{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Confirmed {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Confirmed{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
Retrofit Client
public interface Service {
#GET("/api/countries/{country}")
public Call<Response1> getData(#Path("country")String country);
}

Deserializing list with GSON

I have the following JSON object and I want to deserialize it using Google's GSON library. Unfortunately I am unable to get the list correctly. GSON finds the first list entry but not the second.
This is the code I use for invoking GSON:
Mentions result = gson.fromJson(response, Mentions.class);
Here is my JSON File:
{
"mentions": [
{
"allEntities": [
{
"kbIdentifier": "YAGO:Bob_Dylan",
"disambiguationScore": "0.63692"
}
],
"name": "Dylan",
"bestEntity": {
"kbIdentifier": "YAGO:Bob_Dylan",
"disambiguationScore": "0.63692"
}
},
{
"name": "Duluth",
"bestEntity": {
"kbIdentifier": "YAGO:Duluth\\u002c_Minnesota",
"disambiguationScore": "0.63149"
}
}
]
}
And these are the plain old java objects I have created:
public class Mentions {
public List<Mention> mentions = new ArrayList<>();
}
public class Mention {
#SerializedName("bestEntity")
public BestEntity entity;
#SerializedName("name")
public String name;
}
public class BestEntity {
#SerializedName("kbIdentifier")
public String kbIdentifier;
#SerializedName("disambiguationScore")
public Double disambiguationScore;
}
I also tried directly deserializing the list, but it just gives me an error, saying that GSON expects the list to start at the beginning of the input.
Type datasetListType = new TypeToken<Collection<Mention>>() {
}.getType();
List<Mention> mentions = gson.fromJson(response, datasetListType);
Try this -
AllEntity.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AllEntity {
#SerializedName("kbIdentifier")
#Expose
private String kbIdentifier;
#SerializedName("disambiguationScore")
#Expose
private String disambiguationScore;
public String getKbIdentifier() {
return kbIdentifier;
}
public void setKbIdentifier(String kbIdentifier) {
this.kbIdentifier = kbIdentifier;
}
public String getDisambiguationScore() {
return disambiguationScore;
}
public void setDisambiguationScore(String disambiguationScore) {
this.disambiguationScore = disambiguationScore;
}
#Override
public String toString() {
return "AllEntity [kbIdentifier=" + kbIdentifier
+ ", disambiguationScore=" + disambiguationScore + "]";
}
}
BestEntity.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BestEntity {
#SerializedName("kbIdentifier")
#Expose
private String kbIdentifier;
#SerializedName("disambiguationScore")
#Expose
private String disambiguationScore;
public String getKbIdentifier() {
return kbIdentifier;
}
public void setKbIdentifier(String kbIdentifier) {
this.kbIdentifier = kbIdentifier;
}
public String getDisambiguationScore() {
return disambiguationScore;
}
public void setDisambiguationScore(String disambiguationScore) {
this.disambiguationScore = disambiguationScore;
}
#Override
public String toString() {
return "BestEntity [kbIdentifier=" + kbIdentifier
+ ", disambiguationScore=" + disambiguationScore + "]";
}
}
Mention.java
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Mention {
#SerializedName("allEntities")
#Expose
private List<AllEntity> allEntities = new ArrayList<AllEntity>();
#SerializedName("name")
#Expose
private String name;
#SerializedName("bestEntity")
#Expose
private BestEntity bestEntity;
public List<AllEntity> getAllEntities() {
return allEntities;
}
public void setAllEntities(List<AllEntity> allEntities) {
this.allEntities = allEntities;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BestEntity getBestEntity() {
return bestEntity;
}
public void setBestEntity(BestEntity bestEntity) {
this.bestEntity = bestEntity;
}
#Override
public String toString() {
return "Mention [allEntities=" + allEntities + ", name=" + name
+ ", bestEntity=" + bestEntity + "]";
}
}
Main.java
import com.example.ElemntList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
/**
* #param args
*/
public static void main(String[] args) {
String s = "{\"mentions\":[{\"allEntities\":[{\"kbIdentifier\":\"YAGO:Bob_Dylan\",\"disambiguationScore\":\"0.63692\"}],\"name\":\"Dylan\",\"bestEntity\":{\"kbIdentifier\":\"YAGO:Bob_Dylan\",\"disambiguationScore\":\"0.63692\"}},{\"name\":\"Duluth\",\"bestEntity\":{\"kbIdentifier\":\"YAGO:Duluth\\u002c_Minnesota\",\"disambiguationScore\":\"0.63149\"}}]}";
ElemntList info = gson.fromJson(s, ElemntList.class);
System.out.println(info);
}
}
Result is -
ElemntList [mentions=[Mention [allEntities=[AllEntity [kbIdentifier=YAGO:Bob_Dylan, disambiguationScore=0.63692]], name=Dylan, bestEntity=BestEntity [kbIdentifier=YAGO:Bob_Dylan, disambiguationScore=0.63692]], Mention [allEntities=[], name=Duluth, bestEntity=BestEntity [kbIdentifier=YAGO:Duluth,_Minnesota, disambiguationScore=0.63149]]]]
Shouldn't you use the class you've created ? I.E Mentions
gson.fromJson(response, Mentions.class);
And if I were you, I would map all fields just in case you may need it, you're missing allEntities.

Malformed URL no protocol error [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
java.net.MalformedURLException: no protocol: "localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
Malformed URL exception when reading data from url containing localhost.
Actually my program is as below
package bll.sap;
import java.net.MalformedURLException;
import utility.PropertyUtility;
public class GetActiveData
{
public static void main(String[] args) {
String sapURL = "";
try {
sapURL = PropertyUtility.getSapURL();
//Get Summary Data
SapDataSync sapDataSync = new SapDataSync();
//sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=false");
sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=E13F42EC5E38");
}
catch(MalformedURLException me)
{
me.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
AND
package bll.sap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import utility.Utility;
import com.google.code.morphia.Datastore;
import dal.GetMorphiaDB;
public class SapDataSync
{
private void saveSapTransaction(List<TransactionUnit> sapTransaction){
GetMorphiaDB morphia;
try {
morphia = GetMorphiaDB.getInstance();
Datastore ds = morphia.getDs();
ds.save(sapTransaction);
}catch (Exception e) {
e.printStackTrace();
}
}
private void createSapTransaction(String transactionJson){
JSONObject jsonObj = JSONObject.fromObject(transactionJson);
JSONArray transactionUnits = jsonObj.getJSONArray("TRANSACTION");
List<ActiveUnit> transactionList = new ArrayList<ActiveUnit>();
for(int i = 0; i < transactionUnits.size() ; i++){
JSONObject jsn = transactionUnits.getJSONObject(i);
JSONObject jsnFeed = transactionUnits.getJSONObject(i);
ActiveUnit transactionUnit = new ActiveUnit(
jsn.getString("listEditions"),
jsn.getString("listPackage"),
//Double.parseDouble(jsn.getString("YIELD")),
//Double.parseDouble(jsn.getString("QUANTITY")),
//Double.parseDouble(jsn.getString("VALUE")),
jsn.getString("referenceID")
//jsn.getString("PRICEGROUP"),
//jsn.getString("PAGE"),
//Utility.getCalendarTime(jsn.getString("PUBDATE"), "dd-MM-yyyy"),
//jsn.getString("CLIENTNAME"),
//jsn.getString("CLIENTCODE"),
// new Date().getTime(),
//jsn.getString("BOOKINGUNITNAME"),
//jsn.getString("BCCNAME"),
//jsn.getString("PAGENAME"),
// jsn.getString("PRICEGROUPNAME"),
// jsn.getString("ORDER"),
// jsn.getString("PAGE_LH_RH")
);
transactionList.add(transactionUnit);
System.out.println(transactionList);
}
System.out.println(transactionList.size());
if (transactionList.size() > 0) {
//saveSapTransaction(transactionList);
}
}
public void readTransactionJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
createSapTransaction(sb.toString());
} finally {
is.close();
}
}
}
AND
package bll.sap;
import java.io.Serializable;
import java.util.Date;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
#Entity("SapTransaction")
public class ActiveUnit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private ObjectId id;
private Long tilCreationDate;
private String clientName;
private String clientCode;
private String listEditions;
private Long date;
private String listPackage;
private String bookingUnitName;
private String referenceID;
private String bccName;
private String page;
private String pageName;
private String priceGroup;
private String pgName;
private Double yield;
private Double qty;
private Double value;
private String order;
private String pageType;
public ActiveUnit() {
}
public ActiveUnit(String listEdtions, String listPackage, /*Double yield,
Double qty, Double value,*/ String referenceID /*, String priceGroup,
String page, Long date,String clientName,
String clientCode,Long tilCreationDate,String bookingUnitName,String bccName,String pageName,String pgName,String order,String pageType*/) {
this.listEditions = listEdtions;
this.listPackage = listPackage;
//this.yield = yield;
//this.qty = qty;
//this.value = value;
this.referenceID = referenceID;
//this.priceGroup = priceGroup;
//this.page = page;
//this.date = date;
//this.clientName = clientName;
//this.clientCode = clientCode;
//this.tilCreationDate = tilCreationDate;
//this.setBookingUnitName(bookingUnitName);
//this.bccName = bccName;
//this.pageName = pageName;
//this.pgName = pgName;
//this.order = order;
//this.pageType = pageType;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientCode() {
return clientCode;
}
public void setClientCode(String clientCode) {
this.clientCode = clientCode;
}
public void setId(ObjectId id) {
this.id = id;
}
public ObjectId getId() {
return id;
}
public void setTilCreationDate(Long tilCreationDate) {
this.tilCreationDate = tilCreationDate;
}
public Long getTilCreationDate() {
return tilCreationDate;
}
public String getreferenceID() {
return referenceID;
}
public void setreferenceID(String referenceID) {
this.referenceID = referenceID;
}
public String getPriceGroup() {
return priceGroup;
}
public void setPriceGroup(String priceGroup) {
this.priceGroup = priceGroup;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getListEditions() {
return listEditions;
}
public void setVertical(String listEditions) {
this.listEditions = listEditions;
}
public String getListPackage() {
return listPackage;
}
public void setListPackage(String listPackage) {
this.listPackage = listPackage;
}
public Double getYield() {
return yield;
}
public void setYield(Double yield) {
this.yield = yield;
}
public Double getQty() {
return qty;
}
public void setQty(Double qty) {
this.qty = qty;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public void setBookingUnitName(String bookingUnitName) {
this.bookingUnitName = bookingUnitName;
}
public String getBookingUnitName() {
return bookingUnitName;
}
public String getBccName() {
return bccName;
}
public void setBccName(String bccName) {
this.bccName = bccName;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPgName() {
return pgName;
}
public void setPgName(String pgName) {
this.pgName = pgName;
}
#Override
public String toString() {
String unit = "{ " +
//"ClientCode: " + this.clientCode+
//",TILCreation Date: " + new Date(this.tilCreationDate)+
//",ClientName: "+ this.clientName+
"listEditions: " + this.listEditions+
",listPackage: "+ this.listPackage+
//",BookingUnitName: "+ this.bookingUnitName+
//",Yield: " + this.yield+
//",QTY: " + this.qty+
//",Value: " + this.value+
",referenceID: " + this.referenceID+
//",Price Group: " + this.priceGroup+
//",BCCName: " + this.bccName+
//",PageName: " + this.pageName+
//",PriceGroupName: " + this.pgName+
//",Page: " + this.page+
//",PageType: " + this.pageType+
//",Order: " + this.order+
//",PublishDate: " + new Date(this.date) +
" }";
return unit;
}
public void setOrder(String order) {
this.order = order;
}
public String getOrder() {
return order;
}
public void setPageType(String pageType) {
this.pageType = pageType;
}
public String getPageType() {
return pageType;
}
}
First, make sure you have the protocol set for your request.
Second, make sure that the String containing the URL is URL-encoded. I.e. the URL doesn't have any spaces and other special characters - these should be encoded (space is %20 etc).
Given that the two above are met, your program should not throw an exception from the java.net.URL class.
Looking at the exception above, you'll just have to set the protocol (http://), but do make sure that you encode your URL address strings properly or else you'll get exceptions from other parts of your program.
Also, adding http:// to the following string will also result in a MalformedURLException:
"localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38 as your URL would contain special characters (" in this case) which would need to be encoded.
To provide a valid URL you should make sure that the quotes are stripped from your URL's server and path segments areas:
localhost/uatpw/ActiveTransaction?isx=E13F42EC5E38. Prepeding http:// to this will result in a valid URL.
You are missing the protocol (e.g. http://) in front of localhost.
The welformed URL could be http://localhost/uatpw/ActiveTransaction
This is not a question. What are you trying to do?
But otherwise, "localhost/uatpw/ActiveTransaction" is not a valid URL. An url must start with a protocol (http, https, ftp, etc.).
You should try with:
http://localhost/uatpw/ActiveTransaction

Categories