Spring Boot example how to download file from server - spring-boot

I have a Spring Boot web application and I need an example of how to download a file from the server.
Thanks,
R.

I have this running project of SpringBoot. Below is a part of code which outputs xlsx file.
WebController.java
#RequestMapping(value = {"/excel"}, method = RequestMethod.GET)
public void excel(HttpServletResponse response, #RequestParam("email") String email) {
try {
Query query = new Query();
query.addCriteria(Criteria.where("email").is(email));
if(email.equals(""))
query=new Query();
List<MQTT_Server_Detail> list = mongoTemplate.find(query, MQTT_Server_Detail.class, "owner");
response.addHeader("Content-disposition", "attachment; filename=Door.xlsx");
response.setContentType("application/vnd.ms-excel");
Workbook workbook = new XSSFWorkbook();
workbook.createSheet("owner");
workbook.setSheetName(0, "Owner");
Sheet sheet = workbook.getSheetAt(0);
sheet.createRow(0);
sheet.getRow(0).createCell(0).setCellValue("Owner Email");
sheet.getRow(0).createCell(1).setCellValue("Topic");
sheet.getRow(0).createCell(2).setCellValue("Device Name");
sheet.getRow(0).createCell(3).setCellValue("Device ID");
Row row;
int num = 1;
for (MQTT_Server_Detail a : list) {
Devices devices = getDevice(a.getEmail());
for (int i = 0; i < devices.getDevicesID().size(); i++) {
row = sheet.createRow(num++);
row.createCell(0).setCellValue(a.getEmail());
row.createCell(1).setCellValue(a.getTopic());
row.createCell(2).setCellValue((String) devices.getDevicesName().get(i));
row.createCell(3).setCellValue((String) devices.getDevicesID().get(i));
}
}
sheet = workbook.createSheet("Users");
row = sheet.createRow(0);
row.createCell(0).setCellValue("Name");
row.createCell(1).setCellValue("Device");
row.createCell(2).setCellValue("CardID");
row.createCell(3).setCellValue("Email");
row.createCell(4).setCellValue("Mobile");
row.createCell(5).setCellValue("Blocked");
row.createCell(6).setCellValue("Last in Date");
row.createCell(7).setCellValue("Last in Time");
row.createCell(8).setCellValue("Last out Date");
row.createCell(9).setCellValue("Last out Time");
row.createCell(10).setCellValue("Owner");
Criteria criteria[] = new Criteria[list.size()];
for (int i = 0; i < list.size(); i++) {
criteria[i] = Criteria.where("owner").is(list.get(i).getEmail());
}
List<Users_POJO> users_pojoList;
if (list.size() == 0)
users_pojoList = new ArrayList<>();
else
users_pojoList = mongoTemplate.find(new Query().addCriteria(new Criteria().orOperator(criteria)),
Users_POJO.class, "users");
for (int i = 0; i < users_pojoList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(users_pojoList.get(i).getName());
row.createCell(1).setCellValue(users_pojoList.get(i).getDevice());
row.createCell(2).setCellValue(users_pojoList.get(i).getCard_id());
row.createCell(3).setCellValue(users_pojoList.get(i).getEmail());
row.createCell(4).setCellValue(users_pojoList.get(i).getMobile());
row.createCell(5).setCellValue(users_pojoList.get(i).getBlocked());
row.createCell(6).setCellValue(users_pojoList.get(i).getLast_in_date());
row.createCell(7).setCellValue(users_pojoList.get(i).getLast_in_time());
row.createCell(8).setCellValue(users_pojoList.get(i).getLast_out_date());
row.createCell(9).setCellValue(users_pojoList.get(i).getLast_out_time());
row.createCell(10).setCellValue(users_pojoList.get(i).getOwner());
}
sheet = workbook.createSheet("Logs");
row = sheet.createRow(0);
row.createCell(0).setCellValue("CardID");
row.createCell(1).setCellValue("Device");
row.createCell(2).setCellValue("Date");
row.createCell(3).setCellValue("Time");
row.createCell(4).setCellValue("Count");
criteria = new Criteria[users_pojoList.size()];
for (int i = 0; i < users_pojoList.size(); i++) {
criteria[i] = Criteria.where("card_id").is(users_pojoList.get(i).getCard_id());
}
query = new Query();
query.addCriteria(new Criteria().orOperator(criteria));
List<Log_POJO> log_pojoList;
if (users_pojoList.size() == 0)
log_pojoList = new ArrayList<>();
else
log_pojoList = mongoTemplate.find(query, Log_POJO.class, "logs");
for (int i = 0; i < log_pojoList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(log_pojoList.get(i).getCard_id());
row.createCell(1).setCellValue(log_pojoList.get(i).getDevice());
String date = log_pojoList.get(i).getDay() + "-" + log_pojoList.get(i).getMonth() + "-" + log_pojoList.get(i).getYear();
row.createCell(2).setCellValue(date);
String time = log_pojoList.get(i).getHour() + "-" + log_pojoList.get(i).getMin() + "-" + log_pojoList.get(i).getSec();
row.createCell(3).setCellValue(time);
row.createCell(4).setCellValue(log_pojoList.get(i).getSerial_no());
}
workbook.write(response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
In short, you have to do this:
response.addHeader("Content-disposition", "attachment; filename=Door.xlsx");
response.setContentType("application/vnd.ms-excel");
//get the outputstream of response and write data to it

Spring Boot download file from server
#Controller
#RequestMapping(value = "/")
public class HomeController {
#RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"webpage.html\"");
InputStream inputStream = new FileInputStream(new File("C:\\MyWebPage\\webpage.html"));
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
inputStream.close();
};
}
}

Related

Spring Boot - REST API to Post file and return Zipped file in response

Im trying to receive a file from an HTTP POST which I split into individual files wand then need to return that in a zip file. I am trying to return the file and I have tried everything to return the file, but I am unable to recieve the file... any thoughts?
#RequestMapping(value = "/splitFile", headers = ("content-type=multipart/*"), produces ="application/zip", method = RequestMethod.POST)
public void SplitFile(#RequestParam(value = "file", required = true) MultipartFile[] file, HttpServletResponse response ) throws IOException {
for (int i = 0; i < file.length; i++) {
File uplFile = new File(file[i].getOriginalFilename());
uplFile.createNewFile();
FileOutputStream fos = new FileOutputStream(uplFile);
fos.write(file[i].getBytes());
fos.close();
System.out.println("Splitting File: " + uplFile.getName());
uploadHelper Help = new uploadHelper();
ArrayList<String> filestrings = new ArrayList<String>();
filestrings = uplHelp.GetSplitFiles(uplFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
StringBuilder sb = new StringBuilder();
int filenumber = 0;
for (String filedata : filestrings) {
filenumber = filenumber + 1;
sb.append(filedata);
ZipEntry e = new ZipEntry("file_" + filenumber + ".data");
zipOutputStream.putNextEntry(e);
byte[] data = sb.toString().getBytes();
zipOutputStream.write(data, 0, data.length);
zipOutputStream.closeEntry();
}
System.out.println("Splitting File - Split " + filestrings.size() + " files");
if (zipOutputStream != null) {
zipOutputStream.finish();
zipOutputStream.flush();
IOUtils.closeQuietly(zipOutputStream);
}
IOUtils.closeQuietly(bufferedOutputStream);
IOUtils.closeQuietly(out);
InputStream is = new ByteArrayInputStream(out.toByteArray());
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Content-Disposition", "attachment; filename=test.zip");
response.setCharacterEncoding("gzip");
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}
response.setStatus(HttpServletResponse.SC_ACCEPTED);
response.flushBuffer();
}

Can't find way to debug Internal Server Error (500) caused by new class

I've read a lot of the postings about 500 errors because of the channel emulator, but this is not the case here. I took the standard bot template, which works just fine with the emulator, and replaced it with
ConnectorClient connector = new ConnectorClient(new
Uri(activity.ServiceUrl));
// calculate something for us to return
// int length = (activity.Text ?? string.Empty).Length;
string responseText=
***Bot_Application2.SilviaRestClass.GetRestResult(activity.Text);***
So the issue is in executing the GetRestResult method in the SilivaRestClass.
The code itself works, I'm using it in lots of other places, as it basically sets up a simple 1)get an input utterance in text, 2)send to my SILVIA AI server, and 3)get an utterance back routine. I have a feeling it has something to do with either private vs public methods, and/or [Serializable], based on what I have read so far. The code (minus the credentials) is below. Many thanks, in advance, for any suggestions to try.
`
bool exit = false;
restResponse = "Hello";
bool sessionNew = true;
string viewMessage = null;
string SILVIAUri = "";
string SILVIACore = "/Core/Create/unique/silName";
string SILVIASubmit = "/IO/SetInputManaged/unique/hello";
string SILVIARead = "/IO/GetAll/unique";
string SILVIARelease = "/Core/Release/{unique}";
string SILVIASubKey = "";
string silName = "";
string returnMessage = null;
string holdit = null;
string holdit2 = null;
int forHold = 0;
string responseFromServer = null;
string isfalse = "false";
string myURI = null;
string unique = null;
//CREATE CORE from SILVIA SERVER
myURI = SILVIAUri + SILVIACore;
myURI = myURI.Replace("silName", silName);
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest request = WebRequest.Create(myURI);
request.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
if (sessionNew)
{
Random rnd1 = new Random();
unique = rnd1.Next().ToString() + "askgracie";
sessionNew = false;
WebResponse wResponse = request.GetResponse();
Stream dataStream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
// Clean up the streams and the response.
reader.Close();
wResponse.Close();
}
//SEND UTTERANCE to SILVIA
holdit = null;
myURI = null;
myURI = SILVIAUri + SILVIASubmit;
holdit = restResponse;
// holdit = HttpUtility.UrlEncode(holdit);
myURI = myURI.Replace("hello", holdit);
myURI = myURI.Replace("unique", unique);
if (holdit == "exit")
{
exit = true;
myURI = SILVIAUri + SILVIARelease;
}
System.Net.WebRequest sendRequest = WebRequest.Create(myURI);
sendRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse sendResponse = sendRequest.GetResponse();
Stream sendStream = sendResponse.GetResponseStream();
StreamReader sendReader = new StreamReader(sendStream);
string send_ResponseFromServer = sendReader.ReadToEnd();
// Clean up the streams and the response.
sendReader.Close();
sendResponse.Close();
holdit = send_ResponseFromServer;
forHold = holdit.IndexOf("success");
holdit2 = holdit.Substring(forHold + 9, 5);
if (holdit2 == isfalse)
{
var simpleUtterResponse = "The bot failed to send the
utterance to SILVIA";
}
//GETRESPONSES FROM SILVIA
returnMessage = null;
holdit = null;
responseFromServer = null;
myURI = SILVIAUri + SILVIARead;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest readRequest = WebRequest.Create(myURI);
readRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse readResponse = readRequest.GetResponse();
Stream readStream = readResponse.GetResponseStream();
StreamReader readReader = new StreamReader(readStream);
string read_ResponseFromServer = readReader.ReadToEnd();
viewMessage = read_ResponseFromServer;
string lastRead = "ID ";
List<string> myArray = new List<string>(viewMessage.Split(new
string[] { "\r\n" }, StringSplitOptions.None));
foreach (string s in myArray)
{
if (lastRead == "type: voice")
{
returnMessage = returnMessage + " " + s.Substring(8);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
}
// Clean up the streams and the response.
//readReader.Close();
//readResponse.Close();
if (exit)
{
myURI = SILVIAUri + SILVIARelease;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest closeRequest =
WebRequest.Create(myURI);
closeRequest.Headers["Ocp-Apim-Subscription-Key"] =
SILVIASubKey;
WebResponse closeResponse = closeRequest.GetResponse();
}
return returnMessage;
}
}
}`
I ended up resolving this by cut/paste the class inside the same namespace and physical .cs file. – Brian Garr just now edit

format export to excel using closedxml with Title

I am exporting to excel using closedxml my code is working fine, but i want to format my exported excel file with a title, backgroundcolour for the title if possible adding image.
private void button4_Click(object sender, EventArgs e)
{
string svFileName = GetSaveFileName(Convert.ToInt32(comboBox1.SelectedValue));
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
//if (!Directory.Exists(folderPath))
//{
// Directory.CreateDirectory(folderPath);
//}
if (svFileName == string.Empty)
{
DateTime mydatetime = new DateTime();
SaveFileDialog objSaveFile = new SaveFileDialog();
objSaveFile.FileName = "" + comboBox1.SelectedValue.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx";
objSaveFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
objSaveFile.FilterIndex = 2;
objSaveFile.RestoreDirectory = true;
string folderpath = string.Empty;
Cursor.Current = Cursors.WaitCursor;
if (objSaveFile.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
FileInfo fi = new FileInfo(objSaveFile.FileName);
folderpath = fi.DirectoryName;
int rowcount = 0;
int sheetcount = 1;
int temprowcount = 0;
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt,comboBox1.Text.ToString() + sheetcount.ToString());
ws.Row(1).Height=50;
//ws.FirstRow().Merge();
ws.Row(1).Merge();
//ws.Row(1).Value = comboBox1.Text.ToString();
//ws.Row(1).Cell(1).im
ws.Row(1).Cell(1).Value = comboBox1.Text.ToString();
ws.Row(1).Cell(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(1).Cell(1).Style.Alignment.Vertical=XLAlignmentVerticalValues.Center;
ws.Row(1).Cell(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Row(1).Cell(1).Style.Font.FontColor = XLColor.White;
ws.Row(1).Cell(1).Style.Font.FontSize = 21;
ws.Row(1).Cell(1).Style.Font.Bold = true;
ws.Column(1).Merge();
ws.Column(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Cell(2, 2).InsertTable(dt);
wb.SaveAs(fi.ToString());
//wb.SaveAs(folderpath + "\\" + comboBox1.SelectedItem.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx");
//rowcount = 0;
//sheetcount++;
//}
}
//}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}
else
{
Cursor.Current = Cursors.WaitCursor;
string folderpath = string.Empty;
folderpath = Properties.Settings.Default.ODRSPath + "\\" + svFileName;
using (XLWorkbook wb = new XLWorkbook())
{
//DateTime mydatetime = new DateTime();
wb.Worksheets.Add(dt, comboBox1.SelectedItem.ToString());
wb.SaveAs(folderpath);
}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}

Best way to handle awt.Image buffering in JavaFX

I have a class that takes a String parameter and performs a google search, then it gets the ten images and puts them in an array, that is then handled by another method in the same class. Using Javafx.scene.image would probably allow me to implement the buffering progress easily, but there is a bug with JavaFX Image, that misinterprets the color encoding of normal Images, and saves a weird looking image to the hard drive, so I just decided to use awt.Image.
This is the image search class:
public class GoogleCustomSearch {
static String key = //custom google id;
static String cx = // also a custom google id;
static String searchType = "image";
static java.awt.Image[] publicImageArray;
public static java.awt.Image[] Search(String searchParameter,int start) throws IOException, URISyntaxException{
String formatedText = URLEncoder.encode(searchParameter,"UTF-8");
URL url = new URL("https://www.googleapis.com/customsearch/v1?" + "key=" +key + "&cx=" +cx + "&q=" +formatedText + "&searchType=" +searchType +"&imgSize=medium" + "&start=" + start + "&num=10");
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader( ( conn.getInputStream() ) ) );
GResults results = new Gson().fromJson(br, GResults.class);
java.awt.Image [] imageArray = new java.awt.Image[10];
//JProgressBar prb = new JProgressBar();
//MediaTracker loadTracker = new MediaTracker(prb);
for(int i = 0; i<10; i++){
try {
imageArray[i] = ImageIO.read(new URL(results.getLink(i)));
}catch (java.io.IOException e){
imageArray[i] = ImageIO.read(new File("C:\\Users\\FILIP.D\\IdeaProjects\\Manual_Artwork\\src\\MAT - NoImage.jpg"));
}
}
conn.disconnect();
return imageArray;
}
public static BufferedImage getImage(String searchPar, int index, boolean newSearch) throws IOException, URISyntaxException {
int adaptedIndex;
int start;
BufferedImage bimage;
if(index<10){
adaptedIndex = index;
start = 1;
}else if (index<20){
start = 11;
adaptedIndex = index % 10;
if(index == 10){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else if(index < 30){
start = 21;
adaptedIndex = index % 10;
if (index == 20) {
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else{
adaptedIndex = index % 10;
start = 21; //ovo ce posle 30 da ga vrti u loop prvih 10
}
if(newSearch){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}else{
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}
}
public static RenderedImage getLiveImage (int index){
return (RenderedImage) publicImageArray[index % 10];
}
}
And this is the snippet of the main GUI class that just handles opening the new image in the array
private void nextImageResult() throws IOException, URISyntaxException {
if(imgNr == -1){
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,true),null));
}else{
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,false),null));
}
}
To summarise, I need a proper way to show a progress bar in the place of the image before it loads, and it needs not to hang the UI, for which I can use Task. I can optimise the loading of the array with MediaTracker, so it can prioritize loading the first few images first.

Issue in reading google text document

I could get the handle to the google text doc i needed. I am now stuck at how to read the contents.
My code looks like:
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN);
oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);
DocsService client = new DocsService("sakshum-YourAppName-v1");
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentQuery dquery = new DocumentQuery(feedUrl);
dquery.setTitleQuery("blood_donor_verification_template_dev");
dquery.setTitleExact(true);
dquery.setMaxResults(10);
DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
System.out.println("feed size:" + resultFeed.getEntries().size());
String emailBody = "";
for (DocumentListEntry entry : resultFeed.getEntries()) {
System.out.println(entry.getPlainTextContent());
emailBody = entry.getPlainTextContent();
}
Plz note that entry.getPlainTextContent() does not work and throws object not TextContent type exception
finally i solved it as:
for (DocumentListEntry entry : resultFeed.getEntries()) {
String docId = entry.getDocId();
String docType = entry.getType();
URL exportUrl =
new URL("https://docs.google.com/feeds/download/" + docType
+ "s/Export?docID=" + docId + "&exportFormat=html");
MediaContent mc = new MediaContent();
mc.setUri(exportUrl.toString());
MediaSource ms = client.getMedia(mc);
InputStream inStream = null;
try {
inStream = ms.getInputStream();
int c;
while ((c = inStream.read()) != -1) {
emailBody.append((char)c);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
}

Resources