Example usage for com.vaadin.server FileResource FileResource

List of usage examples for com.vaadin.server FileResource FileResource

Introduction

In this page you can find the example usage for com.vaadin.server FileResource FileResource.

Prototype

public FileResource(File sourceFile) 

Source Link

Document

Creates a new file resource for providing given file for client terminals.

Usage

From source file:io.subutai.plugin.accumulo.ui.wizard.WelcomeStep.java

public WelcomeStep(final Wizard wizard) {

    setSizeFull();/*from  w  w w  . j a v a2 s  .c  o  m*/

    GridLayout grid = new GridLayout(10, 6);
    grid.setSpacing(true);
    grid.setMargin(true);
    grid.setSizeFull();

    Label welcomeMsg = new Label("<center><h2>Welcome to Accumulo Installation Wizard!</h2>");
    welcomeMsg.setContentMode(ContentMode.HTML);
    grid.addComponent(welcomeMsg, 3, 1, 6, 2);

    Label logoImg = new Label();
    // Image as a file resource
    logoImg.setIcon(new FileResource(FileUtil.getFile(AccumuloPortalModule.MODULE_IMAGE, this)));
    logoImg.setContentMode(ContentMode.HTML);
    logoImg.setHeight(56, Unit.PIXELS);
    logoImg.setWidth(220, Unit.PIXELS);
    grid.addComponent(logoImg, 1, 3, 2, 5);

    Button startOverHadoopNZK = new Button("Start over Hadoop & ZK installation");
    startOverHadoopNZK.setId("startOverHadoopNZK");
    startOverHadoopNZK.addStyleName("default");
    grid.addComponent(startOverHadoopNZK, 4, 4, 4, 4);
    grid.setComponentAlignment(startOverHadoopNZK, Alignment.BOTTOM_RIGHT);

    startOverHadoopNZK.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            wizard.init();
            wizard.getConfig().setSetupType(SetupType.OVER_HADOOP_N_ZK);
            wizard.next();
        }
    });

    setContent(grid);
}

From source file:life.qbic.components.OfferManagerTab.java

License:Open Source License

/**
 * adds the functionality of exporting the offer grid to the exportGridButton
 * @param container: SQLContainer holding the data
 * @param exportGridButton: button the export functionality should be added to
 * @throws IOException://from w  ww  . j a v  a2s  .  c  o m
 */
private static void setupTableExportFunctionality(SQLContainer container, Button exportGridButton)
        throws IOException {
    // setup the export as .csv file functionality
    String exportOffersFileName = pathOnServer + "offers.csv";
    exportFileDownloader = new FileDownloader(new FileResource(new File(exportOffersFileName))) {
        @Override
        public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
                throws IOException {
            createExportContent(container, exportOffersFileName, exportFileDownloader);
            return super.handleConnectorRequest(request, response, path);
        }
    };
    exportFileDownloader.extend(exportGridButton);
}

From source file:life.qbic.components.OfferManagerTab.java

License:Open Source License

/**
 * adds the functionality of generating the offer file and exporting it to the printOfferButton
 * @param db: database to connect to/*w w w.j  a v  a2s .  com*/
 * @param printOfferButton: button where the functionality should be added
 * @param container: SQLContainer holding the data
 * @param packageNames: list of all the package names in the current offer
 * @param packageDescriptions: list of all the package descriptions in the current offer
 * @param packageCounts: list of all the package counts in the current offer
 * @param packageUnitPrices: list of all the package prices in the current offer
 * @param packageTotalPrices: list of all the package total prices in the current offer
 * @throws IOException:
 */
private static void setupOfferFileExportFunctionality(Database db, Button printOfferButton,
        SQLContainer container, List<String> packageNames, List<String> packageDescriptions,
        List<String> packageCounts, List<String> packageUnitPrices, List<String> packageTotalPrices)
        throws IOException {
    // init with some non-existent file
    fileDownloader = new FileDownloader(new FileResource(new File("temp"))) {
        @Override
        public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
                throws IOException {

            // fails if no offer has been selected
            boolean success = generateOfferFile(container, db, packageNames, packageDescriptions, packageCounts,
                    packageUnitPrices, packageTotalPrices, fileDownloader);

            // offer file could not be generated, so we return nothing
            if (!success) {
                return false;
            }
            // handle the download of the file
            return super.handleConnectorRequest(request, response, path);
        }
    };
    fileDownloader.extend(printOfferButton);
}

From source file:life.qbic.components.OfferManagerTab.java

License:Open Source License

/**
 * generates the .docx file for the offer
 * @param container: sql container holding the offers
 * @param db: database instance/*from w  w w .j a va  2  s  . co m*/
 * @param packageNames: list of the package names in the offer
 * @param packageDescriptions: list of the package descriptions in the offer
 * @param packageCounts: list of the package counts in the offer
 * @param packageUnitPrices: list of the package unit prices (=price for one package)
 * @param packageTotalPrices: list of the total package prices (package_unit_price*count)*discount
 * @param fileDownloader: file downloader for enabling the download of the file
 * @return whether or not creating the file has worked
 */
private static boolean generateOfferFile(SQLContainer container, Database db, List<String> packageNames,
        List<String> packageDescriptions, List<String> packageCounts, List<String> packageUnitPrices,
        List<String> packageTotalPrices, FileDownloader fileDownloader) {

    if (offerManagerGrid.getSelectedRow() == null) {
        displayNotification("oOps! Forgot something?!", "Please make sure that you select an offer.", "error");
        return false;
    }

    displayNotification("File is being generated",
            "Please wait a few seconds while the file is " + "being generated..", "warning");

    // since we take the package specific values from the grid showing the packages for the current offers,
    // we need to check whether all packages are displayed or e.g. only the sequencing packages
    String selectedPackageGroup = packageGroupComboBox.getValue().toString();
    if (!selectedPackageGroup.equals("All")) {
        packageGroupComboBox.setValue("All");
    }

    String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();

    // file holding the content controls for the bindings
    String contentControlFilename = basepath + "/WEB-INF/resourceFiles/contentControlTemplate.xml";
    // template .docx file containing the bindings
    String templateFileName = basepath + "/WEB-INF/resourceFiles/Template.docx";

    String clientName = container.getItem(offerManagerGrid.getSelectedRow()).getItemProperty("offer_facility")
            .getValue().toString();

    String offerNumber = container.getItem(offerManagerGrid.getSelectedRow()).getItemProperty("offer_number")
            .getValue().toString();

    String[] address = db.getAddressForPerson(clientName);
    String groupAcronym = null;
    String institute = null;
    String umbrellaOrganization = null;
    String street = null;
    String cityZipCodeAndCounty = null;
    String zipCode;
    String city;
    String country;

    // deal with the potential errors; address[0] contains a more detailed error message and tells the user how to fix the issue
    if (address.length == 1) {
        displayNotification("Database entry not found!", address[0], "warning");
    } else {
        groupAcronym = address[0];
        institute = address[1];
        umbrellaOrganization = address[2];
        street = address[3];
        zipCode = address[4];
        city = address[5];
        country = address[6];

        // e.g. D - 72076 Tbingen, Germany
        // TODO: country in english (database entry is in german..), postal code of country (is not in the database)
        cityZipCodeAndCounty = zipCode + " " + city + ", " + country;
    }

    String projectReference = offerNumber.substring(offerNumber.indexOf('_') + 1);

    String clientEmail = db.getClientEmailFromProjectRef(projectReference);

    // TODO: for liferay it probably needs some adjustments, since I couldn't test this properly..
    String projectManager;
    String projectManagerMail;
    try {
        projectManager = LiferayAndVaadinUtils.getUser().getScreenName();
        projectManagerMail = db.getUserEmail(projectManager);
    } catch (NullPointerException e) {
        projectManager = "Project manager not found";
        projectManagerMail = "Mail not found";
    }

    String projectTitle = container.getItem(offerManagerGrid.getSelectedRow()).getItemProperty("offer_name")
            .getValue().toString();
    if (projectTitle == null) {
        displayNotification("Offer name is null", "Warning: The offer name for the current offer is null."
                + "The respective fields in the .docx file will thus hold the placeholder values. Please consider "
                + "setting the offer name in the Offer Manager tab.", "warning");
    }

    Object projectDescriptionObject = container.getItem(offerManagerGrid.getSelectedRow())
            .getItemProperty("offer_description").getValue();
    String projectDescription = projectDescriptionObject == null ? null : projectDescriptionObject.toString();
    if (projectDescription == null) {
        displayNotification("Offer description is null.", "Warning: The offer description for the current "
                + "offer is null. The respective fields in the .docx file will thus hold the placeholder values. Please "
                + "consider setting the offer name in the Offer Manager tab.", "warning");
    }

    DecimalFormat offerPriceFormatter = new DecimalFormat("###,###.###");
    String offerTotal = offerPriceFormatter.format(Float.valueOf(container
            .getItem(offerManagerGrid.getSelectedRow()).getItemProperty("offer_total").getValue().toString()));

    String clientSurname = clientName.split(" ")[clientName.split(" ").length - 1];
    String dateToday = new SimpleDateFormat("yyyyMMdd").format(new Date());
    String projectQuotationNumber = dateToday + "_" + clientSurname + "_" + projectReference;

    SimpleDateFormat currentDateFormat = new SimpleDateFormat("EEEE, dd MMMM yyyy", Locale.ENGLISH);
    String currentDate = currentDateFormat.format(new Date());

    // get the xml document holding the content for the bindings in the docx template file
    org.w3c.dom.Document contentControlDocument = readXMLFile(contentControlFilename);

    // change the fields of the content control document according to the values obtained in the grid
    changeNodeTextContent(contentControlDocument, "client_name", clientName);
    changeNodeTextContent(contentControlDocument, "client_organization", groupAcronym);
    changeNodeTextContent(contentControlDocument, "client_department", institute);
    changeNodeTextContent(contentControlDocument, "client_university", umbrellaOrganization);
    changeNodeTextContent(contentControlDocument, "client_address", street);
    changeNodeTextContent(contentControlDocument, "client_address_town", cityZipCodeAndCounty);
    changeNodeTextContent(contentControlDocument, "client_email", clientEmail);
    changeNodeTextContent(contentControlDocument, "project_reference", projectReference);
    changeNodeTextContent(contentControlDocument, "project_quotation_number", projectQuotationNumber);
    changeNodeTextContent(contentControlDocument, "name", projectManager);
    changeNodeTextContent(contentControlDocument, "email", projectManagerMail);
    changeNodeTextContent(contentControlDocument, "project_title", projectTitle);
    changeNodeTextContent(contentControlDocument, "objective", projectDescription);
    changeNodeTextContent(contentControlDocument, "estimated_total", formatCurrency(offerTotal));
    changeNodeTextContent(contentControlDocument, "date", currentDate);

    // iterate over the packages and add them to the content control .xml file
    for (int i = packageNames.size() - 1; i >= 0; i--) {
        addRowToTable(contentControlDocument, 1, packageNames.get(i) + ": " + packageDescriptions.get(i),
                packageCounts.get(i), formatCurrency(packageUnitPrices.get(i)),
                formatCurrency(packageTotalPrices.get(i)), String.valueOf(i + 1));
    }

    // remove the placeholder row in the .xml file
    removeRowInTable(contentControlDocument, packageNames.size());

    // apply the bindings to the .docx template file
    WordprocessingMLPackage wordProcessor = Docx4jUtils.applyBindings(contentControlDocument, templateFileName);

    String outputFilename = pathOnServer + projectQuotationNumber + ".docx";

    // save updated document to output file
    try {
        assert wordProcessor != null;
        wordProcessor.save(new File(outputFilename), Docx4J.FLAG_SAVE_ZIP_FILE);
    } catch (Docx4JException e) {
        e.printStackTrace();
    }
    fileDownloader.setFileDownloadResource(new FileResource(new File(outputFilename)));

    return true;
}

From source file:life.qbic.components.PackageManagerTab.java

License:Open Source License

/**
 * adds the listeners to the three buttons
 * @param db: database instance to query
 * @param addPackageButton: button for creating a new package
 * @param updatePackageGroupComboBox: combo box for selecting the package group
 * @param updateSelectedPackageButton: button for updating a package
 * @param deleteSelectedPackageButton: button for deleting a package
 * @param container: SQLContainer holding the data from the database
 * @param packageGrid: grid holding the packages
 * @param exportTableButton: button for exporting the grid as csv
 *///  w ww  . j  a v  a2  s  .c o m
private static void addListeners(Database db, Button addPackageButton, ComboBox updatePackageGroupComboBox,
        Button updateSelectedPackageButton, Button deleteSelectedPackageButton, SQLContainer container,
        RefreshableGrid packageGrid, Button exportTableButton) {

    addPackageButton.addClickListener(new Button.ClickListener() {

        /**
         *
         */
        private static final long serialVersionUID = 8181926819540586585L;

        @Override
        public void buttonClick(Button.ClickEvent event) {
            DBManager.getDatabaseInstance().addNewPackage("*** New Package - double click to edit ***");
            displayNotification("New Package Added",
                    "Please edit the package details! If the details are not complete, incompatibility "
                            + "issues are expected to happen.",
                    "success");
            packageGrid.clearSortOrder();
            packageGrid.sort("package_name", SortDirection.ASCENDING);
        }
    });

    updateSelectedPackageButton.addClickListener((Button.ClickListener) event -> {

        if (packageGrid.getSelectedRow() == null) {
            displayNotification("oOps! Forgot something?!",
                    "Please make sure that you select a package to update.", "error");
        } else if (updatePackageGroupComboBox.getValue() == null) {
            displayNotification("oOps! Forgot something?!",
                    "Please make sure that you select an option for the package group.", "error");
        } else {
            String selectedPackageGroup = updatePackageGroupComboBox.getValue().toString();
            String packageId = packageGrid.getSelectedRow().toString();
            db.updatePackageGroupForPackage(selectedPackageGroup, packageId);
            container.refresh();
        }
    });

    deleteSelectedPackageButton.addClickListener((Button.ClickListener) event -> {
        Object selectedRow = packageGrid.getSelectedRow();
        if (selectedRow == null) {
            displayNotification("No package selected!", "Please select a package to delete.", "error");
            return;
        }

        int selectedPackageId = (int) packageGrid.getContainerDataSource().getItem(selectedRow)
                .getItemProperty("package_id").getValue();

        // check if package is used in a offer
        boolean isPackageSelected = db.isPackageSelectedForAnyOffer(selectedPackageId);
        if (isPackageSelected) {
            // get the first offer_id from the offers where the package is in use
            int offerId = db.getFirstOfferIdForPackageId(selectedPackageId);
            displayNotification("Package in use", "Package " + selectedPackageId + " is used by offer "
                    + offerId + " ! Please remove the package from the offer before deleting it.", "error");
            return;
        }

        db.deletePackage(selectedPackageId);
        // since refreshing the rows doesn't work properly; we force an update of the grid by setting the sort direction
        // of the package name column
        packageGrid.sort("package_name", SortDirection.ASCENDING);
        displayNotification("Package deleted", "Package " + selectedPackageId + " successfully deleted.",
                "success");
    });

    // setup the export as .csv file functionality
    String exportPackagesFileName = pathOnServer + "packages.csv";
    fileDownloader = new FileDownloader(new FileResource(new File(exportPackagesFileName))) {
        @Override
        public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
                throws IOException {
            createExportContent(container, exportPackagesFileName, fileDownloader);
            return super.handleConnectorRequest(request, response, path);
        }
    };
    fileDownloader.extend(exportTableButton);

}

From source file:life.qbic.utils.qOfferManagerUtils.java

License:Open Source License

/**
 * creates the content for exporting the tables as .csv file
 * @param container: SQLContainer which should be exported as .csv
 * @param exportFileName: filename of the .csv file
 * @param fileDownloader: file downloader for downloading the .csv file
 *///from ww  w .j  av a 2s.c  om
public static void createExportContent(SQLContainer container, String exportFileName,
        FileDownloader fileDownloader) {
    try {
        // get the contents of the container as a comma separated string
        String containerContents = getContainerContents(container, ",");

        // write the csv file
        try (PrintStream ps = new PrintStream(exportFileName)) {
            ps.print(containerContents);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        fileDownloader.setFileDownloadResource(new FileResource(new File(exportFileName)));
    } catch (Exception e) {
        throw new RuntimeException("Error exporting!", e);
    }
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.file.ImageDisplay.java

License:Apache License

public void setImages(List<File> files) {
    images.clear();
    files.forEach((f) -> {
        images.add(new FileResource(f));
    });
}

From source file:net.sourceforge.javydreamercsw.validation.manager.web.file.ImageDisplay.java

License:Apache License

@Override
public Window getViewer(File f) {
    w = new VMWindow(f.getName());
    boolean found = false;
    for (FileResource fr : images) {
        if (fr.getFilename().equals(f.getName())) {
            found = true;/*from  www.ja  v  a  2 s .com*/
            break;
        }
    }
    if (!found) {
        images.add(new FileResource(f));
    }
    imageViewer.setImages(images);
    w.setContent(imageViewer);
    w.setHeight(80, Sizeable.Unit.PERCENTAGE);
    w.setWidth(80, Sizeable.Unit.PERCENTAGE);
    imageViewer.setCenterImageIndex(0);
    imageViewer.focus();
    return w;
}

From source file:nl.kpmg.lcm.ui.view.administration.LcmIdPanel.java

License:Apache License

public void refreshLcmIdPanel() {
    VerticalLayout panelContent = new VerticalLayout();
    panelContent.setMargin(true);/*  www  .  jav  a2s.c  o m*/
    panelContent.setSpacing(true);

    HorizontalLayout idLayout = new HorizontalLayout();
    idLayout.setMargin(true);
    idLayout.setSpacing(true);
    idLayout.addComponent(new Label("Your LCM id: " + lcmId.getItem().getLcmId()));
    idLayout.addComponent(new Button("Copy", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            StringSelection stringSelection = new StringSelection(lcmId.getItem().getLcmId());
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stringSelection, null);
        }
    }));

    HorizontalLayout certificateLayout = new HorizontalLayout();
    certificateLayout.setMargin(true);
    certificateLayout.setSpacing(true);
    certificateLayout.addComponent(new Label("Certificate file that need to be given to the Authorized LCM. "));
    FileResource certificateResource = new FileResource(new File(certificateFilepath));
    FileDownloader fileDownloader = new FileDownloader(certificateResource);
    Button certificateDownload = new Button("Download Certificate");
    fileDownloader.extend(certificateDownload);

    certificateLayout.addComponent(certificateDownload);

    panelContent.addComponent(idLayout);
    panelContent.addComponent(certificateLayout);
    panel.setContent(panelContent);
}

From source file:nz.co.senanque.workflowui.AttachmentsPopup.java

License:Apache License

private void makeStream(final Attachment attachment) {
    final FileResource stream = new FileResource(new File("")) {
        private static final long serialVersionUID = 1L;

        @Override/*from  w ww . j  a v  a 2s .  co m*/
        public DownloadStream getStream() {
            ByteArrayInputStream in = new ByteArrayInputStream(attachment.getBody());
            DownloadStream ds = new DownloadStream(in, attachment.getMIMEType(), attachment.getFileName());
            // Need a file download POPUP
            ds.setParameter("Content-Disposition", "attachment; filename=" + attachment.getFileName());
            return ds;
        }
    };
    stream.setCacheTime(0);
    Page.getCurrent().open(stream, "_blank", true);
    //        panel.requestRepaint();
}