How to generate json by using lombok+gson using builder() method? - gson

I have a json like this, how can I generate it by using lombok expression + gson library? It has a mixture of array and list. Is there any readymade tool available?
{
"transactions": [
{
"transactionIds": 123456,
"test": 3000,
"amount": {
"currency": "USD",
"value": 10
}
}
]
}

Define the values like you always do and rather generating the getters / setters you would be adding the #Data attribute, Complete code below along with the dependencies
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
public class Stack32 {
public static #Data class Amount {
private String currency;
private int value;
}
public static #Data class Child {
private int transactionIds;
private int test;
private Amount amount;
}
public static #Data class Parent {
private List<Child> transactions = new ArrayList<Child>();
}
public static void main(String[] args) throws JsonProcessingException {
Amount a1 = new Amount();
a1.setCurrency("USD");
a1.setValue(10);
Child a2 = new Child();
a2.setTransactionIds(123456);
a2.setTest(3000);
a2.setAmount(a1);
Parent a3 = new Parent();
a3.getTransactions().add(a2);
ObjectMapper mapper = new ObjectMapper();
String payload = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(a3);
System.out.println(payload);
}
}
Depdendencies :
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>

Related

mongodb reactive spring boot DBRef resolution is not supported

I wrote this programe spring boot mongodb reactive
#SpringBootApplication
public class ReactitveMongoDbApplication {
public static void main(String[] args) {
SpringApplication.run(ReactitveMongoDbApplication.class, args);
}
#Bean
CommandLineRunner ok(SoscieteRepository sos, TransactionRepository trs) {
return a -> {
List<Sosciete> ls = List.of(new Sosciete("SG", "sosciete general", 1235.22),
new Sosciete("AB", "AIR BOLL", 478.36), new Sosciete("TO", "TOYOTA", 458.24));
trs.deleteAll().subscribe(null, null, () -> {
sos.deleteAll().subscribe(null, null, () -> {
ls.forEach(t -> sos.save(t).subscribe(so -> {
System.out.println(so);
for (int i = 0; i < 10; i++) {
Transaction tr = new Transaction();
tr.setDate(Instant.now());
tr.setSosciete(so);
double x = 1 + ((Math.random() * 12) - 6) / 100;
tr.setPrice(so.getPrice() * x);
trs.save(tr).subscribe(ts -> {
System.out.println(ts);
});
}
}));
});
});
System.out.println("done !");
};
}
}
interface SoscieteRepository extends ReactiveMongoRepository<Sosciete, String> {
}
#Document
#Data
#AllArgsConstructor
#NoArgsConstructor
class Sosciete {
#Id
private String id;
private String name;
private double price;
}
interface TransactionRepository extends ReactiveMongoRepository<Transaction, String> {
}
#Document
#Data
#AllArgsConstructor
#NoArgsConstructor
class Transaction {
#Id
private String id;
private Instant date;
private double price;
#DBRef(db = "sosciete", lazy = true)
private Sosciete sosciete;
}
#RestController
class ReactiveRestController {
#Autowired
private SoscieteRepository sos;
#Autowired
private TransactionRepository trans;
#GetMapping(value = "/soscietes")
public Flux<Sosciete> getAllSc() {
return sos.findAll();
}
#GetMapping(value = "/transactions")
public Flux<Transaction> getAllTr() {
return trans.findAll();
}
}
the dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
aplication.prop file:
spring.data.mongodb.database=webflux
spring.data.mongodb.port=27017
server.port=3000
my code works fine in this link :
http://localhost:3000/soscietes
but in this link:
http://localhost:3000/transactions
the code throws the following error:
java.lang.UnsupportedOperationException: DBRef resolution is not supported!
it's the DBRef annotation that is cause for this error,
it does not work at all. It throws the following exception.
can we add such a configuration to make it work?
thank you in advance
I got the same issue with Spring boot version : 2.7.0
And i changed #DBRef to #DocumentReference and it works
I found the solution:
i modified the spring boot parent version in pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath />
</parent>
to 2.1.2.RELEASE

Jackson XML parsing MismatchedInputException

I want to parse Below XML file into Java Object using Jackson. But it shows MismatchedInputException message is become null. I specified feild that I need in Employee class. And using these fields I need to create Employee objects.
d.xml -> the input xml file
<Messages>
<Message>
<Uumid>45</Uumid>
<UumidSuffix>ER.79</UumidSuffix>
<CreationDate>20-05-2020</CreationDate>
<Data>FRHF#%^G</Data>
</Message>
<Message>
<Uumid>89</Uumid>
<UumidSuffix>RT.12</UumidSuffix>
<CreationDate>26-05-2020</CreationDate>
<Data>FGRH#%^</Data>
</Message>
</Messages>
Messages.java
package org.example;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.lang.annotation.Documented;
import java.util.Arrays;
#JacksonXmlRootElement(localName ="Messages")
public final class Messages {
#JacksonXmlElementWrapper(localName = "Message",useWrapping = true)
private Message[] message;
public Messages(){}
public Messages(Message[] message){
this.message=message;
}
public Message[] getMessage() {
return message;
}
public void setMessage(Message[] message) {
this.message = message;
}
#Override
public String toString() {
return "Messages{" +
"message=" + Arrays.toString(message) +
'}';
}
}
Message.java
package org.example;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import javax.xml.bind.annotation.XmlAccessorOrder;
public class Message {
#JacksonXmlProperty(localName = "Uumid")
private String uumid;
#JacksonXmlProperty(localName = "UumidSuffix")
private String uumidSuffix;
#JacksonXmlProperty(localName = "CreationDate")
private String creationDate;
public Message() {}
public Message(String uumid,String uumidSuffix,String creationDate){
this.uumid=uumid;
this.uumidSuffix=uumidSuffix;
this.creationDate=creationDate;
}
public String getUumid() {
return uumid;
}
public void setUumid(String uumid) {
this.uumid = uumid;
}
public String getUumidSuffix() {
return uumidSuffix;
}
public void setUumidSuffix(String uumidSuffix) {
this.uumidSuffix = uumidSuffix;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
#Override
public String toString() {
return "Message{" +
"uumid='" + uumid + '\'' +
", uumidSuffix='" + uumidSuffix + '\'' +
", CreationDate='" + creationDate + '\'' +
'}';
}
}
Parser.java
package org.example;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Parser {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper=new XmlMapper();
Messages messages=objectMapper.readValue(StringUtils.toEncodedString(Files.readAllBytes(Paths.get("disk/d.xml")), StandardCharsets.UTF_8),Messages.class);
System.out.println(messages);
}
}
when executes this error shows
Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.example.Message` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('asdf')
at [Source: (StringReader); line: 3, column: 20] (through reference chain: org.example.Messages["Message"]->java.lang.Object[][0])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1455)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1081)
at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1408)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:176)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:195)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:21)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4524)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3466)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3434)
at org.example.Parser.main(Parser.java:17)
Process finished with exit code 1
maven dependencies
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.2</version>
</dependency>
</dependencies>
Your current code tells Jackson that your messages should be wrapped into a wrapper tag, so it expects XML that looks something like this:
<Messages>
<Message> <!-- this is the wrapper -->
<Message>
<Uumid>...</Uumid>
...
</Message>
<Message>
...
</Message>
</Message>
</Messages>
To fix this, you'll have to tell Jaskcon to not use the wrapper, and that the children are called "Message". In your Messages class you have to update annotations on the message field to the following:
#JacksonXmlElementWrapper(useWrapping = false)
#JacksonXmlProperty(localName = "Message")
private Message[] message;
(BTW, why not call this field messages?)

Can't get xmlelements' values when it uppercase

Can't get the xml elements "CustNo" and "Name" value in the POST API using Spring Boot (It happens with the elements' names in uppercase)
The Custromer class:
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlType(name = "", propOrder = {
"custNo",
"name"
})
#XmlRootElement(name = "customer")
public class Customer {
#XmlElement(name = "CustNo")
private int custNo;
#XmlElement(name = "Name")
private String name;
#XmlElement(name = "CustNo")
public int getCustNo() {
return custNo;
}
public void setCustNo(int custNo) {
this.custNo = custNo;
}
#XmlElement(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
the XML request Body:
<customer>
<CustNo>100</CustNo>
<Name>Alex</Name>
</customer>
Controller:
#PostMapping(path = "/save-cust-info", consumes = MediaType.APPLICATION_XML_VALUE)
public String customerInformation(#RequestBody Customer cust) {
return "Customer information saved successfully ::." + cust.getCustNo() + " " + cust.getName();
}
POM dependencies:
<properties>
<java.version>11</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
</project>
The result is: "Customer information saved successfully ::.0 null United States"
But value CustNo is 0 and Name is null. What did i wrong?
Thanks for any help in advance.
Thank you, Cezary Butler, spring ignored annotations
the solution - is to replace #XmlElement to #JacksonXmlProperty
This is how i solved it:
#JacksonXmlRootElement(localName = "customer")
public class Customer {
private String country;
#JacksonXmlProperty(localName="CustNo")
private int custNo;
#JacksonXmlProperty(localName="Name")
private String name;
public Customer() {
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getCustNo() {
return custNo;
}
public void setCustNo(int custNo) {
this.custNo = custNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>LATEST</version>
</dependency>

Springboot Jpa or hibernate updating records instead of inserting

Hi I have a normal working application which is inserting / deleting / updating correctly. However I am trying to implement receiving a json string from ajax and inserting it in a database (PostgreSQL 10.12)
The first 2 to 5 records get inserted correctly however then the application starts updating records instead of inserting and the primary keys get out of sequence.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dashboard</groupId>
<artifactId>sp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring </name>
<description>Spring boot </description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.13.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
#SuppressWarnings("hiding")
#MappedSuperclass
public abstract class AbstractModel<Long extends Serializable> implements Serializable {
private static final long serialVersionUID = -6323358535657100144L;
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractModel<?> other = (AbstractModel<?>) obj;
if (id == null) {
return other.id == null;
} else return id.equals(other.id);
}
}
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
#Entity
#Data
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class PurchaseOrderProducts extends AbstractModel<Long> {
/**
*
*/
private static final long serialVersionUID = -5927643103467927664L;
#Column(nullable = false)
private Integer productcode;
#Column(nullable = false)
private String manufacturer;
#Column(nullable = false)
private String model;
#Column(nullable = false)
private String supplier;
#Column(nullable = false)
private String supplierproductcode;
#Column(nullable = false)
private Integer orderno;
public Integer getProductcode() {
return productcode;
}
public void setProductcode(Integer productcode) {
this.productcode = productcode;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public String getSupplierproductcode() {
return supplierproductcode;
}
public void setSupplierproductcode(String supplierproductcode) {
this.supplierproductcode = supplierproductcode;
}
public Integer getOrderno() {
return orderno;
}
public void setOrderno(Integer orderno) {
this.orderno = orderno;
}
#Override
public String toString() {
return "PurchaseOrderProducts [productcode=" + productcode + ", manufacturer=" + manufacturer + ", model="
+ model + ", supplier=" + supplier + ", supplierproductcode=" + supplierproductcode + ", orderno="
+ orderno + "]";
}
}
#Service
public class PurchaseOrdersProductsService extends AbstractService<PurchaseOrderProducts, Long> {
#Autowired
private PurchaseOrdersProductsRepository purchaseOrdersProductsRepository;
#Override
protected JpaRepository<PurchaseOrderProducts, Long> getRepository() {
return purchaseOrdersProductsRepository;
}
public List<PurchaseOrderProducts> getAllPurchaseOrdersProducts() {
return getRepository().findAll();
}
#Transactional
public boolean checkIfExists(Integer productcode, Integer orderno) {
boolean val = false;
Integer test = purchaseOrdersProductsRepository.checkIfExists(productcode,orderno);
if(test == 0) {
val = false;
} else {
val = true;
}
return val;
}
public void saveAll(List<PurchaseOrderProducts> purchaseOrderProducts) {
purchaseOrdersProductsRepository.saveAll(purchaseOrderProducts);
}
}
#Repository
public interface PurchaseOrdersProductsRepository extends JpaRepository<PurchaseOrderProducts, Long> {
#Query(value = "SELECT count(productcode) FROM purchase_order_products m WHERE m.productcode = ?1 AND m.orderno=?2" , nativeQuery=true)
Integer checkIfExists(long productcode, long orderno);
}
#PostMapping(value = "/submitpoproducts", consumes = "application/json", produces = "application/json")
#ResponseBody
public List<String> savePurchaseOrderProductList(#RequestBody PurchaseOrderProducts[] purchaseOrderProducts) {
List<String> response = new ArrayList<String>();
for (int i = 0; i < purchaseOrderProducts.length; i++) {
// if (purchaseOrderProducts[i].getProductcode() != null) {
// if
// (purchaseOrdersProductsService.checkIfExists(purchaseOrderProducts[i].getProductcode(),
// purchaseOrderProducts[i].getOrderno()) == false) {
purchaseOrdersProductsService.save(purchaseOrderProducts[i]);
System.out.println(purchaseOrderProducts[i].toString());
// }
// }
// response.add("Saved product: " + purchaseOrderProducts[i]);
}
return response;
}
PurchaseOrderProducts [productcode=10000004, manufacturer=FS, model=CL 20cl, supplier=Fs, supplierproductcode=FAR001, orderno=10000003]
id |
----+
1 |
2 |
3 |
4 |
id |
----+--------------
1 |
3 |
4 |
2 |
5 |
It is hard to test your issue as you didn't provide the JSON. As a best pratice, you should check the client is not sending PurchaseOrderProducts with id, this may be your issue.
For anyone else that might come across this. I removed the json key value pair being sent having the key id and it worked. (with javascript )
delete row['id'];

java.lang.NoClassDefFoundError: Lorg/apache/myfaces/custom/fileupload/UploadedFile

I want to upload files and show them in jsf page, for that I'm using tomahawk 1.1.12, jsf 2.0 and jpa 2, I'm following The BalusC tutorial but the project connot deploy and gives the error : java.lang.NoClassDefFoundError: Lorg/apache/myfaces/custom/fileupload/UploadedFile
pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>maven.test</groupId>
<artifactId>mavenTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>apache-maven-snapshots</id>
<url>
http://people.apache.org/repo/m2-snapshot-repository
</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>myfaces-staging</id>
<url>
http://people.apache.org/builds/myfaces/m2-staging-repository
</url>
<releases>
<enabled>false</enabled>
<!--
Enable to test a MyFaces core release candidate with tomahawk
-->
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.11</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.11</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!-- <dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-api</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>-->
</dependencies>
</project>
my managed bean :
package mbeans;
//import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.faces.application.FacesMessage;
//import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
/*
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.apache.commons.el.Logger;
//import org.apache.log4j.*;
//import org.apache.log4j.spi.LoggerFactory;
*/
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import daoImpl.DocDAO;
import entities.Document;
//import org.slf4j.*;
#ManagedBean
#RequestScoped
public class DocBean {
public DocDAO docDAO;
private Part file;
private String titreDocument;
private String descriptionDocument;
private String lien;
private String dateMise;
private String Categorie;
private Integer sizeDocument;
private String sousCategorie;
public DocBean(){
docDAO=new DocDAO();
}
private UploadedFile uploadedFile;
private String fileName;
// Actions ------------------------------------------------------------------------------------
public void submit() {
// Just to demonstrate what information you can get from the uploaded file.
System.out.println("File type: " + uploadedFile.getContentType());
System.out.println("File name: " + uploadedFile.getName());
System.out.println("File size: " + uploadedFile.getSize() + " bytes");
// Prepare filename prefix and suffix for an unique filename in upload folder.
String prefix = FilenameUtils.getBaseName(uploadedFile.getName());
String suffix = FilenameUtils.getExtension(uploadedFile.getName());
// Prepare file and outputstream.
File file = null;
OutputStream output = null;
try {
// Create file with unique name in upload folder and write to it.
file = File.createTempFile(prefix + "_", "." + suffix, new File("c:/data"));
output = new FileOutputStream(file);
IOUtils.copy(uploadedFile.getInputStream(), output);
fileName = file.getName();
// Show succes message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
} catch (IOException e) {
// Cleanup.
if (file != null) file.delete();
// Show error message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));
// Always log stacktraces (with a real logger).
e.printStackTrace();
} finally {
IOUtils.closeQuietly(output);
}
}
// Getters ------------------------------------------------------------------------------------
public UploadedFile getUploadedFile() {
return uploadedFile;
}
public String getFileName() {
return fileName;
}
// Setters ------------------------------------------------------------------------------------
public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}
//#EJB
//private DocDAO fileUploaderEJB;
//private final static Logger logger = LoggerFactory.getLogger(DocDAO.class);
//public void handleFileUpload(FileUploadEvent event) {
/* titreDocument = event.getFile().getFileName();
//String contentType = event.getFile().getContentType();
byte[] bytes = event.getFile().getContents();
Document garbage = new Document();
garbage.setDescriptionDocument(titreDocument);
garbage.setFile(bytes);
garbage.setDescriptionDocument("info about the file");
fileUploaderEJB.uploadGarbage(garbage);
//((Log) logger).info("Uploaded: {}");
FacesMessage msg = new FacesMessage("Succesful", event.getFile()
.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);*/
//}
public String upload() throws IOException{
file.write("C:\\data\\"+getFilename(file));
return"succes";
}
private static String getFilename(Part part){
for(String cd: part.getHeader("content-disposition").split(";")){
if(cd.trim().startsWith("filename")){
String filename=cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
}
}
return null;
}
/*public List<Document> getAlldoc(){
return docDAO.getAllDoc();
}
public String createdoc(){
docDAO.createDoc(titreDocument, descriptionDocument, sousCategorie, Categorie, sizeDocument, dateMise, lien);;
sizeDocument=null;
titreDocument="";
descriptionDocument="";
lien="";
sousCategorie="";
dateMise="";
Categorie="";
return "success";
}*/
public String getSousCategorie() {
return sousCategorie;
}
public void setSousCategorie(String sousCategorie) {
this.sousCategorie = sousCategorie;
}
public String getTitreDocument() {
return titreDocument;
}
public void setTitreDocument(String titreDocument) {
this.titreDocument = titreDocument;
}
public String getDescriptionDocument() {
return descriptionDocument;
}
public void setDescriptionDocument(String descriptionDocument) {
this.descriptionDocument = descriptionDocument;
}
public String getDateMise() {
return dateMise;
}
public void setDateMise(String dateMise) {
this.dateMise = dateMise;
}
public String getCategorie() {
return Categorie;
}
public void setCategorie(String categorie) {
Categorie = categorie;
}
public Integer getSizeDocument() {
return sizeDocument;
}
public void setSizeDocument(Integer sizeDocument) {
this.sizeDocument = sizeDocument;
}
public String getLien() {
return lien;
}
public void setLien(String lien) {
this.lien = lien;
}
public Part getFile() {
return file;
}
public void setFile(Part file) {
this.file = file;
}
}
my entity :
package entities;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the document database table.
*
*/
#Entity
#Table(name="document")
#NamedQuery(name="Document.findAll", query="SELECT d FROM Document d")
public class Document {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="\"idDocument\"", unique=true, nullable=false)
private Integer idDocument;
#Column(length=45)
private String categorie;
#Column(name="\"dateMise\"", length=45)
private String dateMise;
#Column(name="\"descriptionDocument\"", length=60)
private String descriptionDocument;
#Lob
#Column
private byte[] file;
#Column(length=45)
private String lien;
#Column(name="\"sizeDocument\"")
private Integer sizeDocument;
#Column(name="\"sousCategorie\"", length=45)
private String sousCategorie;
#Column(name="\"titreDocument\"", length=45)
private String titreDocument;
public Document() {
}
public Integer getIdDocument() {
return this.idDocument;
}
public void setIdDocument(Integer idDocument) {
this.idDocument = idDocument;
}
public String getCategorie() {
return this.categorie;
}
public void setCategorie(String categorie) {
this.categorie = categorie;
}
public String getDateMise() {
return this.dateMise;
}
public void setDateMise(String dateMise) {
this.dateMise = dateMise;
}
public String getDescriptionDocument() {
return this.descriptionDocument;
}
public void setDescriptionDocument(String descriptionDocument) {
this.descriptionDocument = descriptionDocument;
}
public byte[] getFile() {
return this.file;
}
public void setFile(byte[] file) {
this.file = file;
}
public String getLien() {
return this.lien;
}
public void setLien(String lien) {
this.lien = lien;
}
public Integer getSizeDocument() {
return this.sizeDocument;
}
public void setSizeDocument(Integer sizeDocument) {
this.sizeDocument = sizeDocument;
}
public String getSousCategorie() {
return this.sousCategorie;
}
public void setSousCategorie(String sousCategorie) {
this.sousCategorie = sousCategorie;
}
public String getTitreDocument() {
return this.titreDocument;
}
public void setTitreDocument(String titreDocument) {
this.titreDocument = titreDocument;
}
}
and my web page xhtml:
<h:panelGrid columns="3">
<h:outputLabel for="file" value="Select file" />
<t:inputFileUpload id="file" value="#{docBean.uploadedFile}" required="true" />
<h:message for="file" style="color: red;" />
<h:panelGroup />
<h:commandButton value="Submit" action="#{docBean.submit}" />
<h:message for="uploadForm" infoStyle="color: green;" errorStyle="color: red;" />
</h:panelGrid>
</h:form>
<h:outputLink value="file/#{docBean.fileName}" rendered="#{docBean.fileName != null}">
Download back
</h:outputLink>
any idea ?
<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk</artifactId>
<version>1.1.12</version>
</dependency>
replace with
<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk20</artifactId>
<version>1.1.12</version>
</dependency>
thanks Omar it was a matter of version I tried to upload using only jsf 2.2 with no tomahawk or primefaces.
resolved

Resources