Getting getting null values when unmarshalling the xml using jaxB - spring

This is my bean class
class resp {
String code;
String msg;
resp() {
code = null;
msg = null;
}
resp(String code, String msg) {
this.code = code;
this.msg = msg;
}
#XmlAttribute(name = "code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#XmlAttribute(name = "msg")
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
This class contains a list of resp class
#XmlRootElement(name = "resps")
class resps {
List<resp> resp = null;
#XmlElement
public List<resp> getResp() {
return resp;
}
public void setResp(List<resp> resp) {
this.resp = resp;
}
}
Main method: In which I am using jaxb to unmarshal the resps.xml into java object (resps)
public static void main(String args[]) throws JAXBException {
try {
File file = new File("resps.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(resps.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
resps res = (resps) jaxbUnmarshaller.unmarshal(file);
List<resp> list = res.getResp();
int i = 1;
for (resp ans : list){
System.out.println(" record " + i++ + " contents :" + ans.code
+ " " + ans.msg);
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
-----------------------------resps.xml---------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<resps>
<resp>
<code>testCode1</code>
<msg>testMsg1</msg>
</resp>
<resp>
<code>testCode2</code>
<msg>testMsg2</msg>
</resp>
</resps>
Output
record 1 contents :null null
record 2 contents :null null

In your resp.class you annotate the code and msg getter methods with #XmlAttribute but in your xml these are present as element. Change annotation #XmlAttribute to #XmlElement.
class resp {
String code;
String msg;
resp() {
code = null;
msg = null;
}
resp(String code, String msg) {
this.code = code;
this.msg = msg;
}
#XmlElement(name = "code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#XmlElement(name = "msg")
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Use #XmlAttribute if your xml is like below:
<?xml version="1.0" encoding="UTF-8"?>
<resps>
<resp code="testCode1" msg = "testMsg1"/>
<resp code="testCode2" msg = "testMsg2"/>
</resps>

Change your resp.java code as given below
#XmlElement(name = "code")
public String getCode()
{
return code;
}
#XmlElement(name = "msg")
public String getMsg()
{
return msg;
}
I suggest You should refer some tutorial, about what is XmlAttribute and XmlElement

Related

Checkmarx: Unsafe object binding

We are using Java Spring framework. We have an endpoint for passing email object.
#RequestMapping(method = RequestMethod.POST, path = "/api/messaging/v1/emailMessages/actions/send")
String sendEmail(#RequestBody Email email);
Here checkmarx says: The email may unintentionally allow setting the value of cc in LinkedList<>, in the object Email.
Email Object is as follow:
public class Email {
private List<String> bcc = new LinkedList<>();
private List<String> cc = new LinkedList<>();
private String content;
private ContentType contentType = ContentType.TXT;
private String from;
private String returnPath;
private Date sent;
private String subject;
private List<EmailAttachment> attachments = new LinkedList<>();
private List<String> to = new LinkedList<>();
public List<String> getBcc() {
return bcc;
}
public void setBcc(String bcc) {
this.bcc = Collections.singletonList(bcc);
}
public void setBcc(List<String> bcc) {
this.bcc = bcc;
}
public List<String> getCc() {
return cc;
}
public void setCc(String cc) {
this.cc = Collections.singletonList(cc);
}
public void setCc(List<String> cc) {
this.cc = cc;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public ContentType getContentType() {
return contentType;
}
public void setContentType(ContentType contentType) {
this.contentType = contentType;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getReturnPath() {
return returnPath;
}
public void setReturnPath(String returnPath) {
this.returnPath = returnPath;
}
public Date getSent() {
return sent;
}
public void setSent(Date sent) {
this.sent = sent;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<String> getTo() {
return to;
}
public void setTo(String to) {
this.to = Collections.singletonList(to);
}
public void setTo(List<String> to) {
this.to = to;
}
public List<EmailAttachment> getAttachments() {
return attachments;
}
public void setAttachments(List<EmailAttachment> attachments) {
this.attachments = attachments;
}
public boolean equals(Object object) {
boolean equals = false;
if (object instanceof Email) {
Email that = (Email) object;
equals = Objects.equal(this.from, that.from)
&& Objects.equal(this.to, that.to)
&& Objects.equal(this.subject, that.subject)
&& Objects.equal(this.content, that.content);
}
return equals;
}
}
I don't understand these findings, how to solve this.
I have added Lombok with #Getter & #Setter annotation to resolve this issue.

How to import data from csv to elasticsearch in java without using logstash?

I want to import data from a csv file to elasticsearch. But I don't want to use logstatsh. So, what are the ways I can do this ?
Any blogs ? Docs ?
I came across TransportClient, but I'm not getting the point from where to start .
Thanks in advance.
very late answer, however :) ….This is for elasticsearch 7.6.0
//this class for keeping csv each row values
public class Document {
private String id;
private String documentName;
private String name;
private String title;
private String dob;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
public String getName() {
return name1;
}
public void setName(String name1) {
this.name1 = name1;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
}
public void bulkInsert() {
long starttime = System.currentTimeMillis();
logger.debug("ElasticSearchServiceImpl => bulkInsert Service Started");
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
BulkRequest request;
Document document;
//elastic Search Index Name
String esIndex = "post";
try {
br = new BufferedReader(new FileReader(<path to CSV>));
request = new BulkRequest();
while ((line = br.readLine()) != null) {
// use comma as separator
String[] row = line.split(cvsSplitBy);
if(row.length >= 1) {
//filling Document object using csv columns array
document = getDocEntity(row);
//adding each filled obect into BulkRequest
request.add(getIndexRequest(document, esIndex));
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : null row ="+row.toString());
}
}
br.close();
if(request.numberOfActions()>0) {
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
if(bulkResponse.hasFailures()) {
logger.error("ElasticSearchServiceImpl => bulkInsert : Some of the record has failed.Please reinitiate the process");
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : Success");
}
} else {
logger.info("ElasticSearchServiceImpl => bulkInsert : No request for BulkInsert ="+request.numberOfActions());
}
} catch (Exception e) {
logger.error("ElasticSearchServiceImpl => bulkInsert : Exception =" + e.getMessage());
}
long endTime = System.currentTimeMillis();
logger.info("ElasticSearchServiceImpl => bulkInsert End" + Util.DB_AVG_RESP_LOG + "" + (endTime - starttime));
}
public static Document getDocEntity(String[] row)throws Exception {
Document document = new Document();
document.setId(UUID.randomUUID().toString());
for(int i=0;i<row.length;i++) {
switch (i) {
case 0:
document.setDocumentName(row[i]);
break;
case 1:
document.setName(row[i]);
break;
case 7:
document.setTitle(row[i]);
break;
case 8:
document.setDob(row[i]);
break;
}
return document;
}
public static IndexRequest getIndexRequest(Document document,String index)throws Exception {
IndexRequest indexRequest = null;
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("doc_name",document.getDocumentName());
jsonMap.put("title",document.getTitle());
jsonMap.put("dob",document.getDob());
indexRequest = new IndexRequest(index).id(document.getId()).source(jsonMap);
return indexRequest;
}
If you need to show each response, you can use the following code for responses
for (BulkItemResponse bulkItemResponse : bulkResponse) {
DocWriteResponse itemResponse = bulkItemResponse.getResponse();
switch (bulkItemResponse.getOpType()) {
case INDEX:
case CREATE:
IndexResponse indexResponse = (IndexResponse) itemResponse;
break;
}
}
For more information please read official link

How to update/refresh list items of list view in oracle maf?

I have list of tasks. When I delete my one of the task my list still shows that task in the list but on server side i have updated list I am not able to refresh my list. I am getting new task array from server but not able to show it. When I launched my app again then it is showing the updated list. How can I get updated list without killing the app? Both the times I have updated array but not able to show it on the view.
public class ModelClass {
private String message;
private String statusCode;
private Response[] res = null;
protected transient PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
public ModelClass() {
super();
clickEvent(new ActionEvent());
}
public static String taskId;
public void setTaskId(String taskId) {
System.out.print(taskId);
this.taskId = taskId;
}
public String getTaskId() {
return taskId;
}
public PropertyChangeSupport getPropertyChangeSupport() {
return _propertyChangeSupport;
}
public void setMessage(String message) {
String oldMessage = this.message;
this.message = message;
_propertyChangeSupport.firePropertyChange("message", oldMessage, message);
}
public String getMessage() {
return message;
}
public void setStatusCode(String statusCode) {
String oldStatusCode = this.statusCode;
this.statusCode = statusCode;
_propertyChangeSupport.firePropertyChange("statusCode", oldStatusCode, statusCode);
}
public String getStatusCode() {
return statusCode;
}
public void setRes(Response[] res) {
Response[] oldRes = this.res;
this.res = res;
System.out.println(res);
_propertyChangeSupport.firePropertyChange("res", oldRes, res);
System.out.println("refreshing here ");
}
public Response[] getRes() {
return res;
}
#Override
public String toString() {
return "ClassPojo [response = " + res + ", message = " + message + ", statusCode = " + statusCode + "]";
}
public void addPropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.removePropertyChangeListener(l);
}
public class Response {
private String taskId;
private String taskType;
private Integer taskTime;
private String taskName;
private PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
Response(String taskId, String taskType, String taskName) {
super();
this.taskId = taskId;
this.taskType = taskType;
this.taskName = taskName;
}
public void setTaskId(String taskId) {
String oldTaskId = this.taskId;
this.taskId = taskId;
_propertyChangeSupport.firePropertyChange("taskId", oldTaskId, taskId);
}
public String getTaskId() {
return taskId;
}
public void setTaskType(String taskType) {
String oldTaskType = this.taskType;
this.taskType = taskType;
_propertyChangeSupport.firePropertyChange("taskType", oldTaskType, taskType);
}
public String getTaskType() {
return taskType;
}
public void setTaskTime(Integer taskTime) {
Integer oldTaskTime = this.taskTime;
this.taskTime = taskTime;
_propertyChangeSupport.firePropertyChange("taskTime", oldTaskTime, taskTime);
}
public Integer getTaskTime() {
return taskTime;
}
public void setTaskName(String taskName) {
String oldTaskName = this.taskName;
this.taskName = taskName;
_propertyChangeSupport.firePropertyChange("taskName", oldTaskName, taskName);
}
public String getTaskName() {
return taskName;
}
#Override
public String toString() {
return "ClassPojo [taskId = " + taskId + ", taskType = " + taskType + ", taskTime = " + taskTime +
", taskName = " + taskName + "]";
}
public void addPropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.removePropertyChangeListener(l);
}
}
protected transient ProviderChangeSupport providerChangeSupport = new ProviderChangeSupport(this);
public void addProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.addProviderChangeListener(l);
}
public void removeProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.removeProviderChangeListener(l);
}
public void clickEvent(ActionEvent actionEvent) {
try {
JSONObject paramsMap = new JSONObject();
paramsMap.put("userId", "1");
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/#########");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(120000);
httpURLConnection.setConnectTimeout(120000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
os.write(paramsMap.toString().getBytes());
bufferedWriter.flush();
bufferedWriter.close();
os.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
builder.append(line + "\n");
line = bufferedReader.readLine();
}
is.close();
if (httpURLConnection != null)
httpURLConnection.disconnect();
System.out.println(builder.toString());
JSONObject json = new JSONObject(builder.toString());
String status = json.optString("statusCode");
String message = json.optString("message");
String response = json.optString("response");
System.out.println(status);
System.out.println(message);
// System.out.println(response);
JSONArray objarr = json.optJSONArray("response");
Response[] temp_res = new Response[objarr.length()];
for (int i = 0; i < objarr.length(); i++) {
System.out.println(objarr.getJSONObject(i));
JSONObject obj = objarr.getJSONObject(i);
String task = obj.optString("taskName");
taskId = obj.optString("taskId");
String taskType = obj.optString("taskType");
System.out.println(task);
System.out.println(taskId);
System.out.println(taskType);
temp_res[i] = new Response(taskId, taskType, task);
}
setRes(temp_res);
} else {
if (httpURLConnection != null)
httpURLConnection.disconnect();
System.out.println("Invalid response from the server");
}
} catch (Exception e) {
e.printStackTrace();
if (httpURLConnection != null)
httpURLConnection.disconnect();
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think you need to add providerChangeSupport.fireProviderRefresh("res");
and you have to make public method for providerChangeSupport.
Here is the link : https://community.oracle.com/message/13203364#13203364
Other than the fix suggested by Rashi Verma, there is one more change required.
The code snippet:
res = (Response[]) res_new.toArray(new Response[res_new.size()]);
setRes(res);
needs to be changed to:
Response[] temp_res;
temp_res = (Response[]) res_new.toArray(new
Response[res_new.size()]);
setRes(temp_res);
Currently, because the value of res is changed before invoking setRes, the propertyChangeEvent is not fired inside setRes. Both this propertyChangeEvent and the providerRefresh are needed for the changes you are making to start reflecting on the UI.

Regarding DataControl in adf

I am developing an ADF web application with Oracle EBS as the backend to call the procedure(Jdeveloper 12 c).
I have invoked a method calling EBS procedure (return type is list) and the result is stored in arraylist. the list is used to create Data control.
What my problem is i have set values to the data control but when i added that dc to view it shows nothing. But on debugging it shows all the values are set in the array list.
Bean class calling EBS procedure in ApplicationModule
BindingContainer bindings = getBindings();
OperationBinding operationBinding = (OperationBinding) bindings.getOperationBinding("getIexpenseLogin");
List<EmployeePojo> result = (List<EmployeePojo>) operationBinding.execute();
System.out.println("Result= " + result);
employeeDC.getEmployeeLogin(result); // Here the list is passed to the Employee DC class to create data controll.
ApplicationModule Containing Custom Procedure
public List getIexpenseLogin(String username,String password){
CallableStatement cs=null;
List<EmployeePojo> empList=new ArrayList<>();
try{
cs=getDBTransaction().createCallableStatement("begin xx_oie_mob_login.oie_mob_login(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?); end;",0);
cs.setString(1,username);
cs.setString(2, password);
cs.registerOutParameter(3, Types.NUMERIC);
cs.registerOutParameter(4, Types.VARCHAR);
cs.registerOutParameter(5, Types.VARCHAR);
cs.registerOutParameter(6, Types.NUMERIC);
cs.registerOutParameter(7, Types.VARCHAR);
cs.registerOutParameter(8, Types.NUMERIC);
cs.registerOutParameter(9, Types.VARCHAR);
cs.registerOutParameter(10, Types.NUMERIC);
cs.registerOutParameter(11, Types.VARCHAR);
cs.registerOutParameter(12, Types.NUMERIC);
cs.registerOutParameter(13, Types.BLOB);
cs.registerOutParameter(14, Types.VARCHAR);
cs.registerOutParameter(15, Types.VARCHAR);
cs.executeUpdate();
if(cs!=null)
{
EmployeePojo ePojo=new EmployeePojo();
ePojo.setEmployeeId(cs.getString(3));
ePojo.setEmployeeName(cs.getString(4));
ePojo.setEmployeeNumber(cs.getString(5));
ePojo.setManagerId(cs.getString(6));
ePojo.setManagerName(cs.getString(7));
ePojo.setJobId(cs.getString(8));
ePojo.setJobName(cs.getString(9));
ePojo.setOrgId(cs.getString(10));
ePojo.setOrgName(cs.getString(11));
ePojo.setImgId(cs.getString(12));
ePojo.setImage(cs.getBlob(13));
empList.add(ePojo);
}
return empList;
}catch(SQLException e){
throw new JboException(e);
}
}
EmployeeDC class used to create Data controll
public class EmployeeDC {
public EmployeeDC() {
super();
}
BindingContainer bindings = null;
private List<EmployeePojo> employee_data_controll=null;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void setEmployee_data_controll(List<EmployeePojo> employee_data_controll) {
List<EmployeePojo> oldEmployee_data_controll = this.employee_data_controll;
this.employee_data_controll = employee_data_controll;
propertyChangeSupport.firePropertyChange("employee_data_controll", oldEmployee_data_controll,
employee_data_controll);
}
public List<EmployeePojo> getEmployee_data_controll() {
return employee_data_controll;
}
public void setPropertyChangeSupport(PropertyChangeSupport propertyChangeSupport) {
PropertyChangeSupport oldPropertyChangeSupport = this.propertyChangeSupport;
this.propertyChangeSupport = propertyChangeSupport;
propertyChangeSupport.firePropertyChange("propertyChangeSupport", oldPropertyChangeSupport,
propertyChangeSupport);
}
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
public void getEmployeeLogin(List<EmployeePojo> result) {
setEmployee_data_controll(result);
getEmployee_data_controll();
System.out.println("DataControl=>"+getEmployee_data_controll().get(0));
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
EmployeePojo Class
public class EmployeePojo {
private String employeeId;
private String employeeName;
private String employeeNumber;
private String managerId;
private String managerName;
private String jobId;
private String jobName;
private String orgId;
private String orgName;
private String imgId;
private Blob image;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void setPropertyChangeSupport(PropertyChangeSupport propertyChangeSupport) {
this.propertyChangeSupport = propertyChangeSupport;
}
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
public void setEmployeeId(String employeeId) {
String oldEmployeeId = this.employeeId;
this.employeeId = employeeId;
propertyChangeSupport.firePropertyChange("employeeId", oldEmployeeId, employeeId);
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeName(String employeeName) {
String oldEmployeeName = this.employeeName;
this.employeeName = employeeName;
propertyChangeSupport.firePropertyChange("employeeName", oldEmployeeName, employeeName);
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeNumber(String employeeNumber) {
String oldEmployeeNumber = this.employeeNumber;
this.employeeNumber = employeeNumber;
propertyChangeSupport.firePropertyChange("employeeNumber", oldEmployeeNumber, employeeNumber);
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setManagerId(String managerId) {
String oldManagerId = this.managerId;
this.managerId = managerId;
propertyChangeSupport.firePropertyChange("managerId", oldManagerId, managerId);
}
public String getManagerId() {
return managerId;
}
public void setManagerName(String managerName) {
String oldManagerName = this.managerName;
this.managerName = managerName;
propertyChangeSupport.firePropertyChange("managerName", oldManagerName, managerName);
}
public String getManagerName() {
return managerName;
}
public void setJobId(String jobId) {
String oldJobId = this.jobId;
this.jobId = jobId;
propertyChangeSupport.firePropertyChange("jobId", oldJobId, jobId);
}
public String getJobId() {
return jobId;
}
public void setJobName(String jobName) {
String oldJobName = this.jobName;
this.jobName = jobName;
propertyChangeSupport.firePropertyChange("jobName", oldJobName, jobName);
}
public String getJobName() {
return jobName;
}
public void setOrgId(String orgId) {
String oldOrgId = this.orgId;
this.orgId = orgId;
propertyChangeSupport.firePropertyChange("orgId", oldOrgId, orgId);
}
public String getOrgId() {
return orgId;
}
public void setOrgName(String orgName) {
String oldOrgName = this.orgName;
this.orgName = orgName;
propertyChangeSupport.firePropertyChange("orgName", oldOrgName, orgName);
}
public String getOrgName() {
return orgName;
}
public void setImgId(String imgId) {
String oldImgId = this.imgId;
this.imgId = imgId;
propertyChangeSupport.firePropertyChange("imgId", oldImgId, imgId);
}
public String getImgId() {
return imgId;
}
public void setImage(Blob image) {
Blob oldImage = this.image;
this.image = image;
propertyChangeSupport.firePropertyChange("image", oldImage, image);
}
public Blob getImage() {
return image;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}

Upload File data into database using spring mvc and hibernate

I need to upload data into 2 database tables(factory and factoryType) using the below form but it isnt working can somebody take a look :
Factory table:factoryId,factoryname
FactoryType table: factoryType,factoryTypeId
FactoryConf table: factoryID,factoryTypeId
We are using hibernate for the database operations.
Model:
#Entity
#Table(name = "FactoryConf", uniqueConstraints = {
#UniqueConstraint(columnNames = { "factoryId" } )
})
public class FactoryConf {
#Id
long factoryId;
#OneToOne
#JoinColumn(name = "factoryId", insertable = false, updatable = false)
Factory factory;
#ManyToOne(optional = false)
#JoinColumn(name = "factoryTypeId")
FactoryType factoryType;
public FactoryConf() {
super();
}
public FactoryConf(long factoryId, FactoryType factoryType) {
super();
this.factoryType = factoryType;
this.factoryId = factoryId;
}
public Factory getFactory() {
return factory;
}
public void setFactory(Factory factory) {
this.factory = factory;
}
public FactoryType getFactoryType() {
return factoryType;
}
public void setFactoryType(FactoryType factoryType) {
this.factoryType = factoryType;
}
public long getFactoryId() {
return factoryId;
}
public void setFactoryId(long factoryId) {
this.factoryId = factoryId;
}
public FactoryType getFactoryTypeByFactoryID(long factoryId){
return factoryType;
}
}
Bean class:
/**
* This bean is defined to parse each record from the CSV file.
* All records are mapped to instances of this bean class.
*
*/
public class FactoryCSVFileInputBean {
private String upload_id;
private String file_name;
private byte file_data;
private long Id;
private String Name;
private String Type;
//getter setters
}
CSV parsing:
/**
* This class is defined for following actions
* 1. Validate the input CSV file format, header columns.
* 2. Parse the CSV file into a list of beans.
* 3. Validate input records with missing data and prepare a valid factory list to be processed. *
*/
public class FactoryCSVUtil {
private static Log log = LogFactory.getLog(FactoryCSVUtil.class);
private static final List<String> fileHeaderFields = new ArrayList<String>();
private static final String UTF8CHARSET = "UTF-8";
static{
for (Field f : FactoryCSVFileInputBean.class.getDeclaredFields()) {
fileHeaderFields.add(f.getName());
}
}
public static List<FactoryCSVFileInputBean> getCSVInputList(InputStream inputStream){
CSVReader reader = null;
List<FactoryCSVFileInputBean> csvList = null;
FactoryCSVFileInputBean inputRecord = null;
String[] header = null;
String[] row = null;
try {
reader = new CSVReader(new InputStreamReader(inputStream,UTF8CHARSET));
csvList = new ArrayList<FactoryCSVFileInputBean>();
header = reader.readNext();
boolean isEmptyLine = true;
while ((row = reader.readNext()) != null) {
isEmptyLine = true;
if(!(row.length==1 && StringUtils.isBlank(row[0]))){//not an empty line, not even containing ','
inputRecord = new FactoryCSVFileInputBean();
isEmptyLine = populateFields(inputRecord, header, row);
if(row.length != header.length)
//inputRecord.setUploadStatus("Not Loaded - Missing or invalid Data");
if(!isEmptyLine)
csvList.add(inputRecord);
}
}
} catch (IOException e) {
log.debug("IOException while accessing FactoryCSVFileInputBean: " + e);
return null;
} catch (IllegalAccessException e) {
log.debug("IllegalAccessException while accessing FactoryCSVFileInputBean: " + e);
return null;
} catch (InvocationTargetException e) {
log.debug("InvocationTargetException while copying FactoryCSVFileInputBean properties: " + e);
return null;
} catch (Exception e) {
log.debug("Exception while parsing CSV file: " + e);
return null;
}finally{
try{
if(reader!=null)
reader.close();
}catch(IOException ioe){}
}
return csvList;
}
protected static boolean populateFields(FactoryCSVFileInputBean inputRecord,String[] header, String[] row) throws IllegalAccessException, InvocationTargetException {
boolean isEmptyLine = true;
for (int i = 0; i < row.length; i++) {
String val = row[i];
if(!StringUtils.isBlank(val)){
BeanUtilsBean.getInstance().copyProperty(inputRecord, header[i], val);
isEmptyLine = false;
} else {
//inputRecord.setUploadStatus(String.format("Not Loaded - Missing or invalid Data for:%s",header[i]));
}
}
return isEmptyLine;
}
public static void validateInputFile(CommonsMultipartFile csvFile, Model model){
InputStream inputStream = null;
CSVReader reader = null;
String fileName = csvFile.getOriginalFilename();
String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
if(fileExtension.toUpperCase().equals("CSV")){
try{
inputStream = csvFile.getInputStream();
reader = new CSVReader(new InputStreamReader(inputStream,UTF8CHARSET));
String[] header = reader.readNext();
if(header!=null){
for (int i = 0; i < header.length; i++) {
if(!header[i].equals("") && !fileHeaderFields.contains(header[i])){
log.debug("Invalid Column found in upload file: " + header[i]);
model.addAttribute("failureMsg", "Invalid Column found in upload file: " + header[i]);
break;
}
}
for(csvHeaderFieldsEnum field : csvHeaderFieldsEnum.values()){
if(!Arrays.asList(header).contains(field.getValue())){
log.debug("Missing column in upload file: " + field.getValue());
model.addAttribute("failureMsg", "Missing column in upload file: " + field.getValue());
break;
}
}
}else{
model.addAttribute("failureMsg", "File is Empty - Please select a valid file");
}
String[] data = reader.readNext();
if(data==null){
log.debug("Empty file with header - No data found");
model.addAttribute("failureMsg", "Empty file with header - No data found");
}
}catch(IOException e){
log.debug("IOException in reading the CSV file: " + e);
model.addAttribute("failureMsg", "Exception in reading the CSV file");
}finally{
if(reader!=null)
try{
reader.close();
}catch(IOException e){ log.debug("IOException in closing reader of CSV file: " + e);}
}
}
else{
model.addAttribute("failureMsg", "Invalid file format - Please select a CSV file");
}
}
}
Model
public class FactoryUploadForm {
private CommonsMultipartFile fileData;
private String uploadComment;
/**
* #return the fileData
*/
public CommonsMultipartFile getFileData() {
return fileData;
}
/**
* #param fileData the fileData to set
*/
public void setFileData(CommonsMultipartFile fileData) {
this.fileData = fileData;
}
/**
* #return the uploadComment
*/
public String getUploadComment() {
return uploadComment;
}
/**
* #param uploadComment the uploadComment to set
*/
public void setUploadComment(String uploadComment) {
this.uploadComment = uploadComment;
}
public String toString(){
return " CSVFileName: " + getFileData().getOriginalFilename() + "; Upload Comment: " + uploadComment;
}
}
Controller
#Controller
public class FactoryUploadDownloadController {
private static final Log logger = LogFactory.getLog(FactoryUploadDownloadController.class);
#Resource
Service Service;
#Resource
FactoryUploadRepository repository;
#RequestMapping(value = "/submitUploadFactoryForm")
public String uploadFactory(FactoryUploadForm uploadform,
HttpServletRequest request, Model model, BindingResult result) {
logger.debug("====================================================================");
List<FactoryCSVFileInputBean> csvList = null;
List<FactoryType> factoryTypes = Service.getFactoryTypes();
try {
CommonsMultipartFile file = uploadform.getFileData();
// parse csv file to list
csvList = FactoryCSVUtil.getCSVInputList(file.getInputStream());
if (csvList == null) {
model.addAttribute("failureMsg","Error in file parsing - Please verify the file");
logger.debug("---------------------------------------------------------");
return "sucess";
}
} catch (Exception e) {
logger.debug("sorry this isn't working for you");
}
try {
CommonsMultipartFile file = uploadform.getFileData();
for (FactoryCSVFileInputBean inputRecord : csvList) {
Factory factoryentity = new Factory();
factoryentity.setId(inputRecord.getId());
factoryentity.setName(inputRecord.getName());
factoryentity = this.Service.saveFactory(factoryentity);
FactoryConf factoryconf = new FactoryConf();
factoryconf.setFactory(factoryentity);
factoryconf.setFactoryType(pickFactoryType(factoryTypes,inputRecord.getType()));
model.addAttribute("factoryconf", factoryconf);
this.Service.savefactoryCfg(factoryconf);
}
} catch (Exception e) {
logger.debug("sorry this isnt working for you");
}
return "success";
}
private FactoryType pickFactoryType(List<FactoryType> types, String typeName) {
for (FactoryType type : types) {
if (type.getFactoryType().equalsIgnoreCase(typeName))
return type;
}
throw new RuntimeException(String.format("Factory Type Invalid :%s", typeName));
}
}
From your question, I understand that you are not able to parse data from a CSV file. Here is sample code for similar task. I think it should help.

Resources