Uploading a file using Spring MVC not working [duplicate] - java

This question already has answers here:
How to upload only csv files into the server in Java
(3 answers)
Closed 7 years ago.
I am trying to upload a csv file and i intend to write success to the uploaded csv if the upload goes successfully. below is my code(this is not working as of now)
#RequestMapping(value = "/submitUploadCarForm")
public String uploadCar(CarUploadForm uploadform,HttpServletRequest request, Model model, BindingResult result) {
try {
CommonsMultipartFile file = uploadform.getFileData();
// parse csv file to list
csvList = CarCSVUtil.getCSVInputList(file.getInputStream());
for (CarCSVFileInputBean inputRecord : csvList) {
Car carentity = new Car();
carentity.setId(inputRecord.getId());
carentity.setName(inputRecord.getcarName());
carentity.setShortName(inputRecord.getcarShortName());
carentity.setEnvironment(inputRecord.getEnvironment());
carentity = this.Service.saveCar(carentity);
CarConfig compcfg = new CarConfig();
compcfg.setCar(carentity);
compcfg.setCarType(pickCarType(carTypes,inputRecord.getcarType()));
this.Service.saveCompCfg(compcfg);
inputRecord.setuploadstatus("success");<--- This is where i need help
}
}
catch (Exception e) {
e.printStackTrace();
result.rejectValue("name", "failureMsg","Error while uploading ");
model.addAttribute("failureMsg", "Error while uploading ");
}
return "view";
}

I am using this code to import csv file and data is store into database.Add opencsv jar file to your build path.
public String importCSV(#RequestParam("file") MultipartFile file,
HttpServletRequest req) throws IOException {
CsvToBean csv = new CsvToBean();
CSVReader reader = new CSVReader(new InputStreamReader(
file.getInputStream()), ',', '\"', 1);
ColumnPositionMappingStrategy maping = new ColumnPositionMappingStrategy();
maping.setType(tbBank.class);
String[] column = { "bankid", "bankname", "bankbranch" };
maping.setColumnMapping(column);
List banklist = csv.parse(maping, reader);
for (Object obj : banklist) {
tbBank bank = (tbBank) obj;
projectservice.insertBank(bank);
}
return "redirect:/bankview";
}

Related

No value present - cucumber json data driven

I've got a problem with data driven testing in cucumber. I want to get data from json file. I've prepared scenario:
Feature: data provider
Scenario Outline: Data driven using json file
Given account user
And Get System Variables
And Delete TB report if already exist
When user navigates to TB report
Then Select Filters On Reports Page from <data>
Example:
|data|
|test|
Data json object:
[
{
"fundName": "test",
"currentDate": "31/12/2020"
},
"fundName": "test2",
"currentDate": "31/12/2020"
}
Pojo class for storing data:
public class Data {
public String fundName;
public String currentDate;
}
Data json reader:
private final String path = "path/to/file";
private List<Data> data;
public JsonDataReader(){
DataList = getData();
}
private List<Data> getData() {
Gson gson = new Gson();
BufferedReader bufferReader = null;
try {
bufferReader = new BufferedReader(new FileReader(path));
Data[] data= gson.fromJson(bufferReader, Data[].class);
return Arrays.asList(data);
}catch(FileNotFoundException e) {
throw new RuntimeException("Json file not found at path : " + path);
}finally {
try { if(bufferReader != null) bufferReader.close();}
catch (IOException ignore) {}
}
}
public final Data getDataByName(String name){
return dataList.stream().filter(x -> x.fundName.equalsIgnoreCase(name)).findAny().get();
}
Step definition:
#Then("Select Filters On Reports Page from \\\"(.*)\\\"$")
public void selectMultipleFilters(String name) {
Data data = FileReaderManager.getInstance().getJsonDataReader().getFundByName(name);
reportSteps.selectMultipleFiltersForReports(data);
}
But when I try to run this I've got an error on 5th step:
java.util.NoSuchElementException: No value present
at JsonDataReader.getDataByName
Can someone tell me what am I doing wrong?

How to let user download -in backend generated- CSV file from frontend?

I am currently working on a web application. I created a button called "export", in the front end. A user click should trigger the download of a CSV file, which I generated in the back end. The CSV file is filled with values from a database table.
Do I need to generate a link to pass it to the front end button (maybe with JSON?)?
How should I proceed?
Additional information: The application is programmed with Java. The framework I use is Spring-Boot.
Code for generating CSV file
public class readDb {
public static List<Success> getDataFromDb (List<Success> success){
System.out.println("getDataFromDb");
erfolg.forEach(System.out::println);
return erfolg;
}
public static void successExport (List<Success> success) throws IOException {
String csvFile = "\\\\fs-vcs-02\\userhome\\username\\Desktop\\test.csv";
FileWriter writer = new FileWriter(csvFile);
CSVUtils.writeLine(writer, Arrays.asList("id", "endDate", "dataFromB", "dataToB", "dataToE", "report", "amountOfM", "rate", "amountOfA", "statistics", "resultP", "resultN", "resultO", "chancel", "assignmentVolume));
for (Erfolg d : erfolg) {
List<String> list = new ArrayList<>();
list.add(d.getId().toString());
list.add(d.getEndDate().toString());
list.add(d.getDataFromB().toString());
list.add(d.getDataToB().toString());
list.add(d.getDataToE().toString());
list.add(d.getReport().toString());
list.add(d.getAmountOfM().toString());
list.add(d.getRate().toString());
list.add(d.getAmountOfA().toString());
list.add(d.getStatistics().toString());
list.add(d.getResultP().toString());
list.add(d.getResultN().toString());
list.add(d.getResultO().toString());
list.add(d.getChancel().toString());
list.add(d.getAssignmentVolume().toString());
CSVUtils.writeLine(writer, list);
}
writer.flush();
writer.close();
}
}
Code for file export
public static void export() {
File f = null;
boolean bool = false;
try {
f = new File("\\\\fs-vcs-02\\userhome\\agoenkur\\Desktop\\test.csv");
bool = f.createNewFile();
System.out.println("File created: "+bool);
f.delete();
System.out.println("delete() method is invoked");
bool = f.createNewFile();
System.out.println("File created: "+bool);
} catch(Exception e) {
e.printStackTrace();
}
}
}

Spring, FlatFileItemWriter write large file

I need to write a large file using FlatFileItemWriter.
When I call the write method, a OutOfMemory occurs.
Is there a way to write large files ?
My writer is defined like this :
FlatFileItemWriter<FieldSet> writer = new FlatFileItemWriter<>();
File mostRecent = <myFile>
FileSystemResource resource = new FileSystemResource(<myTmpFile>);
FileUtils.deleteQuietly(resource.getFile());
writer.setResource(resource);
DelimitedLineAggregator<FieldSet> delimitedLine = new DelimitedLineAggregator<>();
delimitedLine.setDelimiter(SEPARATOR);
writer.setLineAggregator(delimitedLine);
writer.setHeaderCallback(new FlatFileHeaderCallback() {
public void writeHeader(Writer writer) throws IOException
{
StringBuffer buffer = new StringBuffer();
for (Column column : Column.values())
{
buffer.append(column.getName());
buffer.append(SEPARATOR);
}
writer.write(CHAR_FOR_EXCEL + buffer.toString());
}
});
writer.open(new ExecutionContext());
writer.write(items);

Post data into MYSql db using REST

I am very new to Vaadin, REST and Vertx. I want to post the data into MYSQL db from a JSON file. So I have created a base url "localhost:1443" and am able to call the handler in the other project where db is connected. But don't know to to pass the JSON file my current project to the another project where the MYSQL is configured.
Here am calling the method which is defined in REST,
public OutputStream receiveUpload(String filename, String mimeType) {
FileOutputStream fos = null; // Output stream to write to
file = new
File(VaadinService.getCurrent().getBaseDirectory().getAbsolutePath()
+"/Jsonfile/" + filename);
FILE_PATH =
VaadinService.getCurrent().getBaseDirectory().getAbsolutePath()
+"/Jsonfile/" + filename;
try{
fos = new FileOutputStream(file);
JSONArray products =
productsDataProvider.uploadCatalogs(file.toString());
Notification.show("Succesfully converted :)");
}
catch (final java.io.FileNotFoundException e) {
// Error while opening the file. Not reported here.
e.printStackTrace();
return null;
}
return fos; // Return the output stream to write to
}
this is where I defined method,
public JSONArray uploadCatalogs(String catalogClass) {
return dataProviderUtil.getResourceArray("gapi/upload_products", new
HashMap<String, String>(){
{
put("class", catalogClass);
}
});
This is the product handler in another project,
router.mountSubRouter("/gapi/upload_products", new
UploadCatalog(VertxInstance.get()));
Here the class defined,
public class UploadCatalog extends AbstractRouteHandler {
private final static Logger LOG =
LogManager.getLogger(UploadCatalog.class);
public UploadCatalog(Vertx vertx) {
super(vertx);
this.route().handler(BodyHandler.create());
this.get("/").handler(this::upload);
}
private void upload(RoutingContext routingContext) {
LOG.info("hello");
}
i can see the logger info in console...
I tried the below one,
private void upload(RoutingContext routingContext) {
JsonObject paramsObject = routingContext.getBodyAsJson();
JsonObject result = new JsonObject();
Integer id = LocalCache.getInstance().store(new
QueryData("product.insert", paramsObject));
LOG.info("Executing query:" + "product.insert" );
vertx.eventBus().send(DatabaseService.DB_QUERY, id,
(AsyncResult<Message<Integer>> res) -> {
QueryData resultData = (QueryData)
LocalCache.getInstance().remove(res.result().body());
if (resultData.errorFlag ||
resultData.updateResult.getUpdated() == 0) {
/*result.put("status", "error").put("error", "Error
in creating user profile.");
response.putHeader("content-type",
"application/json").end(result.encode());*/
} else {
/*LOG.info("Insert query (ms):" +
resultData.responseTimeInMillis);
this.sendNewUserProfile(data, response);*/
}
});
}
How to insert data in mysql db from JSON file?

how to enhance this java class that reads xls file using POI and JXL?

I am currently using POI to read excel file and it is working great except it can't read xls files with older format (BIFF5/ office 95) to resolve this I am catching OldExcelFormatException and in this case call a function that will read the xls file using jxl. What I want to achieve is to write the same code but without catching the exception. Here is the current working code:
public void translate() throws IOException, CmpException
{
ArrayList<String> row = null;
try
{
// create a new org.apache.poi.poifs.filesystem.Filesystem
POIFSFileSystem poifs = new POIFSFileSystem(fin);
w = new HSSFWorkbook(poifs);
}
catch (OldExcelFormatException e) // OldExcelFormatException
{
w = null;
System.out.println("OldExcelFormatException");
translateBIFF5();
}
catch (Exception e) // Any Exception
{
w = null;
}
if (w != null)
{
// read the excel file using POI
}
}
private void translateBIFF5() throws IOException, CmpException
{
ArrayList<String> row = null;
try
{
jxl_w = Workbook.getWorkbook(excelFile);
}
catch (Exception e) // Any Exception
{
jxl_w = null;
}
if (jxl_w != null)
{
// read the excel file using jxl
}
}
Never mind guys. I found the solution by myself. The trick is to see the workbook name: For excel 95/97, the workbook name is 'Book' while for the new format the workbook name is 'WorkBook'. So here is the piece of coding I have been searching for:
POIFSFileSystem poifs = new POIFSFileSystem(fin);
DirectoryNode directory = poifs.getRoot();
Iterator<Entry> i = directory.getEntries();
while (i.hasNext())
{
Entry e = i.next();
String bookName = e.getName();
if (bookName.equals("Book"))
{
System.out.println("This is an old format");
}
else
{
System.out.println("This is a new format");
}
}

Categories

Resources