Example usage for org.apache.wicket.ajax AjaxRequestTarget prependJavaScript

List of usage examples for org.apache.wicket.ajax AjaxRequestTarget prependJavaScript

Introduction

In this page you can find the example usage for org.apache.wicket.ajax AjaxRequestTarget prependJavaScript.

Prototype

void prependJavaScript(CharSequence javascript);

Source Link

Document

Adds javascript that will be evaluated on the client side before components are replaced.

Usage

From source file:de.alpharogroup.wicket.dialogs.examples.panel.ModalDialogWithStylePanel.java

License:Apache License

@Override
protected MarkupContainer newOpenModalLink(final String id, final IModel<String> model) {
    return new LinkPanel(id, Model.of("Press me")) {

        /**/*  ww  w. j av a 2s .  c  om*/
         * The serialVersionUID
         */
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            /**
             * This is how to prevent IE and Firefox dialog popup when trying to
             * setResponsePage() or set an info message from a wicket modalWindow per below.
             * Dialog popup demands an answer to: "This page is asking you to confirm that you
             * want to leave - data you have entered may not be saved."
             **/
            target.prependJavaScript("Wicket.Window.unloadConfirmation = false;");
            getModalWindow().show(target);
        }
    };
}

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotator.java

License:Apache License

public BratAnnotator(String id, IModel<BratAnnotatorModel> aModel, final AnnotationDetailEditorPanel aEditor) {
    super(id, aModel);
    this.editor = aEditor;
    // Allow AJAX updates.
    setOutputMarkupId(true);//  w  ww.  ja  va 2s . c  om

    // The annotator is invisible when no document has been selected. Make sure that we can
    // make it visible via AJAX once the document has been selected.
    setOutputMarkupPlaceholderTag(true);

    if (getModelObject().getDocument() != null) {
        collection = "#" + getModelObject().getProject().getName() + "/";
    }

    vis = new WebMarkupContainer("vis");
    vis.setOutputMarkupId(true);

    controller = new AbstractDefaultAjaxBehavior() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void respond(AjaxRequestTarget aTarget) {
            final IRequestParameters request = getRequest().getPostParameters();
            aTarget.addChildren(getPage(), FeedbackPanel.class);
            // Parse annotation ID if present in request
            VID paramId;
            if (!request.getParameterValue(PARAM_ID).isEmpty()
                    && !request.getParameterValue(PARAM_ARC_ID).isEmpty()) {
                throw new IllegalStateException("[id] and [arcId] cannot be both set at the same time!");
            } else if (!request.getParameterValue(PARAM_ID).isEmpty()) {
                paramId = VID.parseOptional(request.getParameterValue(PARAM_ID).toString());
            } else {
                paramId = VID.parseOptional(request.getParameterValue(PARAM_ARC_ID).toString());
            }

            // Ignore ghosts
            if (paramId.isGhost()) {
                error("This is a ghost annotation, select layer and feature to annotate.");
                return;
            }

            // Get action
            String action = request.getParameterValue(PARAM_ACTION).toString();

            // Load the CAS if necessary
            boolean requiresCasLoading = action.equals(SpanAnnotationResponse.COMMAND)
                    || action.equals(ArcAnnotationResponse.COMMAND)
                    || action.equals(GetDocumentResponse.COMMAND);
            JCas jCas = null;
            if (requiresCasLoading) {
                // Make sure we load the CAS only once here in case of an annotation action.
                try {
                    jCas = getCas(getModelObject());
                } catch (ClassNotFoundException e) {
                    error("Invalid reader: " + e.getMessage());
                } catch (IOException e) {
                    error(e.getMessage());
                } catch (UIMAException e) {
                    error(ExceptionUtils.getRootCauseMessage(e));
                }
            }

            // HACK: If an arc was clicked that represents a link feature, then open the
            // associated span annotation instead.
            if (paramId.isSlotSet() && action.equals(ArcAnnotationResponse.COMMAND)) {
                action = SpanAnnotationResponse.COMMAND;
                paramId = new VID(paramId.getId());
            }

            BratAjaxCasController controller = new BratAjaxCasController(repository, annotationService);

            // Doing anything but a span annotation when a slot is armed will unarm it
            if (getModelObject().isSlotArmed() && !action.equals(SpanAnnotationResponse.COMMAND)) {
                getModelObject().clearArmedSlot();
            }

            Object result = null;
            try {
                LOG.info("AJAX-RPC CALLED: [" + action + "]");

                if (action.equals(WhoamiResponse.COMMAND)) {
                    result = controller.whoami();
                } else if (action.equals(SpanAnnotationResponse.COMMAND)) {
                    assert jCas != null;
                    // do not annotate closed documents
                    if (editor.isAnnotationFinished()) {
                        error("This document is already closed. Please ask your project manager to re-open it via the Montoring page");
                        LOG.error(
                                "This document is already closed. Please ask your project manager to re-open it via the Montoring page");
                        return;
                    }
                    if (getModelObject().isSlotArmed()) {
                        if (paramId.isSet()) {
                            // Fill slot with existing annotation
                            editor.setSlot(aTarget, jCas, getModelObject(), paramId.getId());
                        } else if (!CAS.TYPE_NAME_ANNOTATION
                                .equals(getModelObject().getArmedFeature().getType())) {
                            // Fill slot with new annotation (only works if a concrete type is
                            // set for the link feature!
                            SpanAdapter adapter = (SpanAdapter) getAdapter(annotationService,
                                    annotationService.getLayer(getModelObject().getArmedFeature().getType(),
                                            getModelObject().getProject()));

                            Offsets offsets = getSpanOffsets(request, jCas, paramId);

                            try {
                                int id = adapter.add(jCas, offsets.getBegin(), offsets.getEnd(), null, null);
                                editor.setSlot(aTarget, jCas, getModelObject(), id);
                            } catch (BratAnnotationException e) {
                                error(ExceptionUtils.getRootCauseMessage(e));
                                LOG.error(ExceptionUtils.getRootCauseMessage(e), e);
                            }
                        } else {
                            throw new BratAnnotationException(
                                    "Unable to create annotation of type [" + CAS.TYPE_NAME_ANNOTATION
                                            + "]. Please click an annotation in stead of selecting new text.");
                        }
                    } else {
                        /*if (paramId.isSet()) {
                        getModelObject().setForwardAnnotation(false);
                        }*/
                        // Doing anything but filling an armed slot will unarm it
                        editor.clearArmedSlotModel();
                        getModelObject().clearArmedSlot();

                        Selection selection = getModelObject().getSelection();

                        selection.setRelationAnno(false);

                        Offsets offsets = getSpanOffsets(request, jCas, paramId);

                        selection.setAnnotation(paramId);
                        selection.set(jCas, offsets.getBegin(), offsets.getEnd());
                        bratRenderHighlight(aTarget, selection.getAnnotation());
                        editor.reloadLayer(aTarget);

                        if (selection.getAnnotation().isNotSet()) {
                            selection.setAnnotate(true);
                            editor.actionAnnotate(aTarget, getModelObject(), false);
                        } else {
                            selection.setAnnotate(false);
                            bratRender(aTarget, jCas);
                            result = new SpanAnnotationResponse();
                        }
                    }
                } else if (action.equals(ArcAnnotationResponse.COMMAND)) {
                    assert jCas != null;
                    // do not annotate closed documents
                    if (editor.isAnnotationFinished()) {
                        error("This document is already closed. Please ask your project manager to re-open it via the Montoring page");
                        LOG.error(
                                "This document is already closed. Please ask your project manager to re-open it via the Montoring page");
                        return;
                    }
                    Selection selection = getModelObject().getSelection();

                    selection.setRelationAnno(true);
                    selection.setAnnotation(paramId);
                    selection.setOriginType(request.getParameterValue(PARAM_ORIGIN_TYPE).toString());
                    selection.setOrigin(request.getParameterValue(PARAM_ORIGIN_SPAN_ID).toInteger());
                    selection.setTargetType(request.getParameterValue(PARAM_TARGET_TYPE).toString());
                    selection.setTarget(request.getParameterValue(PARAM_TARGET_SPAN_ID).toInteger());

                    bratRenderHighlight(aTarget, getModelObject().getSelection().getAnnotation());
                    editor.reloadLayer(aTarget);
                    if (getModelObject().getSelection().getAnnotation().isNotSet()) {
                        selection.setAnnotate(true);
                        editor.actionAnnotate(aTarget, getModelObject(), false);
                    } else {
                        selection.setAnnotate(false);
                        bratRender(aTarget, jCas);
                        result = new ArcAnnotationResponse();
                    }
                } else if (action.equals(LoadConfResponse.COMMAND)) {
                    result = controller.loadConf();
                } else if (action.equals(GetCollectionInformationResponse.COMMAND)) {
                    if (getModelObject().getProject() != null) {
                        result = controller.getCollectionInformation(getModelObject().getAnnotationLayers());
                    } else {
                        result = new GetCollectionInformationResponse();
                    }
                } else if (action.equals(GetDocumentResponse.COMMAND)) {
                    if (getModelObject().getProject() != null) {
                        result = controller.getDocumentResponse(getModelObject(), 0, jCas, true);
                    } else {
                        result = new GetDocumentResponse();
                    }
                }

                LOG.info("AJAX-RPC DONE: [" + action + "]");
            } catch (ClassNotFoundException e) {
                LOG.error("Invalid reader: " + e.getMessage(), e);
                error("Invalid reader: " + e.getMessage());
            } catch (Exception e) {
                error("Unexpected error: " + e.getMessage());
                LOG.error(ExceptionUtils.getRootCauseMessage(e));
            }

            // Serialize updated document to JSON
            if (result == null) {
                LOG.warn("AJAX-RPC: Action [" + action + "] produced no result!");
            } else {
                String json = toJson(result);
                // Since we cannot pass the JSON directly to Brat, we attach it to the HTML
                // element into which BRAT renders the SVG. In our modified ajax.js, we pick it
                // up from there and then pass it on to BRAT to do the rendering.
                aTarget.prependJavaScript("Wicket.$('" + vis.getMarkupId() + "').temp = " + json + ";");
            }
            aTarget.addChildren(getPage(), FeedbackPanel.class);
            if (getModelObject().getSelection().getAnnotation().isNotSet()) {
                editor.setAnnotationLayers(getModelObject());
            }
            editor.reload(aTarget);
            if (BratAnnotatorUtility.isDocumentFinished(repository, getModelObject())) {
                error("This document is already closed. Please ask your project "
                        + "manager to re-open it via the Montoring page");
            }
        }
    };

    add(vis);
    add(controller);
}

From source file:de.webplatz.addons.NavbarScrollToAnchorAjaxLink.java

License:Open Source License

/**
 * Overriden onclick.//from w w  w . j a v  a2s.  com
 * Adds javaScript to the request target which scrolls to the anchor.
 *
 * @param target Request target where to add the scroll.
 */
@Override
public final void onClick(final AjaxRequestTarget target) {
    target.prependJavaScript(String.format("%1s%2$s%3$s", "$('html,body').animate({scrollTop: $(\"a[name='",
            this.anchor, "']\").offset().top - 50}, 'slow');"));
}

From source file:eu.uqasar.web.components.Effects.java

License:Apache License

/**
 * /*from   w  w w . ja v  a2s.co m*/
 * @param target
 * @param component
 * @param jsAddTemplate
 * @param componentHtmlTag
 * @param containerMarkupId
 */
private static void addAndFadeIn(AjaxRequestTarget target, Component component, String jsAddTemplate,
        String componentHtmlTag, String containerMarkupId) {
    // add 'display:none' so that it is initially hidden
    component.add(new DisplayNoneBehavior());
    // add JS to append or prepend component to container html and hide it
    // initially
    target.prependJavaScript(
            String.format(jsAddTemplate, componentHtmlTag, component.getMarkupId(), containerMarkupId));
    target.add(component);// add JS to fade in the new idea
    target.appendJavaScript(String.format(JSTemplates.FADE_IN_ELEM_TEMPLATE, component.getMarkupId()));
}

From source file:eu.uqasar.web.components.Effects.java

License:Apache License

/**
 * Replaces the given {@code component} in HTML using a fade out fade in
 * effect.//from w  w  w  . ja va 2  s  .  c o m
 * 
 * @param target
 * @param component
 */
public static void replaceWithFading(AjaxRequestTarget target, Component component) {
    component.add(new DisplayNoneBehavior());
    target.prependJavaScript(String.format(JSTemplates.FADE_OUT_ELEM_TEMPLATE, component.getMarkupId()));
    target.add(component);
    target.appendJavaScript(String.format(JSTemplates.FADE_IN_ELEM_TEMPLATE, component.getMarkupId()));
}

From source file:eu.uqasar.web.components.Effects.java

License:Apache License

/**
 * Replaces the given {@code component} in HTML using a slide up slide down
 * effect./*from  www .  ja va 2 s .c o  m*/
 * 
 * @param target
 * @param component
 */
public static void replaceWithSliding(AjaxRequestTarget target, Component component) {
    component.add(new DisplayNoneBehavior());
    target.prependJavaScript(String.format(JSTemplates.SLIDE_UP_ELEM_TEMPLATE, component.getMarkupId()));
    target.add(component);
    target.appendJavaScript(String.format(JSTemplates.SLIDE_DOWN_ELEM_TEMPLATE, component.getMarkupId()));
}

From source file:gr.abiss.calipso.wicket.EditItemRenderingTemplatePanel.java

License:Open Source License

/**
 * just closes the window, override to actually persist
 * //from  w  w w . ja va2  s  .  c  o  m
 * @param modalWindow
 * @param itemRenderingTemplateForm
 * @return
 */
protected AjaxButton getSaveButton(final ModalWindow modalWindow,
        Form<ItemRenderingTemplate> itemRenderingTemplateForm, final FeedbackPanel feedbackPanel) {
    AjaxButton save = new IndicatingAjaxButton(BUTTON_SAVE, itemRenderingTemplateForm) {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            persist(target, form);
            if (target != null) {
                target.prependJavaScript("removeEditors();");
                modalWindow.close(target);
            }
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form form) {
            if (target != null) {
                target.addComponent(feedbackPanel);
            }
        }
    };
    save.add(new TinyMceAjaxSubmitModifier());
    return save;
}

From source file:gr.abiss.calipso.wicket.EditItemRenderingTemplatePanel.java

License:Open Source License

protected AjaxButton getCancelButton(final ModalWindow modalWindow,
        Form<ItemRenderingTemplate> itemRenderingTemplateForm) {
    AjaxButton cancel = new AjaxButton(BUTTON_CANCEL, itemRenderingTemplateForm) {

        @Override/*from  w ww  .ja va  2 s  .  c o  m*/
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            if (target != null) {
                target.prependJavaScript("removeEditors();");
                modalWindow.close(target);
            }
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
        }

    };
    return cancel;
}

From source file:gr.eap.pages.AnalysisPage.java

License:Open Source License

public AnalysisPage(final PageParameters parameters) {
    if (parameters == null || parameters.isEmpty()) {
        analysis = ((EapSession) getSession()).getAnalysis();
    } else {//from   w w w.  j a  va2  s .  co m
        String code = parameters.get(0).toString();
        if (code == null) {
            analysis = new Analysis();
            warn(" .");
        } else if ("new".equals(code)) {
            analysis = new Analysis();
        } else {
            analysis = getDataStore().get(code);
            if (analysis == null) {
                analysis = new Analysis();
                warn(" ?   : " + code);
            }
        }

    }
    if (analysis == null) {
        analysis = new Analysis();
    }
    ((EapSession) getSession()).setAnalysis(analysis);

    Form<Analysis> form = new Form<Analysis>("form", new CompoundPropertyModel<Analysis>(analysis));
    form.add(new TextField<String>("title"));
    form.add(new TextArea<String>("description"));
    form.add(new TextField<String>("keywords"));
    form.add(new TextField<String>("usageEstimation"));
    form.add(new CheckBox("keyusers"));
    form.add(new CheckBox("itDepartment"));
    form.add(new CheckBox("sensitiveData"));

    form.add(new SubmitLink("submit") {
        @Override
        public void onSubmit() {
            setResponsePage(ViewAnalysis.class);
        }
    });
    add(form);

    final WebMarkupContainer solutionsContainer = new WebMarkupContainer("solutionsContainer");
    solutionsContainer.setOutputMarkupId(true);
    form.add(solutionsContainer);
    final WebMarkupContainer sygkrishContainer = new WebMarkupContainer("sygkrishContainer");
    sygkrishContainer.setOutputMarkupId(true);
    form.add(sygkrishContainer);

    solutionsContainer.add(new PropertyListView<Lysh>("solutions", analysis.getLyseis()) {
        @Override
        protected void populateItem(final ListItem<Lysh> item) {
            item.add(new Label("title"));
            Form<Lysh> lyshForm = new Form<Lysh>("solution_form");
            lyshForm.setDefaultModel(new CompoundPropertyModel<Lysh>(item.getModelObject()));
            lyshForm.add(new TextField<String>("title"));
            lyshForm.add(
                    new DropDownChoice<Integer>("anapty3hBy", weightedChoices, new Anapty3hChoiceRenderer()));
            lyshForm.add(
                    new DropDownChoice<Integer>("synthrhshBy", weightedChoices, new Anapty3hChoiceRenderer()));
            lyshForm.add(new TextArea<String>("techDesc"));
            lyshForm.add(
                    new DropDownChoice<Integer>("filo3eniaBy", normalChoices, new Filo3eniaChoiceRenderer()));
            lyshForm.add(
                    new DropDownChoice<Integer>("diaxeirishBy", normalChoices, new Anapty3hChoiceRenderer()));
            lyshForm.add(new AjaxSubmitLink("save_solution") {
                private static final long serialVersionUID = 1L;

                @Override
                protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                    target.add(solutionsContainer);
                    target.add(sygkrishContainer);
                    target.prependJavaScript("hideSolutionForm();");
                }

                @Override
                protected void onError(AjaxRequestTarget target, Form<?> form) {
                    getSession().error("? ?!!!");
                    target.add(getFeedbackPanel());
                }
            });
            lyshForm.add(new AjaxFallbackLink<AnalysisPage>("cancel") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    target.add(solutionsContainer);
                    target.add(sygkrishContainer);
                    target.prependJavaScript("hideSolutionForm();");
                }
            });
            item.add(lyshForm);
            item.add(new AjaxFallbackLink<AnalysisPage>("delete") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    analysis.getLyseis().remove(item.getModelObject());
                    target.add(solutionsContainer);
                    target.add(sygkrishContainer);
                }

                @Override
                protected IAjaxCallDecorator getAjaxCallDecorator() {
                    return new AjaxCallDecorator() {
                        private static final long serialVersionUID = 1L;

                        @Override
                        public CharSequence decorateScript(Component c, CharSequence script) {
                            return "if( !confirm(' ?   ?  ?   \""
                                    + item.getModelObject().getTitle() + "\";') ) return false;" + script;
                        }
                    };
                }
            });
        }
    });

    sygkrishContainer.add(new PropertyListView<Lysh>("solutions", analysis.getLyseis()) {
        @Override
        protected void populateItem(final ListItem<Lysh> item) {
            item.add(new Label("title"));
            Form<Lysh> lyshForm = new Form<Lysh>("solution_form");
            lyshForm.setDefaultModel(new CompoundPropertyModel<Lysh>(item.getModelObject()));
            lyshForm.add(new Label("title"));
            lyshForm.add(new TextField<BigDecimal>("kostosAnapty3hsF"));
            lyshForm.add(new TextField<Long>("xronosAnapty3hs"));
            lyshForm.add(new TextField<BigDecimal>("ethsioKostosSynthrhshsF"));
            lyshForm.add(new TextField<BigDecimal>("ethsioKostosFilo3eniasF"));
            lyshForm.add(new TextField<BigDecimal>("ethsioKostosDiaxeirishsF"));
            lyshForm.add(new TextField<BigDecimal>("ethsioKostosAdeiwnF"));
            lyshForm.add(new AjaxSubmitLink("save_solution") {
                private static final long serialVersionUID = 1L;

                @Override
                protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                    target.add(solutionsContainer);
                    target.add(sygkrishContainer);
                    target.prependJavaScript("hideSolutionForm();");
                }

                @Override
                protected void onError(AjaxRequestTarget target, Form<?> form) {
                    getSession().error("? ?!!!");
                    target.add(getFeedbackPanel());
                }
            });
            lyshForm.add(new AjaxFallbackLink<AnalysisPage>("cancel") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    target.add(solutionsContainer);
                    target.add(sygkrishContainer);
                    target.prependJavaScript("hideSolutionForm();");
                }
            });
            item.add(lyshForm);
        }
    });

    form.add(new AjaxFallbackLink<AnalysisPage>("add_solution") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            analysis.getLyseis().add(new Lysh());
            target.add(solutionsContainer);
            target.add(sygkrishContainer);
        }
    });
}

From source file:name.martingeisse.wicket.component.misc.ExpandableRepeater.java

License:Open Source License

/**
 * Expands the number of visible batches by one.
 *//* ww w.j av  a  2s .co m*/
public final void expandByOneBatch() {

    // Increment the batch count -- this will already cause a full render to consider the new batch.
    batchCount++;

    // In non-AJAX calls, that's it. In AJAX calls, we'll have to render an on-the-fly update.
    final AjaxRequestTarget target = AjaxRequestUtil.getAjaxRequestTarget();
    if (target == null) {
        return;
    }

    // build items
    final int batchIndex = batchCount - 1;
    final List<E> batch = loadBatch(batchIndex);
    final int expansionSize = batch.size();
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("var newItemMarkupIds = [");
    boolean first = true;
    for (int localIndex = 0; localIndex < expansionSize; localIndex++) {
        final IModel<E> listItemModel = new PropertyModel<E>(batch, Integer.toString(localIndex));
        final Item<E> listItem = newItem(internalGetItemId(batchIndex, localIndex), listItemModel);
        add(listItem);
        populateItem(listItem);
        if (first) {
            first = false;
        } else {
            stringBuilder.append(',');
        }
        JavascriptAssemblerUtil.appendStringLiteral(stringBuilder, listItem.getMarkupId());
        target.add(listItem);
    }

    // build append script
    stringBuilder.append("];\n");
    stringBuilder.append("var $parent = $('#").append(initialItemMarkupId).append("').parent();");
    stringBuilder.append("for (var i in newItemMarkupIds) {\n");
    stringBuilder.append("  var item = document.createElement('").append(validElementType).append("'); ");
    stringBuilder.append("  item.id = newItemMarkupIds[i];");
    stringBuilder.append("  $parent.append(item);");
    stringBuilder.append("}\n");
    target.prependJavaScript(stringBuilder);

}