when i start .jar app on mac do nothing - macos

I have made a simple JavaFx application, wich read/write the txt file (the code is below). I have tested it on windows platform (7 and higher).
After i gave app my friend for test on Mac. But when we run it, just do nothing. The GUI did not appear.
I tried run it through terminal (just "drug and drop" the icon to terminal, then enter in teminal. I don't know did i do right?) and terminal returned message "Permission denied". Can somebody explain what is require to run application, and what is not permitted exactly?
I found the similar question there but it have not answer...
Code:
import javafx.application.*;
import javafx.concurrent.Task;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.text.Font;
import javafx.stage.*;
import javafx.scene.layout.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class Main extends Application {
static Properties props;
static double fontSize;
static String charsetName;
static long mills;
static String delimiter;
static String pathToDictionary;
static String pathErrLog;
static {
String pathFileProps = System.getProperty("user.dir") + "\\props.txt";
props = new Properties();
try {
FileInputStream fis = new FileInputStream(pathFileProps);
props.load(fis);
fontSize = Double.parseDouble(props.getProperty("Font"));
charsetName = props.getProperty("Charset");
mills = Long.parseLong(props.getProperty("mills"));
delimiter = props.getProperty("delimiter");
pathToDictionary = props.getProperty("dict.path");
fis.close();
} catch (IOException e) {
try {
props.put("Font", "20");
props.put("Charset", "UTF-8");
props.put("mills", "1000");
props.put("delimiter", "\t");
props.put("dict.path", System.getProperty("user.dir") + "\\dict.txt");
System.out.println("dictPath:" + System.getProperty("user.dir") + "\\dict.txt");
System.setProperty("file.encoding", "UTF-8");
FileOutputStream fos = new FileOutputStream(pathFileProps);
props.store(fos
, "Props description:" + "\n" +
"Font" + "\t\t" + "size of font's words " + "\n" +
"Charset" + "\t" + "charset of file-dictionary" + "\n" +
"mills" + "\t\t" + "per animations in milliseconds" + "\n" +
"delimiter" + "\t" + "delimiter between a pair words in string: eng<->rus \"<->\" is delimiter there." + "\n" +
"dict.path" + "\t" + "path to file-dictionary. Use \"/\"-symbol in path. Ex: C:/temp/dict.txt" + "\n" +
"\t\t\t" + "Use only eng symbols to set path!" + "\n" +
"\tYou can change only values!\n");
fos.close();
System.exit(0);
} catch (IOException e1) {
errPrint(e1,"Ошибка создания файла: " + pathFileProps + "\n");
}
}
}
ArrayList<String> dictionary = new ArrayList<>();
public static void errPrint(Exception exc, String note) {
if (pathErrLog == null) {
pathErrLog = System.getProperty("user.dir") + "\\errors.log";
}
try {
PrintWriter outFile = new PrintWriter(new FileWriter(pathErrLog, true));
outFile.println(note);
exc.printStackTrace(outFile);
outFile.close();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
launch(args);
}
public void init() throws IOException {
try {
BufferedReader reader = new BufferedReader(new FileReader(pathToDictionary));
int cnt = 0;
while (reader.ready()) {
String line = new String(reader.readLine().getBytes(), Charset.forName(charsetName));
dictionary.add(line);
}
} catch (FileNotFoundException e) {
errPrint(e,"Не найден файл " + pathToDictionary);
} catch (IOException e) {
errPrint(e,"Ошибка чтения файла " + pathToDictionary);
}
}
public void start(Stage myStage) {
myStage.setTitle("WordsLearner");
SplitPane sp = new SplitPane();
sp.setOrientation(Orientation.VERTICAL);
Label labelUp = new Label();
Label labelDw = new Label();
labelUp.setFont(new Font(fontSize));
labelDw.setFont(new Font(fontSize));
Scene scene = new Scene(sp, 600, 200);
myStage.setScene(scene);
final StackPane sp1 = new StackPane();
sp1.getChildren().add(labelUp);
sp1.setAlignment(Pos.BOTTOM_CENTER);
final StackPane sp2 = new StackPane();
sp2.getChildren().add(labelDw);
sp2.setAlignment(Pos.TOP_CENTER);
final boolean[] flag = {true};
sp.setOnMouseClicked(event -> {
Task<Void> task = new Task<Void>() {
#Override
public Void call() throws Exception {
if (flag[0]) {
flag[0] = false;
final String[] str = new String[1];
final String[] eng = new String[1];
final String[] rus = new String[1];
while (true) {
Platform.runLater(() -> {
try {
str[0] = dictionary.get(ThreadLocalRandom.current().nextInt(0, dictionary.size()));
eng[0] = str[0].split(delimiter)[0];
rus[0] = str[0].split(delimiter)[1];
labelUp.setText(eng[0]);
labelDw.setText(rus[0]);
} catch (Exception e) {
System.exit(-1);
}
});
Thread.sleep(mills);
}
}
return null;
}
};
new Thread(task).start();
});
sp.getItems().addAll(sp1, sp2);
sp.setDividerPositions(0.5f, 0.5f);
myStage.show();
}
public void stop() {
System.exit(0);
}
}

Related

Error: cannot find symbol for BufferReader

I have the following code:
import.java.io.*;
public class BasheminParkingLot
{
public static void main(String[]args)throws Exception
{
Stack parkinglot = new Stack();
Stack alley= new Stack();
File f = new File("bashemin.in");
FileInputStream finstream = new FileInputStream(f);
InputStreamReader finreader = new InputStreamReader(finstream);
BufferReader finput = new BufferReader(finreader);
String line = finput.readLine();
String plate = "";
System.out.println();
System.out.println("The Bashemin Status");
System.out.println();
while(line!=null)
{
if(line.charAt(0)=='a')
{
plate = line.substring(1);
System.out.println ("car" + plate + " arrived and parked");
parkinglot.Push(plate);
}
}
}
}
and am getting the error:
BasheminParkingLot.java:13: error: cannot find symbol
BufferReader finput = new BufferReader(finreader);
^
I was wondering if anyone could help me debug this?? Thanks!
This shouldn't be BufferReader. It should be BufferedReader.
The following code will work:
import java.io.*;
class Stack {
int x;
void Push(String value) {
// DO SOMETHING
}
}
public class BasheminParkingLot
{
public static void main(String[]args)throws IOException
{
Stack parkinglot = new Stack();
Stack alley= new Stack();
File f = new File("bashemin.in");
FileInputStream finstream = new FileInputStream(f);
InputStreamReader finreader = new InputStreamReader(finstream);
BufferedReader finput = new BufferedReader(finreader);
String line = finput.readLine();
String plate = "";
System.out.println();
System.out.println("The Bashemin Status");
System.out.println();
while(line!=null)
{
if(line.charAt(0)=='a')
{
plate = line.substring(1);
System.out.println ("car" + plate + " arrived and parked");
parkinglot.Push(plate);
}
}
}
}

Check for broken links using java code and link is not getting redirect

This code will check my link is broken or not and validateWebResourceUrl method will return 0 status .even if i get 200 status my link couldn't redirect to mozilla firefox when i call my api call.Below code will show u my api cal.
#RequestMapping(method = RequestMethod.POST, value = "/validate/fburl")
public ModelAndView validateFbLink(HttpServletRequest request,#RequestParam(value="key", required=true) String key ,#RequestParam(value = "link") String link, HttpServletResponse response) throws Exception {
ModelAndView jsonmodel = new ModelAndView("rest/model");
jsonmodel.addObject("model", httpFrameBreakChecker.validateHttpLink(link, key));
return jsonmodel;
}
This api call will go to check the link is broken or not ,if not it will go to redirect.I am trying to find the broken links and i am getting status 200 for that link but that link is not redirecting.Below is my code.
package org.ednovo.gooru.util;
import org.springframework.stereotype.Component;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebResponse;
#Component
public class HttpFrameBreakChecker extends LinkChecker {
#Override
public Integer validateHttpLink(String resourceUrl, String key) {
Integer status = null;
status = validateWebResourceUrl(resourceUrl, getPageTesterPath());
putResourceStatus(status, key);
return status;
}
public synchronized Integer validateWebResourceUrl(String webURL, String pageTesterURL) {
WebClient webClient = null;
WebResponse webResponse = null;
try {
webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setCssEnabled(false);
webClient.setThrowExceptionOnScriptError(false);
webResponse = webClient.getPage(webURL).getWebResponse();
int i = webResponse.getStatusCode();
logger.info(i+"");
if (webResponse.getStatusCode() != 200) {
return null;
}
String urlToCheck = webURL + pageTesterURL;
// Now check if the page has a frame breaker.
webResponse = webClient.getPage(urlToCheck).getWebResponse();
int status = webResponse.getStatusCode();
logger.info(status+""+"frame");
String pageURL = webResponse.getWebRequest().getUrl().toString();
int validationStatus = (urlToCheck.equals(pageURL) && status == 200) ? 0 : 1;
logger.info(validationStatus+ " return statement of validateWebResourceUrl ");
return validationStatus;
} catch (Exception exception) {
logger.error("ERROR : Unable to start web driver : " + exception.getMessage());
return null;
} finally {
try {
if (webClient != null) {
webClient.closeAllWindows();
}
} catch (Exception ex) {
}
}
}
#Override
public void commitPage() {
if (resources.size() > 0) {
String resourcesString = getxStream().toXML(resources);
postData(getApiPath(), "/resource/urls/update/frameBreaker/" + getGlobalJobKey(), resourcesString);
postData(getSearchApiPath(), "/search/resource/update/index/" + getGlobalJobKey(), resourcesString );
}
}
#Override
public String getType() {
return "FB";
}
}
And Below code will show you the LinkChecker class.
package org.ednovo.gooru.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public abstract class LinkChecker extends BaseComponent {
private int pageSize = 100;
private Map<String, String> configSettings;
private XStream xStream = new XStream(new DomDriver());
protected Map<Integer, List<String>> resources = new HashMap<Integer, List<String>>();
private String listResponse = null;
private Map<Long, String> resourceUrls = null;
public final synchronized void execute() {
reset();
ClientResource configResource = null;
Representation representation = null;
try {
configResource = createClientResource(getApiPath() + "/config-settings");
representation = configResource.get();
String settingsText = representation.getText();
configSettings = (Map<String, String>) xStream.fromXML(settingsText);
if (isLinkCheckerSchedulerEnabled()) {
run();
}
} catch (Exception exception) {
logger.error(exception.getMessage());
} finally {
releaseClientResources(configResource, representation);
}
}
public void run() throws Exception {
reset();
int page = 0;
while (true) {
++page;
listResponse = null;
resourceUrls = null;
final int currentPage = page;
ClientResourceExecuter clientResourceExecuter = new ClientResourceExecuter() {
#Override
public void run(ClientResource clientResource, Representation representation) throws Exception {
reset();
clientResource = createClientResource(getSearchApiPath() +"/search/resource-url-check?category="+getType()+"&pageSize="+pageSize+"&format=xml");
representation = clientResource.get();
listResponse = representation.getText();
if (listResponse != null || listResponse.length() > 1) {
try {
resourceUrls = (Map<Long, String>) xStream.fromXML(listResponse);
} catch (Exception ex) {
logger.error("Conversion of json to list failed in " + getType() + " validation");
}
logger.warn("Validating " + getType() + " Urls of Page : " + currentPage + " with size : " + (resourceUrls != null ? resourceUrls.size() : 0));
validateResourceUrls(resourceUrls);
}
}
};
clientResourceExecuter = null;
listResponse = null;
if (resourceUrls == null || resourceUrls.size() == 0) {
break;
}
if (getType().equals("HTTP") && page >= 5) {
break;
}else if (getType().equals("FB") && page >= 1) {
break;
}
}
}
public Integer validateHttpLink(String link, String key) {
URL url = null;
URLConnection connection = null;
HttpURLConnection httpConnection = null;
Integer responseCode = null;
try {
url = new URL(link);
connection = url.openConnection();
connection.connect();
httpConnection = (HttpURLConnection) connection;
httpConnection.setConnectTimeout(60000);
responseCode = httpConnection.getResponseCode();
if (responseCode != 200) {
logger.error("Url Checker validation fails for resource : " + link + " : " + responseCode);
}
} catch (MalformedURLException e) {
logger.error("Error in link checker : " + link + " Message : " + e.getMessage());
return 404;
} catch (IOException e) {
logger.error("Error in link checker : " + link + " Message : " + e.getMessage());
return 404;
} catch (Exception ex) {
logger.error("Error in link checker : " + link + " Message : " + ex.getMessage());
return null;
} finally {
try {
if (httpConnection != null) {
httpConnection.disconnect();
}
} catch (Exception ex) {
}
}
return responseCode;
}
protected void postData(String path, String url, String data) {
Form form = new Form();
form.add("data", data);
createAndRunClientResource(path, url, form);
}
public void validateResourceUrls(Map<Long, String> resourceUrls) throws Exception {
if (resourceUrls.size() > 0) {
Iterator<?> iterator = resourceUrls.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry<Long, String>) iterator.next();
String resourceUrl = entry.getValue();
if (getType().equals("FB")) {
Thread.sleep(1000);
} else {
Thread.sleep(900);
}
logger.debug("Validating " + getType() + " url - " + resourceUrl);
Integer status = validateHttpLink(resourceUrl, entry.getKey()+"");
putResourceStatus(status, entry.getKey()+"");
}
commitPage();
}
}
public void commitPage() throws Exception {
if (resources.size() > 0) {
String resourcesString = getxStream().toXML(resources);
postData(getApiPath(), "/resource/urls/checker/update/" + getGlobalJobKey(), resourcesString);
//postData(getSearchApiPath(), "/search/resource/update/index/" + getGlobalJobKey(), resourcesString);
}
}
public void putResourceStatus(Integer status, String resourceId) {
if (status == null) {
status = -99;
}
List<String> resourceIds = null;
if (resources.containsKey(status)) {
resourceIds = resources.get(status);
} else {
resourceIds = new ArrayList<String>();
resources.put(status, resourceIds);
}
resourceIds.add(resourceId);
}
public void reset() {
resources.clear();
}
public boolean isLinkCheckerSchedulerEnabled() {
if (configSettings != null && configSettings.containsKey("urlChecker.scheduler.enabled")) {
return configSettings.get("urlChecker.scheduler.enabled").equals("true") ? true : false;
} else {
return false;
}
}
public abstract String getType();
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public XStream getxStream() {
return xStream;
}
public static void main(String args[]) {
}
}

JDBC database java using vector of vectors

Does someone can help my by creating an database query with vectors?
I want to query the Lieferranten Table of the nordwind database and showing it on a JTable.
My problem is how to show data sets in the jTable1?
This is my previous code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
public class Anzeige extends JFrame {
private JTable jTable1 = new JTable(5, 5);
private DefaultTableModel jTable1Model = (DefaultTableModel) jTable1.getModel();
private JScrollPane jTable1ScrollPane = new JScrollPane(jTable1);
public Anzeige (String title) {
super (title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 676;
int frameHeight = 467;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
Container cp = getContentPane();
cp.setLayout(null);
// Anfang Komponenten
jTable1ScrollPane.setBounds(72, 56, 521, 289);
jTable1.getColumnModel().getColumn(0).setHeaderValue("Title 1");
jTable1.getColumnModel().getColumn(1).setHeaderValue("Title 2");
jTable1.getColumnModel().getColumn(2).setHeaderValue("Title 3");
jTable1.getColumnModel().getColumn(3).setHeaderValue("Title 4");
jTable1.getColumnModel().getColumn(4).setHeaderValue("Title 5");
cp.add(jTable1ScrollPane);
// Ende Komponenten
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new Anzeige("Anzeige");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nordwind", "root", "");
Statement statement = dbConn.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM Lieferranten");
Vector vector = new Vector();
while (results.next()) {
String s1 = results.getString(2);
String s2 = results.getString(5);
System.out.println(s1 + "\n" + s2);
System.out.println(results.getString(2) + " " + results.getString(5));
Vector data = new Vector();
data.add(results.getString(1));
data.add(results.getString(2));
vector.add(data);
}
//results.close();
statement.close();
dbConn.close();
}
catch (InstantiationException e) {
System.err.println("Error in Instantiation!");
}
catch (ClassNotFoundException e) {
System.err.println("Class not found!");
}
catch (IllegalAccessException e) {
System.err.println("Access denied!");
}
catch (SQLException e) {
System.err.println("SQL Error!");
}
}
}
I assume that you will get five column values as you had added five column titles. After that use addRow(java.util.Vector) method of DefaultTableModel to insert row in jTable1.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
public class Anzeige extends JFrame {
private JTable jTable1 = new JTable(5, 5);
private DefaultTableModel jTable1Model = (DefaultTableModel) jTable1.getModel();
private JScrollPane jTable1ScrollPane = new JScrollPane(jTable1);
public Anzeige (String title) {
super (title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 676;
int frameHeight = 467;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
Container cp = getContentPane();
cp.setLayout(null);
// Anfang Komponenten
jTable1ScrollPane.setBounds(72, 56, 521, 289);
jTable1.getColumnModel().getColumn(0).setHeaderValue("Title 1");
jTable1.getColumnModel().getColumn(1).setHeaderValue("Title 2");
jTable1.getColumnModel().getColumn(2).setHeaderValue("Title 3");
jTable1.getColumnModel().getColumn(3).setHeaderValue("Title 4");
jTable1.getColumnModel().getColumn(4).setHeaderValue("Title 5");
cp.add(jTable1ScrollPane);
// Ende Komponenten
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new Anzeige("Anzeige");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nordwind", "root", "");
Statement statement = dbConn.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM Lieferranten");
while (results.next()) {
String s1 = results.getString(2);
String s2 = results.getString(5);
System.out.println(s1 + "\n" + s2);
System.out.println(results.getString(2) + " " + results.getString(5));
Vector data = new Vector();
data.add(results.getString(1));
data.add(results.getString(2));
data.add(results.getString(3));
data.add(results.getString(4));
data.add(results.getString(5));
jTable1Model.addRow(data);
}
//results.close();
statement.close();
dbConn.close();
}
catch (InstantiationException e) {
System.err.println("Error in Instantiation!");
}
catch (ClassNotFoundException e) {
System.err.println("Class not found!");
}
catch (IllegalAccessException e) {
System.err.println("Access denied!");
}
catch (SQLException e) {
System.err.println("SQL Error!");
}
}
}

How to use accesslog_parser.pl Kannel access log parser?

I have found kannel access log parser accesslog_parser.pl in utils folder.
How to use this file for parse.
Also i want convert kannel_access.log in csv format. Please help me.
Assuming Kannel log is at /var/log/kannel/access.log
This should do
cat /var/log/kannel/access.log |accesslog_parser.pl
May be an old question but I'd like to share this small tool a wrote in java for parsing kannel log files and outputing the results in csv format:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.StringTokenizer;
/**
*
* #author bashizip
*/
public class KannelLogsParser {
static String fileName;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// fileName = args[0];
fileName = "access_kannel.txt";
String allLines = readLines(fileName);
parseAndWriteToCsv(allLines);
}
static String readLines(String fileName) {
BufferedReader br = null;
String sCurrentLine = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(
new FileReader(fileName));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return sb.toString();
}
private static void parseAndWriteToCsv(String allLines) throws IOException {
String[] lines = allLines.split("\n");
System.out.println("lines to parse : " + lines.length);
StringTokenizer st;
StringBuilder output = new StringBuilder();
output.append("DATE;Heure;sent;SMS; SMSC; SVC; ACT; BINF; FID; from; to; flags; msg;;udh"+"\n");
int count = 0;
for (String line : lines) {
count++;
System.out.println("Parsing ..." + 100 * count / lines.length + "%");
st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
String currentToken = st.nextToken();
boolean messageToken = false;
boolean afterMessageToken = false;
if (currentToken.startsWith("[")) {
System.out.println(currentToken);
messageToken = currentToken.startsWith("[msg");
try {
currentToken = currentToken.substring(currentToken.indexOf(":") + 1, currentToken.indexOf("]"));
} catch (Exception e) {
System.err.println(e.getMessage());
messageToken = true;
currentToken = currentToken.substring(currentToken.indexOf(":") + 1);
}
}
currentToken = currentToken.replace("[", "");
currentToken = currentToken.replace("]", "");
output.append(currentToken);
if (!messageToken) {
output.append(";");
} else if (afterMessageToken) {
afterMessageToken = false;
output.append(" ");
} else {
output.append(" ");
afterMessageToken = true;
}
}
output.append("\n");
}
Files.write(Paths.get(fileName + ".csv"), output.toString().getBytes());
System.out.println("Output CVS file: " + fileName + ".csv");
System.out.println("Finished !");
}
}
Hope it can help someone one day :-)

Vaadin: Downloaded file has whole path as file name

I have a download action implemented on my Vaadin application but for some reason the downloaded file has the original file's full path as the file name.
Any idea?
You can see the code on this post.
Edit:
Here's the important part of the code:
package com.bluecubs.xinco.core.server.vaadin;
import com.bluecubs.xinco.core.server.XincoConfigSingletonServer;
import com.vaadin.Application;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.FileResource;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
/**
*
* #author Javier A. Ortiz Bultrón<javier.ortiz.78#gmail.com>
*/
public class FileDownloadResource extends FileResource {
private final String fileName;
private File download;
private File newFile;
public FileDownloadResource(File sourceFile, String fileName,
Application application) {
super(sourceFile, application);
this.fileName = fileName;
}
protected void cleanup() {
if (newFile != null && newFile.exists()) {
newFile.delete();
}
if (download != null && download.exists() && download.listFiles().length == 0) {
download.delete();
}
}
#Override
public DownloadStream getStream() {
try {
//Copy file to directory for downloading
InputStream in = new CheckedInputStream(new FileInputStream(getSourceFile()),
new CRC32());
download = new File(XincoConfigSingletonServer.getInstance().FileRepositoryPath
+ System.getProperty("file.separator") + UUID.randomUUID().toString());
newFile = new File(download.getAbsolutePath() + System.getProperty("file.separator") + fileName);
download.mkdirs();
OutputStream out = new FileOutputStream(newFile);
newFile.deleteOnExit();
download.deleteOnExit();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
final DownloadStream ds = new DownloadStream(
new FileInputStream(newFile), getMIMEType(), fileName);
ds.setParameter("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, "utf-8"));
ds.setCacheTime(getCacheTime());
return ds;
} catch (final FileNotFoundException ex) {
Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (IOException ex) {
Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
I already debugged and verified that fileName only contains the file's name not the whole path.
The answer was actually a mix of houman001's answer and this post: https://vaadin.com/forum/-/message_boards/view_message/200534
I went away from the above approach to a simpler working one:
StreamSource ss = new StreamSource() {
byte[] bytes = //Get the file bytes here
InputStream is = new ByteArrayInputStream(bytes);
#Override
public InputStream getStream() {
return is;
}
};
StreamResource sr = new StreamResource(ss, <file name>, <Application Instance>);
getMainWindow().open(sr, "_blank");
Here is my code that works fine (downloading a blob from database as a file), but it's using a Servlet and OutputStream rather than DownloadStream in your case:
public class TextFileServlet extends HttpServlet
{
public static final String PARAM_BLOB_ID = "id";
private final Logger logger = LoggerFactory.getLogger(TextFileServlet.class);
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
Principal userPrincipal = req.getUserPrincipal();
PersistenceManager pm = PMFHolder.get().getPersistenceManager();
Long id = Long.parseLong(req.getParameter(PARAM_BLOB_ID));
MyFile myfile = pm.getObjectById(MyFile.class, id);
if (!userPrincipal.getName().equals(myfile.getUserName()))
{
logger.info("TextFileServlet.doGet - current user: " + userPrincipal + " file owner: " + myfile.getUserName());
return;
}
res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition", "attachment;filename=\"" + myfile.getName() + "\"");
res.getOutputStream().write(myfile.getFile().getBytes());
}
}
I hope it helps you.
StreamResource myResource = createResource(attachmentName);
System.out.println(myResource.getFilename());
if(attachmentName.contains("/"))
attachmentName = attachmentName.substring(attachmentName.lastIndexOf("/"));
if(attachmentName.contains("\\"))
attachmentName = attachmentName.substring(attachmentName.lastIndexOf("\\"));
myResource.setFilename(attachmentName);
FileDownloader fileDownloader = new FileDownloader(myResource);
fileDownloader.extend(downloadButton);

Resources