Send multiple files from angular typescript to spring and return as zip folder for downloading? - spring

I want to send multiple files in an array to spring and create a zip folder for downloading

UploadController:
#Autowired
StorageService storageService;
#PostMapping("/upload")
public ResponseEntity<ResponseMessage> uploadFiles(#RequestParam("files") MultipartFile[] files) {
String message = "";
try {
storageService.zip(files);
message = "Uploaded the files successfully";
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = "Fail to upload files!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
StorageService
public void zip(MultipartFile[] files) {
List<Path> filepaths = new ArrayList();
for (MultipartFile file : files) {
Path filepath = Paths.get("my/tmp/dir", file.getOriginalFilename());
filepaths.add(filepath);
try (OutputStream os = Files.newOutputStream(filepath)) {
os.write(file.getBytes());
}
}
File zip = new File("path/to/my/zip");
try { zip.createNewFile(); }
FileOutputStream output = null;
try { output = new FileOutputStream(zip); }
ZipOutputStream out = new ZipOutputStream(output);
try {
for (Path filepath : filepaths) {
File f = new File(filepath);
FileInputStream input = new FileInputStream(f);
ZipEntry e = new ZipEntry(f.getName());
out.putNextEntry(e);
byte[] bytes = new byte[1024];
int length;
while((length = input.read(bytes)) >= 0) {
out.write(bytes, 0, length);
}
input.close();
}
out.close();
output.close();
}
}

Related

Return a new thymeleaf page fragment and some file from spring controller

Tell me how to properly implement the spring controller. I want it to return a new thymeleafe page fragment and Excel file at the same time.
I know how to implement a controller to return a page fragment:
#GetMapping("/some_url")
public String updateFragment(Model model) {
model.addAttribute("attribute", someAtribute);
return "some_page :: fragment";
}
And I know how to implement a controller for downloading files:
#GetMapping("some_url")
public void getReport(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=file.xlsx";
response.setHeader(headerKey, headerValue);
try {
FileInputStream inputStream = new FileInputStream(new File("path_to_file"));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int row = 12;
Row exampleRow = sheet.getRow(12);
int count = 1;
for (SIZForKomplex s : objectList) {
if (s.getNumber() != 0) {
sheet.getRow(row).setRowStyle(exampleRow.getRowStyle());
sheet.getRow(row).setHeight(exampleRow.getHeight());
for (int i = 0; i < 8; i++) {
sheet.getRow(row).getCell(i).setCellStyle(exampleRow.getCell(i).getCellStyle());
}
sheet.getRow(row).getCell(0).setCellValue(count);
sheet.getRow(row).getCell(1).setCellValue(s.getNomenclatureNumber());
sheet.getRow(row).getCell(2).setCellValue(s.getNamesiz());
sheet.getRow(row).getCell(3).setCellValue(s.getSize());
sheet.getRow(row).getCell(4).setCellValue(s.getHeight());
sheet.getRow(row).getCell(5).setCellValue(s.getNumber());
sheet.getRow(row).getCell(6).setCellValue(sizRepository.findById(s.getId()).orElseThrow().getEd_izm());
sheet.getRow(row).getCell(7).setCellValue(" ");
row++;
count++;
}
}
inputStream.close();
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException
ex) {
ex.printStackTrace();
}
}
But how do I combine this. I need to update the data on the page and download the Excel file

lose of ZLIB inputstream fails when using try with resources

i have function for decompressing zips with multiple entries. Sometimes an exception is catched that states "Unexpected end of ZLIB Input stream". In my opinion it is not possible because i am using try with resrsources.
private boolean decompress(final Path blf) {
final String pathToZip = blf.getParent().toString();
final byte[] buffer = new byte[8192];
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(blf.toFile()))) {
//We will unzip files in this folder
if (!Files.exists(Paths.get(pathToZip))) {
Files.createDirectory(Paths.get(pathToZip));
}
ZipEntry entry = zipInputStream.getNextEntry();
final Path pathToFile = Paths.get(pathToZip + "\\" + entry.getName());
//Faster procedure if the file already exists
if (Files.exists((pathToFile))) {
loggerAnalysis.log(new LogRecord(Level.INFO, "[Analysis]",
"File already exists, skipping" + pathToFile));
return true;
}
//Iterate over entries
while (entry != null) {
//If directory then create a new directory in uncompressed folder
if (entry.isDirectory()) {
loggerAnalysis.log(new LogRecord(Level.INFO, "[Analysis]",
"Creating Directory:" + pathToFile));
Files.createDirectories(pathToFile);
} else {
Files.createFile(pathToFile);
loggerAnalysis.log(new LogRecord(Level.INFO, "[Analysis]",
"File unzip: " + pathToFile.getFileName()));
try (FileOutputStream fileOutputStream = new FileOutputStream(pathToFile.toString())) {
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}
}
entry = zipInputStream.getNextEntry();
}
}
return true;
} catch (final IOException e) {
loggerAnalysis.log(new LogRecord(Level.ERROR, "[Analysis]", e.getMessage()));
return false;
}
}
best regards

Receive assets on Handheld

I'm sending files from wear to handheld side. I'm sending 4 or 5 files (2 of them are bigger) but everytime the handheld side only receives ONE of the bigger ones...
wear:
public void sendFile(String filename){
//BLE files
fileToArray("BLEdata/" + filename + "_RightDevice.txt", "/BLEdata/");
//send log file
fileToArray(filename + "_LOG.txt", "/LOGdata/");
//send GPS file
fileToArray("GPSdata/" + filename + "_GPS.txt", "/GPSdata/");
//send Report files
fileToArray("Report/" + filename + "_Report.txt", "/REPORTdata/");
//BLE files
fileToArray("BLEdata/" + filename + "_LeftDevice.txt", "/BLEdata/");
}
public void fileToArray(String filename, String path)
{
FileInputStream fileInputStream = null;
File file = new File(Environment.getExternalStorageDirectory() + "/TuneWear/" + filename);
System.out.println("PATH: " + file.getPath());
if(file.exists()){
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
WearResultsActivity main = (WearResultsActivity) getActivity();
long time = main.getInitTime();
if(filename.contains("_RightDevice")){
new SendToDataLayerThread(path + time, bFile, 2).start();
}else if (filename.contains("_LeftDevice")){
new SendToDataLayerThread(path + time, bFile, 1).start();
} else
new SendToDataLayerThread(path + time, bFile).start();
}catch(Exception e){
e.printStackTrace();
}
} else System.out.println("Doesn't exist:\n" + file.getPath());
}
class SendToDataLayerThread extends Thread {
String path;
byte[] bFile;
int footSide;
// Constructor for sending data objects to the data layer
SendToDataLayerThread(String p, byte[] bytes, int footside) {
path = p;
bFile = bytes;
footSide = footside;
}
SendToDataLayerThread(String p, byte[] bytes) {
path = p;
bFile = bytes;
}
public void run() {
WearResultsActivity main = (WearResultsActivity) getActivity();
GoogleApiClient googleClient = main.getGoogleClient();
Asset asset = Asset.createFromBytes(bFile);
System.out.println(asset.toString());
PutDataMapRequest dataMap = PutDataMapRequest.create(path);
dataMap.getDataMap().putLong("timestamp", Calendar.getInstance().getTimeInMillis());
dataMap.getDataMap().putLong("/InitialTime", ((WearResultsActivity) getActivity()).getInitTime());
dataMap.getDataMap().putAsset("asset", asset);
if(footSide == 1) {
dataMap.getDataMap().putInt("footside", footSide);
System.out.println("DATAMAP COM LEFT " + footSide);
}else if (footSide == 2) {
dataMap.getDataMap().putInt("footside", footSide);
System.out.println("DATAMAP COM RIGHT " + footSide);
}
PutDataRequest request = dataMap.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(googleClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
System.out.println("RESULT");
}
});
//Wearable.DataApi.putDataItem(googleClient, request);
}
}
Handheld:
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
System.out.println("COUNT " + dataEvents.getCount());
for (DataEvent event : dataEvents) {
DataItem item = event.getDataItem();
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
if (item.getUri().getPath().contains(LOGdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_LOG.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(GPSdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/GPSdata/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_GPS.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(REPORTdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/Report/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_Report.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(BLEdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/BLEdata/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = null;
System.out.println("FOOT SIIIIIIDE: " + dataMapItem.getDataMap().getInt("footside"));
if(dataMapItem.getDataMap().getInt("footside") == 1){
file = new File(myDir, "Run_" + fileName + "_LeftDevice.txt");
System.out.println("FILE: " + file.getPath());
} else if(dataMapItem.getDataMap().getInt("footside") == 2){
file = new File(myDir, "Run_" + fileName + "_RightDevice.txt");
System.out.println("FILE: " + file.getPath());
}
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
}
catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
System.out.println("DataItem deleted: " + event.getDataItem().getUri());
}
//Wearable.DataApi.deleteDataItems(googleClient, event.getDataItem().getUri(), DataApi.FILTER_PREFIX);
}
}
I only receive the GPS, Report and LOG data every time. The other 2 files I only receive ONE... Im sending them exactly the same way, but I'm receiving only one of them.
Does anyone detects the error on my code???
EDIT
I just discovered that if the smartwatch is connected to the handheld at the time that the files are sent, they are all received. If they are not connected, one of the files (RightDevice.txt or LeftDevice.txt) are not received when they connect...
I solved it!
It was the most basic error of all.... I was sending the same path for the two files (RightDevice and LeftDevice) so only one of the objects was updated on the googleapiclient.

File is getting locked on read/write operation in C#

A third party application is reading the output text file of my windows application,it is getting paused.I think,it is happening because of file gets locked either on writing or reading.how can i make this work fine.Please see my code.
List<string> fileList = new List<string>();
System.Timers.Timer timer;
string currentfilename;
string currentcontent;
public Service1()
{
//
timer = new System.Timers.Timer();
timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
throw new NotImplementedException();
}
private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
{
DateTime LastChecked = DateTime.Now;
try
{
string[] files = System.IO.Directory.GetFiles(#"C:\Journal", "*.jrn", System.IO.SearchOption.AllDirectories);
foreach (string file in files)
{
if (!fileList.Contains(file))
{
currentfilename = file;
fileList.Add(file);
copywarehouse(file);
try
{
string sourcePath = #"C:\Journal";
string sourceFile = System.IO.Path.Combine(sourcePath, file);
using (FileStream fs= new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
currentcontent = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception ex)
{
throw (ex);
}
}
}
try
{
string sourcePath1 = #"C:\Journal";
string currentfilecontent;
string sourceFile1 = System.IO.Path.Combine(sourcePath1, currentfilename);
using (FileStream fs = new FileStream(sourceFile1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
currentfilecontent = sr.ReadToEnd();
sr.Close();
}
if (currentfilecontent != currentcontent)
{
if (currentfilecontent.Contains(currentcontent))
{
string originalcontent = currentfilecontent.Substring(currentcontent.Length);
File.WriteAllText(#"C:\Journal\tempfile.txt", originalcontent + "\r\n");
using (FileStream fs = new FileStream(#"C:\Journal\tempfile.txt", FileMode.OpenOrCreate))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(originalcontent);
sw.Close();
}
currentcontent = currentfilecontent;
}
}
}
//}
catch (Exception ex)
{
throw (ex);
}
TimeSpan ts = DateTime.Now.Subtract(LastChecked);
TimeSpan MaxWaitTime = TimeSpan.FromMilliseconds(100);
if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
timer.Interval = MaxWaitTime.Subtract(ts).Milliseconds;
else
timer.Interval = 1;
timer.Start();
}
catch (Exception ex)
{
throw (ex);
}
}
private void copywarehouse(string filename)
{
string sourcePath = #"C:\Journal";
string targetPath = #"C:\Journal";
string copycontent=null;
try
{
string sourceFile = System.IO.Path.Combine(sourcePath, filename);
string destFile = System.IO.Path.Combine(targetPath, "tempfile.txt");
using (FileStream fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
copycontent = sr.ReadToEnd();
sr.Close();
}
using (FileStream fs = new FileStream(destFile, FileMode.Append))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(copycontent);
sw.Close();
}
}
catch (Exception ex)
{
throw (ex);
}
}
Here the problem is with third party application which is reading my application output as input.it is not allowing access to more than one file content..

Error "Operation not permitted on IsolatedStorageFileStream." wp7

I am trying to read a text file from IsolatedStorage and check it contains a string. If not, the string is added to the end of the file. But When I am trying to write the string into file I got an error: "Operation not permitted on IsolatedStorageFileStream.". My code shown below. How can I overcome this problem?
public void AddToDownloadList()
{
IsolatedStorageFile downloadFile=IsolatedStorageFile.GetUserStoreForApplication();
try
{
string downloads = string.Empty;
if (!downloadFile.DirectoryExists("DownloadedFiles"))
downloadFile.CreateDirectory( "DownloadedFiles" );
if(downloadFile.FileExists("DownloadedFiles\\DownloadList.txt"))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile("DownloadedFiles\\DownloadList.txt",FileMode.Open, FileAccess.Read );
using ( StreamReader reader = new StreamReader( downloadStream ) )
{
downloads = reader.ReadToEnd();
reader.Close();
}
downloadFile.DeleteFile( "DownloadedFiles\\DownloadList.txt" );
}
downloadFile.CreateFile( "DownloadedFiles\\DownloadList.txt" );
string currentFile = FileName;
if ( !downloads.Contains( currentFile ) )
{
downloads += currentFile;
using ( StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "DownloadedFiles\\DownloadList.txt", FileMode.Create, FileAccess.Write, downloadFile ) ) )
{
writeFile.Write( currentFile + "," );
writeFile.Close();
}
}
}
catch ( Exception ex )
{
string message = ex.Message;
}
}
I think the problem you were having has to do with the line where you create the StreamWriter by newing up the IsolatedStorageFileStream - when you already should have the right one from the return of the downloadFile.CreateFile() call.
Try this code, I think it does what you want to do:
public static void AddToDownloadList()
{
try
{
AddToDownloadList("DownloadedFiles", "this file name", "DownloadedFiles\\DownloadList.txt");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
}
}
public static void AddToDownloadList(string directory, string fileName, string filePath)
{
string downloads = string.Empty;
using (IsolatedStorageFile downloadFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!downloadFile.DirectoryExists(directory))
downloadFile.CreateDirectory(directory);
if (downloadFile.FileExists(filePath))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile(filePath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(downloadStream))
{
downloads = reader.ReadToEnd();
reader.Close();
}
}
string currentFile = fileName;
if (!downloads.Contains(currentFile))
{
downloadFile.DeleteFile(filePath);
using (IsolatedStorageFileStream stream = downloadFile.CreateFile(filePath))
{
downloads += currentFile;
using (StreamWriter writeFile = new StreamWriter(stream))
{
writeFile.Write(currentFile + ",");
writeFile.Close();
}
}
}
}
}

Resources