view gwt-client/src/main/java/org/dive4elements/river/client/client/ui/TableDataPanel.java @ 9416:05405292a7ca

Navigationtheme panel now shows themes of dWt and WQ charts grayed out, if the current station is outside the valid range of the theme.
author gernotbelger
date Thu, 16 Aug 2018 16:28:03 +0200
parents 217e8e59c386
children
line wrap: on
line source
/* Copyright (C) 2011, 2012, 2013 by Bundesanstalt für Gewässerkunde
 * Software engineering by Intevation GmbH
 *
 * This file is Free Software under the GNU AGPL (>=v3)
 * and comes with ABSOLUTELY NO WARRANTY! Check out the
 * documentation coming with Dive4Elements River for details.
 */

package org.dive4elements.river.client.client.ui;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.dive4elements.river.client.client.Config;
import org.dive4elements.river.client.client.FLYSConstants;
import org.dive4elements.river.client.client.services.CSVExportService;
import org.dive4elements.river.client.client.services.CSVExportServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;

/**
 * This UIProvider creates a widget that displays calculated data in a table.
 *
 * @author <a href="mailto:raimund.renkert@intevation.de">Raimund Renkert</a>
 */
public class TableDataPanel {
    /** The message class that provides i18n strings. */
    protected FLYSConstants MESSAGES = GWT.create(FLYSConstants.class);

    protected CSVExportServiceAsync exportService = GWT.create(CSVExportService.class);

    /** A container that will contain the location or the distance panel. */
    protected VLayout container;

    /** The export type. */
    protected String name;

    /** The UUID of the collection. */
    protected String uuid;

    /** The table. */
    protected ListGrid dataTable;

    private final TabSet tabSet;

    /**
     * Creates a new TableDataPanel instance.
     */
    public TableDataPanel() {
        this.container = new VLayout();
        this.dataTable = new ListGrid();
        this.tabSet = new TabSet();
        this.name = "";
    }

    /**
     * This method creates a widget that contains a table.
     *
     * @return a panel.
     */
    public Canvas create() {
        final Config config = Config.getInstance();
        final String locale = config.getLocale();
        this.dataTable.setEmptyMessage(this.MESSAGES.empty_table());
        this.dataTable.setShowHeaderContextMenu(false);
        this.dataTable.setCanDragSelectText(true);

        this.exportService.getCSV(locale, this.uuid, this.name, new AsyncCallback<List<String[]>>() {
            @Override
            public void onFailure(final Throwable caught) {
                GWT.log("Could not receive csv.");
                SC.warn(caught.getMessage());
            }

            @Override
            public void onSuccess(final List<String[]> l) {
                GWT.log("Recieved csv with " + l.size() + " lines.");
                setData(l);
            }
        });
        this.container.addMember(this.dataTable);

        return this.container;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public void setUuid(final String uuid) {
        this.uuid = uuid;
    }

    /**
     * This method sets the data to a dynamic table.
     *
     * @param list
     *            List of String[] containing the data.
     */

    public void setData(final List<String[]> list) {
        if (list == null || list.size() < 2) {
            this.dataTable.setEmptyMessage(this.MESSAGES.error_no_calc_result());
            this.dataTable.redraw();
            return;
        }

        final Config config = Config.getInstance();
        final String locale = config.getLocale();

        NumberFormat nf;
        if (locale.equals("de")) {
            nf = NumberFormat.getFormat("#,##");
        } else {
            nf = NumberFormat.getFormat("#.##");
        }
        final Map<String, List<String[]>> tabData = getTabData(list);
        if (tabData.size() == 1) {
            createTable(this.dataTable, tabData.get(tabData.keySet().iterator().next()), nf);

        } else if (tabData.size() > 1) {

            for (final String key : tabData.keySet()) {
                final List<String[]> items = tabData.get(key);

                final ListGrid table = new ListGrid();

                createTable(table, items, nf);
                final Tab tab = new Tab();
                tab.setTitle(key);
                tab.setPane(table);
                this.tabSet.addTab(tab);
            }
            this.tabSet.selectTab(0);
            this.container.removeChild(this.dataTable);
            this.container.addChild(this.tabSet);
            this.tabSet.setWidth100();
            this.tabSet.setHeight100();
        }
    }

    private void createTable(final ListGrid dataTableTab, final List<String[]> list, final NumberFormat nf) {

        final String[] header = list.get(0);
        final String[] displayField = new String[header.length];

        final ListGridField[] fields = new ListGridField[header.length];

        for (int i = 0; i < header.length; i++) {
            final ListGridField f = new ListGridField(String.valueOf(i));
            fields[i] = f;
            f.setTitle(header[i]);

            try {
                /*
                 * Try to determine the type with the first
                 * non empty element. -> WARUM??! OK, nur Formatierung/Sortierung
                 */
                for (int j = 1; j < list.size(); j++) {
                    if (!list.get(j)[i].isEmpty()) {
                        nf.parse(list.get(j)[i]);
                        f.setType(ListGridFieldType.FLOAT);

                        break;
                    }
                }
            }
            catch (final NumberFormatException nfe) {
                f.setType(ListGridFieldType.TEXT);
            }

            // To keep server-side formatting and i18n also of
            // float values, we will store the value once formatted 'as is'
            // to be displayed and once as e.g. float to allow functions like
            // sorting on it.
            displayField[i] = "$" + i + "_displayField";
            f.setDisplayField(displayField[i]);
            f.setValueField(String.valueOf(i));
            f.setSortByDisplayField(false);
        }
        dataTableTab.setFields(fields);

        for (int i = 1; i < list.size(); i++) { // index bei 1, da erster Eintrag Header ist

            final String[] sItem = list.get(i);
            final Record r = new Record();
            for (int j = 0; j < sItem.length; j++) {
                // See above, display 'as is' from server, but keep value
                // in machine-usable way (float), to allow numeric sorting.
                final String item = sItem[j];
                final String encodedText = SafeHtmlUtils.htmlEscapeAllowEntities(item);

                r.setAttribute(displayField[j], encodedText);
                if (fields[j].getType() == ListGridFieldType.TEXT) {
                    r.setAttribute(String.valueOf(j), item);
                } else {
                    try {
                        final Float valueFloatSortable = (float) nf.parse(item);
                        r.setAttribute(String.valueOf(j), valueFloatSortable);
                    }
                    catch (final NumberFormatException nfe) {
                        r.setAttribute(String.valueOf(j), item);
                    }
                }

            }

            dataTableTab.addData(r);
        }
    }

    private Map<String, List<String[]>> getTabData(final List<String[]> raw) {
        // Condition: tableTitle must be first
        final Map<String, List<String[]>> tabs = new TreeMap<String, List<String[]>>(); // auto-sort

        if (raw.get(0)[0].startsWith(this.MESSAGES.export_csv_title())) {
            // Bedingung für Tabs
            int lastIndex = 0;
            String lastTableTitle = "";

            for (int i = 0; i < raw.size(); i++) {

                final String[] row = raw.get(i);
                if (row[0].startsWith(this.MESSAGES.export_csv_title())) {

                    if (i > 0) {
                        tabs.put(makeKeyTitle(lastTableTitle, tabs.size()), raw.subList((lastIndex + 1), (i))); // toIndex exclusive (without
                                                                                                                // tabTitle-Line of the next tab, which is
                                                                                                                // stored in the current row (raw.get(i));
                                                                                                                // fromIndex
                                                                                                                // inclusive ->
                                                                                                                // without tabTitle from the past tab ->
                                                                                                                // lastindex+1
                    }
                    lastTableTitle = row[0].replace(this.MESSAGES.export_csv_title(), "");
                    lastIndex = i;
                }

                if (i == (raw.size() - 1)) {
                    tabs.put(makeKeyTitle(lastTableTitle, tabs.size()), raw.subList((lastIndex + 1), i + 1));
                    // last result-tab:
                    // toIndex exclusive -> last i + 1
                    // fromIndex inclusive: lastInde +1 -> no title-line included
                }

            }
        } else {
            // plainOld Table, no TABS
            tabs.put("", raw);
        }

        return tabs;
    }

    private String makeKeyTitle(final String title, final int index) {
        return new StringBuilder().append("(").append((index + 1)).append(") ").append(title).toString();
    }
}
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org