Downloading empty java file Vaadin - java

Currently I'm developing an application with help of Vaadin framework 8.0.
I need to download generated file from server. So I'm using FileDownloader and it's quite simple:
private void createButton() {
Button downloadButton = new Button("download me)
new FileDownloader(getStreamResource().extend(downloadButton))
}
private StreamResource getStreamResource() {
StreamResource streamResource = new StreamResource(new StreamResource.StreamSource() {
#Override
public InputStream getStream() {
return new ByteArrayInputStream(generatedCode.getBytes);
}
}, "Generated.txt");
}
And all is ok when I'm using filename - "Generated.txt". But I need to save this file as a Java class. And when I'm using filename - "Generated.java" I'm just getting an empty file.
What I am doing wrong and how can I fix it? Thanks in advance.

Related

how to download file from folder inside kubernetes container using browser ? we are using java and K8

We have web application with client in agnular.js and server in java. we have deployed this application docker container. Now our applicaton logs are created at location /var/tmp/logs.tar.
Our use case is to give end user facility of downloading this log file i.e. logs.tar currently we are giving this download facility on client on click of button but using Blob octet-stream. our issue is in case this log size becomes huge in some GB then while streaming it will create load on application memory. so we want to give functionality where instead of streaming an external link will be there from which file will get directly downloaded on click of button. we want to do this using the code as an application functionality.
Server side function -
public File downloadLogs() {
File file = null;
try {
executor.execute("/bin/sh", "-c", mcmProp.getKeyValue("download.log.script.location"));
String filePath = "/var/tmp/logs.tar";
file = new File(filePath);
logger.debug("File exist for download");
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Client side code -
this._service.downloadLogs().subscribe(
success => {
var blb = new Blob([success], { 'type': "application/octet-stream" });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blb, 'logs.tar');
}
else {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blb);
link.download = "logs.tar";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});

How to open a generated PDF in vaadin?

In my vaadin application I have a Table with an additional column containing a print Button. The Button calls the following util method to create a pdf and open it in a new window (ui parameter is the button):
public static void printPDF(Offer offer, AbstractComponent ui) throws IOException, DocumentException, TemplateException {
// ... create PDF
FileResource resource = new FileResource(pdfFile);
BrowserWindowOpener opener = new BrowserWindowOpener(resource);
opener.setFeatures("");
opener.extend(ui);
}
Now clicking the button the first time does not work. Clicking it the second time works. Clicking it the third time, opens two windows. This increases on every further click.
I also want to open the pdf using the context menu e.g.
table.addActionHandler(new Handler()...
There I don't even have a button to extend. I would prefer to, not use the .extend() part and just open a new window. How can I do that?
EDIT: This blocks the button from opening mulitple instances, still not a nice solution and the first click does not work.
Collection<Extension> extensions = ui.getExtensions();
for (Extension e : extensions) {
if (e instanceof BrowserWindowOpener) {
((BrowserWindowOpener) e).setResource(resource);
return;
}
}
I guess I would need to create a BrowserWindowOpener for every print Button in my Table.
Not a very clean solution, the table may contain lots of rows which would create a lot of BrowserWindowOpener instances which will never be used. The context menu problem would not be solved as well.
EDIT2: This is the other solution I tried:
ResourceReference rr = ResourceReference.create(resource, ui, "print");
Page.getCurrent().open(rr.getURL(), "blank_");
Here I get the following error:
Button (175) did not handle connector request for
print/2016_9090_R_1634500091131558445.pdf
You can use the FileDownloader to achieve what you want.
FileResource resource = new FileResource(pdfFile);
FileDownloader downloader = new FileDownloader(resource);
Button pdf= new Button("Download PDF");
downloader.extend(pdf);
Use this code
Window window = new Window();
((VerticalLayout) window.getContent()).setSizeFull();
window.setResizable(true);
window.setCaption("Exemplo PDF");
window.setWidth("800");
window.setHeight("600");
window.center();
StreamSource s = new StreamResource.StreamSource() {
#Override
public InputStream getStream() {
try {
File f = new File("C:/themes/repy.pdf");
FileInputStream fis = new FileInputStream(f);
return fis;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
StreamResource r = new StreamResource(s, "repy.pdf", mainLayout.getApplication());
Embedded e = new Embedded();
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
r.setMIMEType("application/pdf");
e.setSource(r);
window.addComponent(e);
getMainWindow().addWindow(window);

File upload and download in vaadin

Am very very new to Vaadin. Am setting up the project by looking into Github and other docs, where am using Spring-security, Vaadin, Maven.
I created sample vaadin-maven with spring security project. Now am getting login page then after suucessful login, am getting some MainView.java.
Am trying to change the upload .xls file and read that file and do some functionality and then download pop-up.
I have followed http://demo.vaadin.com/sampler/#ui/data-input/other/upload , but errors. unable to reproduce my output.
For now, am able to read the file using path " final String FILE_PATH = "F://input.xls";" But, i need option to upload the file and then use that file for further functionality.
After the functionality completed, i need to download the file.
Please suggest me how can i browse the file and upload and use the uploaded file for ding some read and write operation and then download Vaadin.
Am having sleepless nights for this. Please suggest me how can i come out of this.
Here is my code:
#Component
#Scope("prototype")
#VaadinView(RoleAdminView.NAME)
#Secured("ROLE_ADMIN")
public class RoleAdminView extends Panel implements View
{
public static final String NAME = "role_admin";
#PostConstruct
public void PostConstruct()
{
LoggerFactory.getLogger(this.getClass()).debug("POST");
setSizeFull();
VerticalLayout layout = new VerticalLayout();
layout.setSpacing(true);
layout.setMargin(true);
layout.addComponent(new Button());
layout.addComponent(new Label("ROLE_ADMIN"));
layout.addComponent(new Link("Go back", new ExternalResource("#!" +
MainView.NAME)));
setContent(layout);
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event)
{
}
}
A big thank you in advance. Hope you guys sort out my issue :)
You can do,
public class RoleAdminView extends Panel implements View{
//add a button view
//
#Override
public void uploadFailed(Upload.FailedEvent event) {
Notification.show(event.getFilename() + "----" + event.getMIMEType());
//here it will show the error if upload failed
}
#Override
public void uploadSucceeded(SucceededEvent event) {
/// do your functionlity
}
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
FileOutputStream fos = null;
// do your functionality to save in any path or server path
return fos; // Return the output stream to write to
}
}
I hope this my help you :)

Opening file geodatabase using ESRI android API

for some time I am trying to open file godatabase on android using ESRI api in version 10.2.
I have a file godatabase made with Arccatalog 10.1. It contains one layer. I can open it in Arcmap so everything looks fine here.
The geodatabase is in folder named android.gdb
I copied it to microSD card and tried to open it using this code:
new com.esri.core.gdb.Geodatabase("/mnt/sdcard2/android.gdb");
The "/mnt/sdcard2/android.gdb" file exists and is a folder and I have read and write permissions.
I get a RuntimeException with the message that the goedatabase file could not be opened.
Anyone had similiar issues with that ?
The ESRI runtime api for android wont be able to open that kind of database. It uses a proprietary version of a geodatabase built in SQLLite. You will need to publish a service in ArcGisOnline or ArcServer 10.2 and call the GeodatabaseSyncTask object in order to get a version of your database in the right format onto the device. On your published feature service you will need to make sure Sync is enabled. Then you can utilize this code to call your feature service and store it locally. This code is based on this ESRI sample -- https://developers.arcgis.com/android/sample-code/offline-editor/
public void LoadGdb(UserCredentials credentials, Polygon extent, SpatialReference spatRef){
mapExtent = extent;
mapSpatialRef = spatRef;
String replicaUrl = callingActivity.getResources().getString(R.string.feature_service_url);
gdbTask = new GeodatabaseSyncTask(replicaUrl, credentials);
gdbTask.fetchFeatureServiceInfo(new CallbackListener<FeatureServiceInfo>() {
#Override
public void onError(Throwable e) {
Log.e(TAG, "", e);
}
#Override
public void onCallback(FeatureServiceInfo objs) {
if (objs.isSyncEnabled()) {
requestGdbInOneMethod(gdbTask, mapExtent, mapSpatialRef);
}
}
});
}
protected void requestGdbInOneMethod(GeodatabaseSyncTask geodatabaseSyncTask, Polygon extent, SpatialReference spatRef) {
GenerateGeodatabaseParameters params = new GenerateGeodatabaseParameters({0, 1}, extent,
spatRef, true, SyncModel.LAYER, spatRef);
CallbackListener<String> gdbResponseCallback = new CallbackListener<String>() {
#Override
public void onCallback(String obj) {
try {
// This onCallback gets called after the generateGeodatabase
// function on the GeodatabaseSyncTask is called.
// You can store a reference to this database or you can load it
// with your code and point it to the gdbFileName location
Geodatabase myGeodatabase = (Geodatabase)obj;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void onError(Throwable e) {
Log.e(TAG, "", e);
}
};
GeodatabaseStatusCallback statusCallback = new GeodatabaseStatusCallback() {
#Override
public void statusUpdated(GeodatabaseStatusInfo status) {
showMessage(callingActivity, status.getStatus().toString());
}
};
// !! THE gdbFileName is a string of the path and filename
// where the geodatabse will be stored.
geodatabaseSyncTask.generateGeodatabase(params, gdbFileName, false, statusCallback, gdbResponseCallback);
}
To load a local file you need to use ArcGIS Desktop 10.2.1 or higher to generate a Runtime Geodatabase file with a *.geodatabase file extension. See the instructions here: http://resources.arcgis.com/en/help/main/10.2/index.html#//00660000045q000000

JSF/primefaces display image out of code - Image Location?

I'm using JSF with primefaces and want to display an image from java code.
I already saw the tutorial on http://www.primefaces.org/showcase/ui/dynamicImage.jsf
But I'm not clear on how I can get the path to my image file correctly:
Code:
Bean:
#ManagedBean
public class ABean {
private StreamedContent bStatus;
public ABean() {
try {
Boolean connected = false;
if (connected == true) {
bStatus = new DefaultStreamedContent(new FileInputStream(new File("/images/greendot.png")), "image/jpeg");
} else {
bStatus = new DefaultStreamedContent(new FileInputStream(new File("/images/reddot.png")), "image/jpeg");
}
} catch(Exception e) {
e.printStackTrace();
}
}
public StreamedContent getBStatus() {
return bStatus;
}
public void setBStatus(StreamedContent bStatus) {
this.bStatus = bStatus;
}
}
xhtml:
<p:graphicImage value="#{ABean.bStatus}" />
returns:
java.io.FileNotFoundException: \images\reddot.png
I would appreciate best practices on where to store my image when displaying it form code and how to do it.
Since your images are in your web folder, you don't really need to use DefaultStreamedContent. I'd leave that only for images generated on the fly.
For your case, I'd just create a simple method that returns the image path (in your web folder) based on the boolean variable. Something like this:
public String getImagePath(){
return connected ? "/images/greendot.png" : "/images/reddot.png";
}
And on the graphicImage, you can just reference that:
<p:graphicImage value="#{yourBean.imagePath}"/>
Note that you might have to adjust the graphicImage tag if your web context is not root.
EDIT
You can actually make this even simpler:
<p:graphicImage value="#{yourBean.connected ? '/images/greendot.png' : '/images/reddot.png'}"/>
Just make sure to have a getter for the connected property.
Create your StreamedContent as follows:
bStatus = new DefaultStreamedContent(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/images/greendot.png"), "image/jpeg");
When you are creating new File() this will be absolute path in your disk, not just in your application.

Categories

Resources