Example usage for com.vaadin.server FileDownloader setFileDownloadResource

List of usage examples for com.vaadin.server FileDownloader setFileDownloadResource

Introduction

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

Prototype

public void setFileDownloadResource(Resource resource) 

Source Link

Document

Sets the resource that is downloaded when the extended component is clicked.

Usage

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  ww  .j  a v  a 2s.c  om*/
 * @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.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  w  ww  .j  a va2  s.  c o  m
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);
    }
}