I know I've already asked about Lab 14, but I've edited my code a lot since then. I think its a lot better, but I think something is still wrong. Is it with the setters? I looked on another forum that says I'm making progress, but while they get back to me, I need someone to help edit my syntax. If what I'm doing wrong is my setters, I'll be fine but tell me that please.
I really really really really want to get this program working so that I can move on since I'm behind in class. Yes, this is Java.
Here's my code:
public class StreetAddress
{
public String street;
public String city;
public String state;
public String zip;
public StreetAddress(String findStreet, String findCity,String findState,String findZIP) {
street = findStreet;
city = findCity;
state = findState;
zip = findZIP;
}
public String getStreet() {
return street;
}
public void makeStreet(String street) {
this.street = street;
}
public String getcity() {
return city;
}
public void makeCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void makeState(String state) {
this.state = state;
}
public String getZip() {
return zip;
public void makeZip(String zip) {
this.zip = zip;
}
}
}
}
Thanks.
You can do it in any of the 2 ways.
Using parameterized constructor
class StreetAddress
{
public String street;
public String city;
public String state;
public String zip;
public StreetAddress(String findStreet, String findCity,String findState,String findZIP){
street = findStreet;
city = findCity;
state = findState;
zip = findZIP;
}
public String getStreet() {
return street;
}
public String getcity() {
return city;
}
public String getState(){
return state;
}
public String getZip() {
return zip;
}
}
and pass values from main function during calling of StreetAddress object.
by using Default constructor,
class StreetAddress
{
public String street;
public String city;
public String state;
public String zip;
public String getStreet() {
return street;
}
public void makeStreet(String street){
this.street = street;
}
public String getcity() {
return city;
}
public void makeCity(String city){
this.city = city;
}
public String getState(){
return state;
}
public void makeState(String state){
this.state = state;
}
public String getZip() {
return zip;
}
}
and pass values directly by calling functions makeZip(anyString);
You have three closing braces at the end! It should be only one and you forgot to write closing brace for your getZip Method. One more problem with your code is that you have defined your instance variables public which doesn't make any sense when you are implementing accessors for them. As a result, you'd better to make them private so you also follow the encapsulation topic of OOP. One other problem with your naming is your setters' naming convention. It is a common convention in Java programming that you name your getter as get[InstanceVatiableName] ie: getStreet and your setter like: set[InstanceVariableName] ie: setStreet.
I have corrected mentioned problems for your code in below:
public class StreetAddress
{
private String street;
private String city;
private String state;
private String zip;
public StreetAddress(String findStreet, String findCity, String findState, String findZIP) {
street = findStreet;
city = findCity;
state = findState;
zip = findZIP;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getcity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
Related
I have a service, that gets an xml/json string, tries to read it as an pojo, then returns it. Then, I want to show the result in thymeleaf. I did that successfully, but - in the model I have validation annotations, but if I submit invalid information it accepts the value, although I validated the method. Here is my code:
Controller:
#Controller
public class ConvertController implements WebMvcConfigurer {
#Autowired
PrintJSON printJSON;
#Autowired
PrintXML printXML;
#Autowired
ReadJSON readJSON;
#Autowired
ReadXML readXML;
#GetMapping("/read")
public String showReadForm() {
return "read";
}
#PostMapping("/read")
public String read(#RequestParam(value = "convertFrom") String
convertFrom, String text, Model model){
if("json".equals(convertFrom)){
Book newBook = readJSON.read(text);
model.addAttribute("result", newBook);
return "converted";
}else if("xml".equals(convertFrom)){
Book newBook = readXML.read(text);
model.addAttribute("result", newBook);
return "converted";
}
return "read";
}
#GetMapping("/print")
public String showPrintForm(Book book){
return "convert";
}
#PostMapping("/print")
public String convert(#RequestParam(value = "convertTo") String
convertTo, #Valid Book book, Errors errors, Model model) {
if(errors.hasErrors()){
return "convert";
}
if("json".equals(convertTo)){
model.addAttribute("result", printJSON.getJSON(book));
return "converted";
}
if("xml".equals(convertTo)){
model.addAttribute("result", printXML.getXML(book));
return "converted";
}
return "convert";
}}
Service
public class ReadXML {
#Autowired
#Qualifier("XmlMapper")
XmlMapper xmlMapper;
#Valid
public Book read(String xml){
try{
#Valid Book book = xmlMapper.readValue(xml, Book.class);
return book;
}
catch(JsonProcessingException e){
e.printStackTrace();
return new Book();
}
}
}
Model
public class Book {
#NotEmpty
private String title;
private String description;
private Date publishDate;
private int ISBN;
private List<#Valid Author> authors;
#Override
public String toString(){
String bookString = String.format("Title: %s\nDescription: %s\nPublish Date: %s\nISBN: %s\nAuthor", title, description, publishDate, ISBN);
for(Author a : authors){
bookString += a.toString();
}
return bookString;
}
public String getTitle() {
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(String newPublishDate) throws ParseException {
Date publishDate = new SimpleDateFormat(Constants.dateFormat).parse(newPublishDate);
this.publishDate = publishDate;
}
public int getISBN() {
return ISBN;
}
public void setISBN(int ISBN){
this.ISBN = ISBN;
}
public void addAuthor(Author author) {
authors.add(author);
}
public List<Author> getAuthors(){
return authors;
}
}
Where is my problem???
Thank you!
I am developing a chat app but I am getting the following error: Cannot find getter for the field.
that's why I want to convert Integer to String using type converters in Room but I did not find any sample below my User.java model class
#Entity public class User implements IChatUser {
#PrimaryKey(autoGenerate = true)
private Integer id;
#ColumnInfo(name = "name")
private String name;
#Ignore
Bitmap icon;
public User() {
}
#Ignore
public User(String name, Bitmap icon) {
this.name = name;
this.icon = icon;
}
#Override
public Integer getId() {
return this.id;
}
#Override
public String getName() {
return this.name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
#Override
public Bitmap getIcon() {
return this.icon;
}
#Override
public void setIcon(Bitmap icon) {
this.icon = icon;
} }
below IchatUser.kt
interface IChatUser {
fun getId(): String
fun getName(): String?
fun getIcon(): Bitmap?
fun setIcon(bmp: Bitmap)
}
To create a #TypeConverter create a java class and call it IntConverter
public class IntConverter {
#TypeConverter
public static String toString(int number) {
return number == null ? null : Integer.toString(number);
}
#TypeConverter
public static int toInt(String str) {
return str == null ? null : Integer.parseInt(str);
}
}
Now you need the database to know about this TypeConverter so declare this:
#TypeConverters(IntConverter.class)
Just below the #Database annotation in the Database class
I'm trying to build a Spring WebFlux project and realize the follow business logic:
1 - Call an external REST Api using WebClient and parse the Json results using the Models below. It is working OK
2 - To show the Mono results Mono<DeviceList> devices, I'm using the ResponseApi class and returning it, but it is NOT working
I'm getting the follow error:
Response status 406 with reason "Could not find acceptable representation"
Thanks
# Json Result
{
"data": [
{
"id": "5bc3c0efe833d93f401bafa8",
"name": "XXXXX",
"group": "5b8fd1fa0499f54cfa7febb8",
"description": "Geolocalizacao gps",
"payloadType": "None",
"contract": "5bc08be5e833d93f40e1f936",
"keepAlive": 0
}
]
}
# Controller
public class DeviceController{
...
...
#RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
Mono<DeviceList> devices = deviceService.findDeviceTypes();
ResponseApi r = new ResponseApi();
r.setMessage("Test");
r.setCode("200");
r.setStatus(200);
r.setData(devices);
return ok().body(Mono.just(r), ResponseApi.class);
}
}
# Repository
public Mono<DeviceList> findDeviceTypes() {
return webClient.get()
.uri(DEVICE_TYPES_URL)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(DeviceList.class);
}
# Model
public class DeviceList{
#JsonProperty("data")
private List<Device> data;
public List<Device> getData() {
return data;
}
public void setData(List<Device> data) {
this.data = data;
}
}
public class Device{
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("group")
private String group;
#JsonProperty("description")
private String description;
#JsonProperty("keepAlive")
private Integer keepAlive;
#JsonProperty("payloadType")
private String payloadType;
#JsonProperty("contract")
private String contract;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(Integer keepAlive) {
this.keepAlive = keepAlive;
}
public String getPayloadType() {
return payloadType;
}
public void setPayloadType(String payloadType) {
this.payloadType = payloadType;
}
public String getContract() {
return contract;
}
public void setContract(String contract) {
this.contract = contract;
}
}
#JsonRootName("data")
public class ResponseApi{
#JsonProperty("status")
private Integer status;
#JsonProperty("code")
private String code;
#JsonProperty("message")
private String message;
#JsonProperty("data")
private Object data;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
You can get devices, then in non blocking way, map them to the ResponseApi like that:
#RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
return deviceService.findDeviceTypes()
.flatMap(devices -> {
ResponseApi r = new ResponseApi();
r.setMessage("Test");
r.setCode("200");
r.setStatus(200);
r.setData(devices);
return ok().body(Mono.just(r), ResponseApi.class);
});
}
I want to sort Descending by lastChange property, the List of items from mongo.
RequestRepository interface:
public interface RequestRepository extends MongoRepository<Request, String> {
List<Request> findByUser(String id);
}
Request.java:
#Document(collection = "Requests")
public class Request {
#Id
private String id;
private String user;
private String username;
private String requestTitle;
private String requestMessage;
private boolean read;
private Date lastChange;
private Date requestDate;
private boolean isActiveRequest;
private boolean isPremiumRequest; //paid request
public Request() {}
public Request(
String user,
String requestTitle,
String requestMessage,
boolean read,
Date lastChange,
Date requestDate,
boolean isActiveRequest) {
this.user = user;
this.requestTitle = requestTitle;
this.requestMessage = requestMessage;
this.read = read;
this.lastChange = lastChange;
this.requestDate = requestDate;
this.isActiveRequest = isActiveRequest;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRequestTitle() {
return requestTitle;
}
public void setRequestTitle(String requestTitle) {
this.requestTitle = requestTitle;
}
public String getRequestMessage() {
return requestMessage;
}
public void setRequestMessage(String requestMessage) {
this.requestMessage = requestMessage;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public Date getLastChange() {
return lastChange;
}
public void setLastChange(Date lastChange) {
this.lastChange = lastChange;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public boolean isActiveRequest() {
return isActiveRequest;
}
public void setActiveRequest(boolean activeRequest) {
isActiveRequest = activeRequest;
}
public boolean isPremiumRequest() {
return isPremiumRequest;
}
public void setPremiumRequest(boolean premiumRequest) {
isPremiumRequest = premiumRequest;
}
}
In my code I have the following list:
List<Request> = RequestRepository.findByUser(userObj.getId());
I want to have the data from RequestRepository.findByUser(userObj.getId()); sorted DESCENDING by the property lastChange.
I have searched on StackOverflow, and found the following method to sort:
List<Request> findAllByOrderByUpdatedAtDesc();
but this does not work if I search by User.
What is the solution to search by User id and to sort by lastChange?
Thank you!
This should do it.
List<Request> findByUserOrderByLastChangeDesc(String user);
Update your question with proper details.
I have the following class that I take as input in my Resource
#JsonIgnoreProperties(ignoreUnknown = false)
public class InputRequest {
#NotEmpty
private List<String> names;
private DateTime startDate;
private DateTime endDate;
#ValidationMethod(message="startDate should be less than endDate")
public boolean isValidDates() {
return startDate.isBefore(endDate);
}
#ValidationMethod(message = "one of the names is not valid")
public boolean isValidNames() {
//do something
}
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
public DateTime getStartDate() {
return startDate;
}
public void setStartDate(DateTime startDate) {
this.startDate = startDate;
}
public DateTime getEndDate() {
return endDate;
}
public void setEndDate(DateTime endDate) {
this.endDate = endDate;
}
}
The resource class is as follows
public Response getData(#Auth String userId, #Valid InputRequest request) {
However, the following input is not causing any exceptions
{"names":["somename"],"startDate":1427155200000,"endDate":1427846400000, "x":"a"}
Can someone tell me what I am doing wrong here?
EDIT: Also if I send the following instead, its passing through
{"names":["somename"],"startDate":1427155200000}
I want it to fail if something field is missing
bootstrap.getObjectMapperFactory().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
worked for me