Example usage for com.google.gwt.safehtml.shared SafeHtmlUtils htmlEscape

List of usage examples for com.google.gwt.safehtml.shared SafeHtmlUtils htmlEscape

Introduction

In this page you can find the example usage for com.google.gwt.safehtml.shared SafeHtmlUtils htmlEscape.

Prototype

public static String htmlEscape(String s) 

Source Link

Document

HTML-escapes a string.

Usage

From source file:net.eve.finger.client.WinViewChar.java

License:Open Source License

/**
 * Creates the note editor grid./*  w ww.jav a2 s .c o m*/
 * @return The note editor grid.
 */
private EditorGrid<BeanModel> createNotesGrid() {
    // Holds the columns
    List<ColumnConfig> columns = new ArrayList<ColumnConfig>(3);

    // ************ BEGIN: Build the notes column ************

    // Create the column's editor and container
    TextArea noteEditor = new TextArea();

    ColumnConfig noteConfig = new ColumnConfig("notes", "Notes", 100);
    CellEditor noteCellEditor = new CellEditor(noteEditor);
    noteEditor.setHeight(50);
    noteCellEditor.setAutoSizeMode(AutoSizeMode.WIDTH);
    noteConfig.setEditor(noteCellEditor);

    // We'd like this column to have wordwrap
    noteConfig.setRenderer(new GridCellRenderer<BeanModel>() {
        @Override
        public Object render(BeanModel model, String property,
                com.extjs.gxt.ui.client.widget.grid.ColumnData config, int rowIndex, int colIndex,
                ListStore<BeanModel> store, Grid<BeanModel> grid) {
            StringBuilder sb = new StringBuilder();
            sb.append("<span style='white-space:normal'>");
            String noteLines[] = SafeHtmlUtils.htmlEscape((String) model.get("notes")).split("\n");
            for (String line : noteLines) {
                sb.append(line);
                sb.append("<br/>");
            }
            sb.append("</span>");
            return sb.toString();
        }
    });

    // Add the notes column
    columns.add(noteConfig);

    // ************ END: Build the notes column ************

    // Add the added by column
    columns.add(new ColumnConfig("addedByName", "Added By", 70));

    // ************ BEGIN: Build the access column ************

    // Create the column container
    ColumnConfig accessConfig = new ColumnConfig("neededAccess", "Access", 70);

    // Since access groups are integers, we need to render something more
    // meaningful, such as the access group's name.
    accessConfig.setRenderer(new GridCellRenderer<BeanModel>() {
        @Override
        public Object render(BeanModel model, String property,
                com.extjs.gxt.ui.client.widget.grid.ColumnData config, int rowIndex, int colIndex,
                ListStore<BeanModel> store, Grid<BeanModel> grid) {
            StringBuilder sb = new StringBuilder();
            sb.append("<span>");
            sb.append((String) accessStore.findModel("id", model.get("neededAccess")).get("name"));
            sb.append("</span>");
            return sb.toString();
        }
    });

    // Create an editor for the access column
    ComboBox<BeanModel> accessEditor = new ComboBox<BeanModel>();
    accessEditor.setStore(accessStore);
    accessEditor.setDisplayField("name");
    accessEditor.setTriggerAction(TriggerAction.ALL);
    accessEditor.setEditable(false);
    accessEditor.setForceSelection(true);

    // We'll need some custom handling to transport values
    // between the combo box and the grid/store
    CellEditor accessEditorConfig = new CellEditor(accessEditor) {
        /**
         * From testing, it appears that this function
         * is supposed to return the model that should be
         * set in the editor when the user enters edit mode.
         * @param value Seems to be the value from the grid's model
         *            that the editor should be set to represent.
         */
        @Override
        public Object preProcessValue(Object value) {
            if (value == null) {
                return value;
            }
            return accessStore.findModel("id", value);
        }

        /**
         * From testing, it appears that this function
         * is supposed to return the value that should be
         * put in the grid/model when the edit is complete.
         * @param value Seems to be the ModelData selected in
         *            the editor.
         */
        @Override
        public Object postProcessValue(Object value) {
            if (value == null) {
                return value;
            }
            return ((ModelData) value).get("id");
        }
    };
    accessConfig.setEditor(accessEditorConfig);

    // Add the access column
    columns.add(accessConfig);

    // ************ END: Build the access column ************

    // Create the grid
    final EditorGrid<BeanModel> notesGrid = new EditorGrid<BeanModel>(charNotesStore, new ColumnModel(columns));

    // This actually disables click to edit behavior for
    // the row editor
    notesRowEditor.setClicksToEdit(ClicksToEdit.TWO);

    // Enable the row editor plugin
    notesGrid.addPlugin(notesRowEditor);

    // ************ BEGIN: Build the grid's context menu ************

    // Create the menu
    Menu notesCtxMenu = new Menu();

    // Build the edit item
    final MenuItem editItem = new MenuItem("Edit");
    editItem.addSelectionListener(new SelectionListener<MenuEvent>() {
        @Override
        public void componentSelected(MenuEvent ce) {
            // Delete the currently selected note
            executeEditNote();
        }
    });
    editItem.setEnabled(false);
    notesCtxMenu.add(editItem);

    // Build the delete item
    final MenuItem deleteItem = new MenuItem("Delete");
    deleteItem.addSelectionListener(new SelectionListener<MenuEvent>() {
        @Override
        public void componentSelected(MenuEvent ce) {
            // Delete the currently selected note
            executeDeleteNote();
        }

    });
    deleteItem.setEnabled(false);
    notesCtxMenu.add(deleteItem);

    // ************ END: Build the grid's context menu ************

    // Set the grid's context menu
    notesGrid.setContextMenu(notesCtxMenu);

    // Setup the selection model      
    final GridSelectionModel<BeanModel> selModel = new GridSelectionModel<BeanModel>();
    selModel.bindGrid(notesGrid);
    selModel.bind(charNotesStore);
    selModel.setSelectionMode(SelectionMode.SINGLE);
    notesGrid.setSelectionModel(selModel);

    // Custom click handling for the grid to change
    // selection behavior and manage the context menu
    notesGrid.addListener(Events.OnMouseDown, new Listener<GridEvent<BeanModel>>() {
        @Override
        public void handleEvent(GridEvent<BeanModel> e) {
            // Get the row (if one exists)                  
            BeanModel note = e.getModel();

            // Is there a row?
            if (note != null) {
                // Set if the user can update this row               
                editItem.setEnabled((Integer) note.get("addedBy") == userID);

                // Allow the user to delete the row
                deleteItem.setEnabled(true);

                // Select this row            
                selModel.select(note, false);
            } else {
                // No selection, don't allow the user to invoke
                // actions on the grid context menu
                editItem.setEnabled(false);
                deleteItem.setEnabled(false);
            }
        }
    });

    // Suppress click to edit functionality
    notesGrid.addListener(Events.BeforeEdit, new Listener<GridEvent<BeanModel>>() {
        @Override
        public void handleEvent(GridEvent<BeanModel> e) {
            // TODO Auto-generated method stub
            e.setCancelled(true);
        }
    });

    // Set simple properties      
    notesGrid.setAutoExpandColumn("notes");
    notesGrid.setTabIndex(2);
    notesGrid.setStripeRows(true);

    // Return the grid
    return notesGrid;
}

From source file:net.scran24.admin.client.NewSurvey.java

License:Apache License

public NewSurvey() {
    contents = new FlowPanel();

    final Grid surveyParametersGrid = new Grid(7, 2);
    surveyParametersGrid.setCellPadding(5);

    contents.add(surveyParametersGrid);//from  w  w  w.ja  v  a2 s . c om

    final Label idLabel = new Label("Survey identifier: ");
    final TextBox idTextBox = new TextBox();

    surveyParametersGrid.setWidget(0, 0, idLabel);
    surveyParametersGrid.setWidget(0, 1, idTextBox);

    final Label schemeBoxLabel = new Label("Survey scheme: ");
    final ListBox schemeBox = new ListBox();
    schemeBox.setMultipleSelect(false);

    final Label localeLabel = new Label("Locale: ");
    final ListBox localeBox = new ListBox();
    localeBox.setMultipleSelect(false);

    localeBox.addItem("English (UK)", "en_GB");
    localeBox.addItem("English (New Zealand)", "en_NZ");
    localeBox.addItem("Portuguese (Portugal)", "pt_PT");
    localeBox.addItem("Danish (Denmark)", "da_DK");
    localeBox.addItem("Arabic (UAE)", "ar_AE");

    for (SurveySchemeReference s : SurveySchemes.allSchemes)
        schemeBox.addItem(s.description(), s.id());

    schemeBox.setSelectedIndex(0);

    surveyParametersGrid.setWidget(1, 0, schemeBoxLabel);
    surveyParametersGrid.setWidget(1, 1, schemeBox);

    surveyParametersGrid.setWidget(2, 0, localeLabel);
    surveyParametersGrid.setWidget(2, 1, localeBox);

    final Label genUserLabel = new Label("Allow auto login: ");
    final CheckBox genCheckBox = new CheckBox();

    surveyParametersGrid.setWidget(3, 0, genUserLabel);
    surveyParametersGrid.setWidget(3, 1, genCheckBox);

    final Label forwardToSurveyMonkey = new Label("SurveyMonkey support:");
    final CheckBox smCheckBox = new CheckBox();

    surveyParametersGrid.setWidget(4, 0, forwardToSurveyMonkey);
    surveyParametersGrid.setWidget(4, 1, smCheckBox);

    final Label surveyMonkeyUrl = new Label("SurveyMonkey link:");
    final TextBox smUrlTextBox = new TextBox();

    surveyParametersGrid.setWidget(5, 0, surveyMonkeyUrl);
    surveyParametersGrid.setWidget(5, 1, smUrlTextBox);

    smUrlTextBox.setEnabled(false);

    final Label supportEmailLabel = new Label("Support e-mail:");
    final TextBox supportEmailTextBox = new TextBox();

    surveyParametersGrid.setWidget(6, 0, supportEmailLabel);
    surveyParametersGrid.setWidget(6, 1, supportEmailTextBox);

    smCheckBox.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
        @Override
        public void onValueChange(ValueChangeEvent<Boolean> valueChangeEvent) {
            smUrlTextBox.setEnabled(valueChangeEvent.getValue());
        }
    });

    final FlowPanel errorDiv = new FlowPanel();
    errorDiv.getElement().addClassName("scran24-admin-survey-id-error-message");

    contents.add(errorDiv);

    final Button createButton = WidgetFactory.createButton("Create survey");

    createButton.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            createButton.setEnabled(false);
            final String id = idTextBox.getText();
            errorDiv.clear();

            String smUrlText = smUrlTextBox.getText();

            Option<String> smUrl;

            if (smCheckBox.getValue())
                smUrl = smUrlText.isEmpty() ? Option.<String>none() : Option.some(smUrlText);
            else
                smUrl = Option.<String>none();

            if (smCheckBox.getValue() && smUrlText.isEmpty()) {
                errorDiv.add(new Label("Please paste the SurveyMonkey link!"));
                createButton.setEnabled(true);
                return;
            } else if (smCheckBox.getValue()
                    && !smUrlText.contains("intake24_username=[intake24_username_value]")) {
                errorDiv.add(new Label("Invalid SurveyMonkey link: intake24_username variable missing!"));
                createButton.setEnabled(true);
                return;
            }

            service.createSurvey(id, schemeBox.getValue(schemeBox.getSelectedIndex()),
                    localeBox.getValue(localeBox.getSelectedIndex()), genCheckBox.getValue(), smUrl,
                    supportEmailTextBox.getValue(), new AsyncCallback<Option<String>>() {
                        @Override
                        public void onSuccess(Option<String> result) {
                            result.accept(new Option.SideEffectVisitor<String>() {
                                @Override
                                public void visitSome(String error) {
                                    errorDiv.add(new Label(error));
                                    createButton.setEnabled(true);
                                }

                                @Override
                                public void visitNone() {
                                    contents.clear();
                                    contents.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(
                                            "<h2>Survey created!</h2><p>Please go to <strong>Survey management</strong> and upload the staff accounts for the new survey.</p>")));
                                }
                            });
                        }

                        @Override
                        public void onFailure(Throwable caught) {
                            createButton.setEnabled(true);
                            errorDiv.add(
                                    new Label("Server error (" + SafeHtmlUtils.htmlEscape(caught.getMessage())
                                            + "), please check server logs"));
                        }
                    });
        }
    });
    createButton.getElement().addClassName("scran24-admin-button");

    VerticalPanel buttonsPanel = new VerticalPanel();
    buttonsPanel.add(createButton);

    contents.add(buttonsPanel);

    initWidget(contents);
}

From source file:net.scran24.admin.client.SurveyManagement.java

private void setControlsFor(String id) {
    surveyControls.clear();/*  w  w w.  j ava 2  s . co  m*/

    final HTMLPanel idLabel = new HTMLPanel("<h2>" + SafeHtmlUtils.htmlEscape(id) + "</h2>");
    final HTMLPanel staffUploadLabel = new HTMLPanel("<h3>Upload staff accounts</h3>");
    final FlowPanel messageDiv = new FlowPanel();
    messageDiv.getElement().addClassName("scran24-admin-survey-id-message");

    List<String> permissions = Arrays.asList(new String[] { "downloadData:" + id, "readSurveys:" + id,
            "uploadUserInfo:" + id, "surveyControl:" + id });

    final UserInfoUpload staffUpload = new UserInfoUpload(id, "staff", permissions,
            new Callback1<Option<String>>() {
                @Override
                public void call(Option<String> res) {
                    res.accept(new Option.SideEffectVisitor<String>() {
                        @Override
                        public void visitSome(String error) {
                            messageDiv.clear();
                            messageDiv.getElement().getStyle().setColor("#d00");
                            messageDiv.add(new HTMLPanel(SafeHtmlUtils.fromString(error)));
                        }

                        @Override
                        public void visitNone() {
                            messageDiv.clear();
                            messageDiv.getElement().getStyle().setColor("#0d0");
                            messageDiv.add(new HTMLPanel(
                                    SafeHtmlUtils.fromString("Staff accounts uploaded successfully")));
                        }
                    });
                }
            });

    surveyControls.add(idLabel);
    surveyControls.add(staffUploadLabel);
    surveyControls.add(messageDiv);
    surveyControls.add(staffUpload);

}

From source file:net.scran24.common.client.Section.java

public static <T extends Widget> Section<T> withSimpleHeader(String title, T content) {
    return new Section<T>(
            new HTMLPanel(SafeHtmlUtils.fromSafeConstant("<h2>" + SafeHtmlUtils.htmlEscape(title) + "</h2>")),
            content);//from  ww  w .j a  v  a 2  s  .c  o m
}

From source file:net.scran24.staff.client.StaffPage.java

private void showSurveyStatus() {
    content.clear();//from www .j av  a  2s  .c o m

    switch (parameters.state) {
    case SUSPENDED:
        content.add(new HTMLPanel("<h1>Survey is suspended</h1>"));
        content.add(new HTMLPanel(
                "<h2>Reason</h2><p>" + SafeHtmlUtils.htmlEscape(parameters.suspensionReason) + "</p>"));

        Button resumeButton = WidgetFactory.createButton("Resume", new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                surveyControl.setParameters(parameters.withState(SurveyState.ACTIVE).withSuspensionReason(""),
                        new AsyncCallback<Void>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                content.clear();
                                content.add(new HTMLPanel("<p>Server error: </p>" + caught.getMessage()));
                            }

                            @Override
                            public void onSuccess(Void result) {
                                Location.reload();
                            }
                        });
            }
        });

        resumeButton.getElement().addClassName("scran24-admin-button");

        content.add(resumeButton);
        break;
    case NOT_INITIALISED:
        content.add(new HTMLPanel("<h1>Survey has not yet been activated</h1>"));
        content.add(new HTMLPanel("<p>Follow the instructions below to activate the survey."));

        FlowPanel initDiv = new FlowPanel();
        content.add(initDiv);

        initStage1(initDiv);
        break;
    case ACTIVE:
        Date now = new Date();

        boolean showSuspend = true;

        if (now.getTime() < parameters.startDate)
            content.add(new HTMLPanel("<h1>Survey is active, but not yet started</h1>"));
        else if (now.getTime() > parameters.endDate) {
            content.add(new HTMLPanel("<h1>Survey is finished</h1>"));
            showSuspend = false;
        } else
            content.add(new HTMLPanel("<h1>Survey is running</h1>"));

        content.add(new HTMLPanel("<h2>Start date (inclusive)</h2>"));
        content.add(new HTMLPanel(
                "<p>" + DateTimeFormat.getFormat("EEE, MMMM d, yyyy").format(new Date(parameters.startDate))
                        + "</p>"));

        content.add(new HTMLPanel("<h2>End date (exclusive)</h2>"));
        content.add(new HTMLPanel("<p>"
                + DateTimeFormat.getFormat("EEE, MMMM d, yyyy").format(new Date(parameters.endDate)) + "</p>"));

        if (showSuspend) {

            content.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant("<h3>Suspend survey</h3>")));
            content.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant("<p>Reason for suspension:</p>")));
            final TextBox reason = new TextBox();
            reason.getElement().getStyle().setWidth(600, Unit.PX);

            Button suspend = WidgetFactory.createButton("Suspend", new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    if (reason.getText().isEmpty()) {
                        Window.alert("Please give a reason for suspension.");
                    } else {
                        surveyControl.setParameters(parameters.withSuspensionReason(reason.getText())
                                .withState(SurveyState.SUSPENDED), new AsyncCallback<Void>() {
                                    @Override
                                    public void onSuccess(Void result) {
                                        Location.reload();
                                    }

                                    @Override
                                    public void onFailure(Throwable caught) {
                                        Window.alert("Server error: " + caught.getMessage());
                                    }
                                });
                    }
                }
            });

            suspend.getElement().addClassName("scran24-admin-button");

            content.add(reason);
            content.add(new HTMLPanel("<p></p>"));
            content.add(suspend);
        }
        break;
    }
}

From source file:net.scran24.user.client.Scran24.java

License:Apache License

public void initPage(final UserInfo userInfo) {
    final RootPanel links = RootPanel.get("navigation-bar");

    Anchor watchTutorial = new Anchor(surveyMessages.navBar_tutorialVideo(), TutorialVideo.url, "_blank");

    Anchor logOut = new Anchor(surveyMessages.navBar_logOut(),
            "../../common/logout" + Location.getQueryString());

    // These divs are no longer used for content, but this code is left here
    // to handle legacy survey files

    Element se = Document.get().getElementById("suspended");
    if (se != null)
        se.removeFromParent();/*from  w  w w. j  a v  a  2s.  c  o m*/
    Element ae = Document.get().getElementById("active");
    if (ae != null)
        ae.removeFromParent();
    Element fe = Document.get().getElementById("finished");
    if (fe != null)
        fe.removeFromParent();
    Element ee = Document.get().getElementById("serverError");
    if (ee != null)
        ee.removeFromParent();
    Element fpe = Document.get().getElementById("finalPage");
    if (fpe != null)
        fpe.removeFromParent();

    mainContent = Document.get().getElementById("main-content");
    mainContent.setInnerHTML("");

    HTMLPanel mainContentPanel = HTMLPanel.wrap(mainContent);

    switch (userInfo.surveyParameters.state) {
    case NOT_INITIALISED:
        mainContentPanel
                .add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(surveyMessages.survey_notInitialised())));
        links.add(new NavigationBar(watchTutorial, logOut));
        break;
    case SUSPENDED:
        mainContentPanel.add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(surveyMessages
                .survey_suspended(SafeHtmlUtils.htmlEscape(userInfo.surveyParameters.suspensionReason)))));
        links.add(new NavigationBar(watchTutorial, logOut));
        break;
    case ACTIVE:
        Date now = new Date();

        if (now.getTime() > userInfo.surveyParameters.endDate) {
            mainContentPanel
                    .add(new HTMLPanel(SafeHtmlUtils.fromSafeConstant(surveyMessages.survey_finished())));
        } else {
            SurveyInterfaceManager surveyInterfaceManager = new SurveyInterfaceManager(mainContentPanel);

            SurveyScheme scheme = SurveySchemeMap.initScheme(
                    SurveySchemes.schemeForId(userInfo.surveyParameters.schemeName),
                    LocaleInfo.getCurrentLocale().getLocaleName(), surveyInterfaceManager);

            links.add(new NavigationBar(scheme.navBarLinks(), watchTutorial, logOut));

            scheme.showNextPage();
        }
        break;
    }

    RootPanel.get("loading").getElement().removeFromParent();

    initComplete();
}

From source file:net.scran24.user.client.survey.flat.rules.AskIfHomeRecipe.java

private Prompt<FoodEntry, FoodOperation> buildPrompt(final String foodName, final boolean isDrink) {
    PVector<String> options = TreePVector.<String>empty().plus(messages.homeRecipe_haveRecipeChoice())
            .plus(messages.homeRecipe_noRecipeChoice());

    return PromptUtil.asFoodPrompt(new RadioButtonPrompt(
            SafeHtmlUtils.fromSafeConstant(
                    messages.homeRecipe_promptText(SafeHtmlUtils.htmlEscape(foodName.toLowerCase()))),
            AskIfHomeRecipe.class.getSimpleName(), options, messages.homeRecipe_continueButtonLabel(),
            "homeRecipeOption", Option.<String>none()), new Function1<String, FoodOperation>() {
                @Override/*from  www. j a v a  2  s .c o m*/
                public FoodOperation apply(String argument) {
                    if (argument.equals(messages.homeRecipe_haveRecipeChoice())) {
                        GoogleAnalytics.trackMissingFoodHomeRecipe();
                        return FoodOperation
                                .replaceWith(new CompoundFood(FoodLink.newUnlinked(), foodName, isDrink));
                    } else {
                        return FoodOperation.update(new Function1<FoodEntry, FoodEntry>() {
                            @Override
                            public FoodEntry apply(FoodEntry argument) {
                                GoogleAnalytics.trackMissingFoodNotHomeRecipe();
                                return argument.withFlag(MissingFood.NOT_HOME_RECIPE_FLAG);
                            }
                        });
                    }
                }
            });
}

From source file:net.scran24.user.client.survey.flat.rules.ShowHomeRecipeServingsPrompt.java

@Override
public Option<Prompt<Pair<FoodEntry, Meal>, MealOperation>> apply(final Pair<FoodEntry, Meal> data,
        SelectionMode selectionType, final PSet<String> surveyFlags) {
    return data.left.accept(new FoodEntry.Visitor<Option<Prompt<Pair<FoodEntry, Meal>, MealOperation>>>() {

        private Option<Prompt<Pair<FoodEntry, Meal>, MealOperation>> getPromptIfApplicable(
                final FoodEntry food) {
            if (forall(Meal.linkedFoods(data.right.foods, data.left), FoodEntry.isPortionSizeComplete)
                    && (!food.customData.containsKey(Recipe.SERVINGS_NUMBER_KEY))) {

                FractionalQuantityPrompt quantityPrompt = new FractionalQuantityPrompt(
                        SafeHtmlUtils.fromSafeConstant(messages
                                .homeRecipe_servingsPromptText(SafeHtmlUtils.htmlEscape(food.description()))),
                        messages.homeRecipe_servingsButtonLabel());

                return Option.some(
                        PromptUtil.asExtendedFoodPrompt(quantityPrompt, new Function1<Double, MealOperation>() {
                            @Override
                            public MealOperation apply(final Double servings) {
                                return MealOperation.updateFood(data.right.foodIndex(food),
                                        new Function1<FoodEntry, FoodEntry>() {
                                            @Override
                                            public FoodEntry apply(FoodEntry argument) {
                                                return argument.withCustomDataField(Recipe.SERVINGS_NUMBER_KEY,
                                                        Double.toString(servings));
                                            }
                                        });

                            }/* w  ww .j  av  a2s .  c o  m*/
                        }));
            } else {
                return Option.none();
            }
        }

        @Override
        public Option<Prompt<Pair<FoodEntry, Meal>, MealOperation>> visitRaw(RawFood food) {
            return Option.none();
        }

        @Override
        public Option<Prompt<Pair<FoodEntry, Meal>, MealOperation>> visitEncoded(EncodedFood food) {
            return Option.none();
        }

        @Override
        public Option<Prompt<Pair<FoodEntry, Meal>, MealOperation>> visitTemplate(final TemplateFood food) {
            if (food.isTemplateComplete())
                return getPromptIfApplicable(food);
            else
                return Option.none();
        }

        @Override
        public Option<Prompt<Pair<FoodEntry, Meal>, MealOperation>> visitMissing(MissingFood food) {
            return Option.none();
        }

        @Override
        public Option<Prompt<Pair<FoodEntry, Meal>, MealOperation>> visitCompound(CompoundFood food) {
            return getPromptIfApplicable(food);
        }

    });
}

From source file:net.scran24.user.client.survey.portionsize.experimental.AsServedScript.java

License:Apache License

@Override
public Option<SimplePrompt<UpdateFunc>> nextPrompt(PMap<String, String> data, FoodData foodData) {
    boolean hasLeftoverImages = !leftoversImages.isEmpty();

    /*Logger log = Logger.getLogger("AsServedScript");
            /*from  w ww .  j a v a 2  s.c  om*/
    log.info("Has leftovers: " + hasLeftoverImages);
            
    for (String k : data.keySet()) {
       log.info (k + " = " + data.get(k));
    }*/

    if (!data.containsKey("servingWeight")) {
        SimplePrompt<UpdateFunc> portionSizePrompt = withBackLink(asServedPrompt(servingImages,
                messages.asServed_servedLessButtonLabel(), messages.asServed_servedMoreButtonLabel(),
                messages.asServed_servedContinueButtonLabel(), "servingChoiceIndex", "servingImage",
                "servingWeight", defaultServingSizePrompt(foodData.description())));

        if (!hasLeftoverImages)
            return Option.some(setAdditionalField(portionSizePrompt, "leftoversWeight", "0"));
        else
            return Option.some(portionSizePrompt);
    } else if (!data.containsKey("leftoversWeight") && hasLeftoverImages) {
        if (!data.containsKey("leftovers"))
            return Option.some(withBackLink(yesNoPromptZeroField(
                    SafeHtmlUtils.fromSafeConstant(messages.asServed_leftoversQuestionPromptText(
                            SafeHtmlUtils.htmlEscape(foodData.description().toLowerCase()))),
                    messages.yesNoQuestion_defaultYesLabel(), messages.yesNoQuestion_defaultNoLabel(),
                    "leftovers", "leftoversWeight")));
        else
            return Option.some(withBackLink(asServedPrompt(leftoversImages.getOrDie(),
                    messages.asServed_leftLessButtonLabel(), messages.asServed_leftMoreButtonLabel(),
                    messages.asServed_leftContinueButtonLabel(), "leftoversChoiceIndex", "leftoversImage",
                    "leftoversWeight", defaultLeftoversPrompt(foodData.description()))));
    } else
        return done();
}

From source file:net.scran24.user.client.survey.portionsize.experimental.CerealPortionSizeScript.java

License:Apache License

@Override
public Option<SimplePrompt<UpdateFunc>> nextPrompt(PMap<String, String> data, FoodData foodData) {
    if (!data.containsKey("bowl")) {
        return Option
                .some(PromptUtil.map(/*from  w  ww . j  a v a2s.  c o m*/
                        withBackLink(
                                guidePrompt(SafeHtmlUtils.fromSafeConstant(messages.cereal_bowlPromptText()),
                                        bowlImageDef, "bowlIndex", "imageUrl")),
                        new Function1<UpdateFunc, UpdateFunc>() {
                            @Override
                            public UpdateFunc apply(final UpdateFunc f) {
                                return new UpdateFunc() {
                                    @Override
                                    public PMap<String, String> apply(PMap<String, String> argument) {
                                        PMap<String, String> a = f.apply(argument);
                                        return a.plus("bowl",
                                                bowlCodes.get(Integer.parseInt(a.get("bowlIndex")) - 1));
                                    }
                                };
                            }
                        }));
    }
    if (!data.containsKey("servingWeight")) {
        String asServedSetId = "cereal_" + data.get("type") + data.get("bowl");

        SimplePrompt<UpdateFunc> portionSizePrompt = withBackLink(
                asServedPrompt(asServedDefs.get(asServedSetId), messages.asServed_servedLessButtonLabel(),
                        messages.asServed_servedMoreButtonLabel(),
                        messages.asServed_servedContinueButtonLabel(), "servingChoiceIndex", "servingImage",
                        "servingWeight", defaultServingSizePrompt(foodData.description())));
        return Option.some(portionSizePrompt);
    } else if (!data.containsKey("leftoversWeight")) {
        if (!data.containsKey("leftovers"))
            return Option.some(withBackLink(yesNoPromptZeroField(
                    SafeHtmlUtils.fromSafeConstant(messages.asServed_leftoversQuestionPromptText(
                            SafeHtmlUtils.htmlEscape(foodData.description().toLowerCase()))),
                    messages.yesNoQuestion_defaultYesLabel(), messages.yesNoQuestion_defaultNoLabel(),
                    "leftovers", "leftoversWeight")));
        else {
            String leftoversSetId = "cereal_" + data.get("type") + data.get("bowl") + "_leftovers";

            return Option.some(withBackLink(asServedPrompt(asServedDefs.get(leftoversSetId),
                    messages.asServed_leftLessButtonLabel(), messages.asServed_leftMoreButtonLabel(),
                    messages.asServed_leftContinueButtonLabel(), "leftoversChoiceIndex", "leftoversImage",
                    "leftoversWeight", defaultLeftoversPrompt(foodData.description()))));
        }
    } else
        return done();
}