Example usage for org.apache.wicket Component getId

List of usage examples for org.apache.wicket Component getId

Introduction

In this page you can find the example usage for org.apache.wicket Component getId.

Prototype

@Override
public String getId() 

Source Link

Document

Gets the id of this component.

Usage

From source file:com.francetelecom.clara.cloud.presentation.utils.PaasWicketTester.java

License:Apache License

public String lookupPath(final MarkupContainer markupContainer, final String path) {
    // try to look it up directly
    if (markupContainer.get(path) != null)
        return path;

    // if that fails, traverse the component hierarchy looking for it
    final List<Component> candidates = new ArrayList<Component>();
    markupContainer.visitChildren(new IVisitor<Component, List<Component>>() {
        Set<Component> visited = new HashSet<Component>();

        @Override/*w w w .  ja va  2 s  .co  m*/
        public void component(Component c, IVisit<List<Component>> visit) {
            if (!visited.contains(c)) {
                visited.add(c);

                if (c.getId().equals(path)) {
                    candidates.add(c);
                } else {
                    if (c.getPath().endsWith(path)) {
                        candidates.add(c);
                    }
                }
            }
        }
    });
    // if its unambiguous, then return the full path
    if (candidates.isEmpty()) {
        fail("path: '" + path + "' not found for " + Classes.simpleName(markupContainer.getClass()));
        return null;
    } else

    if (candidates.size() == 1) {
        String pathToContainer = markupContainer.getPath();
        String pathToComponent = candidates.get(0).getPath();
        return pathToComponent.replaceFirst(pathToContainer + ":", "");
    } else {
        String message = "path: '" + path + "' is ambiguous for "
                + Classes.simpleName(markupContainer.getClass()) + ". Possible candidates are: ";
        for (Component c : candidates) {
            message += "[" + c.getPath() + "]";
        }
        fail(message);
        return null;
    }
}

From source file:com.github.wicket.autowire.AutoWire.java

License:Apache License

private static Component buildComponent(Component component, final String id, Node child) {
    Class<?> clazz = component.getClass();
    while (Component.class.isAssignableFrom(clazz)) {
        try {//from   w w  w  .j  a v a  2  s  .c  o m
            Field field = null;
            Component value = null;
            // look for annotated field
            for (Field iter : clazz.getDeclaredFields()) {
                if (iter.isAnnotationPresent(AutoComponent.class)) {
                    value = getValue(component, iter);
                    if (value != null && value.getId().equals(id)) {
                        child.field = iter;
                        break;
                    } else {
                        value = null;
                    }
                }
            }
            if (value != null) {
                return value;
            }
        } catch (final SecurityException e) {
            throw new RuntimeException(e);
        } catch (final IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
        clazz = clazz.getSuperclass();
    }

    return null;
}

From source file:com.googlecode.wicketelements.components.lists.ComponentListPanel.java

License:Apache License

private void init(final ComponentListModel componentListModelParam) {
    final ListView<Component> listView = new ListView<Component>("componentList", componentListModelParam) {
        @Override/*from   ww w  .  jav a2 s.c om*/
        protected void populateItem(final ListItem<Component> itemParam) {
            final Component component = itemParam.getModelObject();
            PRE_COND.String.requireNotBlank(component.getId(),
                    "The ComponentList elements must have an id which is not blank.");
            PRE_COND.Logic.requireTrue(Objects.equal(LIST_ELEMENT_WICKET_ID, component.getId()),
                    "The ComponentList elements must have the id: " + LIST_ELEMENT_WICKET_ID);
            itemParam.add(component);
            onItem(itemParam);
            if (isFirstItem(itemParam)) {
                onFirstItem(itemParam);
            }
            if (isLastItem(itemParam)) {
                onLastItem(itemParam);
            }
        }
    };
    add(listView);
}

From source file:com.googlecode.wicketwebbeans.containers.BeanForm.java

License:Apache License

/**
 * Allows external app to set the field to receive focus.
 * // w ww  .ja  v a 2 s.c  o  m
 * @param component the component, may be null to unset the field.
 */
public void setFocusComponent(Component component) {
    setFocusField(component == null ? null : component.getId());
}

From source file:com.premiumminds.webapp.wicket.repeaters.AbstractRepeater2.java

License:Apache License

/**
 * @see org.apache.wicket.Component#onBeforeRender()
 *//*w w  w  . j a v  a  2s. c  om*/
@Override
protected void onBeforeRender() {
    onPopulate();

    if (getApplication().usesDevelopmentConfig()) {
        Iterator<? extends Component> i = iterator();
        while (i.hasNext()) {
            Component c = i.next();
            Matcher matcher = SAFE_CHILD_ID_PATTERN.matcher(c.getId());
            if (!matcher.matches()) {
                log.warn("Child component of repeater " + getClass().getName() + ":" + getId()
                        + " has a non-safe child id of " + c.getId()
                        + ". Safe child ids must be composed of digits only.");
                // do not flood the log
                break;
            }

        }
    }
    super.onBeforeRender();
}

From source file:com.servoy.extensions.plugins.window.popup.wicket.PopupPanel.java

License:Open Source License

/**
 * @param id//w ww. j a  va 2  s.  co  m
 */
public PopupPanel(String id, IForm form, Component elementToShowRelatedTo,
        IClientPluginAccess clientPluginAccess, int width, int height) {
    super(id);
    this.elementToShowRelatedTo = elementToShowRelatedTo;
    this.formName = form.getName();
    this.clientPluginAccess = clientPluginAccess;
    Component formUI = (Component) form.getFormUI();
    add(formUI);
    setOutputMarkupId(true);
    Dimension size = ((FormController) form).getForm().getSize();

    StringBuilder style = new StringBuilder("display:none;position:absolute;z-index:").append(ZINDEX) //$NON-NLS-1$
            .append(";"); //$NON-NLS-1$
    int popupHeight;
    if (height > -1)
        popupHeight = height;
    else {
        popupHeight = size.height;
        int formView = form.getView();
        if (formView == IForm.LIST_VIEW || formView == FormController.LOCKED_LIST_VIEW) {
            IFoundSet formModel = ((FormController) form).getFormModel();
            if (formModel != null) {
                FormController fc = (FormController) form;
                int extraHeight = fc.getPartHeight(Part.HEADER) + fc.getPartHeight(Part.TITLE_HEADER)
                        + fc.getPartHeight(Part.FOOTER) + fc.getPartHeight(Part.TITLE_FOOTER);
                popupHeight = (popupHeight - extraHeight) * formModel.getSize() + extraHeight;
                WebRuntimeWindow window = (WebRuntimeWindow) clientPluginAccess.getCurrentRuntimeWindow();
                int maxHeight = elementToShowRelatedTo instanceof ISupportWebBounds
                        ? window.getHeight()
                                - (int) ((ISupportWebBounds) elementToShowRelatedTo).getWebBounds().getY()
                                - (int) ((ISupportWebBounds) elementToShowRelatedTo).getWebBounds().getHeight()
                        : window.getHeight();
                if (popupHeight > maxHeight)
                    popupHeight = maxHeight;
            }
        }
    }
    style.append("width:").append(width > -1 ? width : size.width).append("px;height:").append(popupHeight) //$NON-NLS-1$//$NON-NLS-2$
            .append("px"); //$NON-NLS-1$

    // the following two lines are not needed when working with Servoy >= 7.4 rc2 (when WebForm already does this for popup form as well), but
    // if we want transparency to work with older versions, they are needed (cause now PopupPanel has class="webform" which by default has a white background)
    boolean isTransparent = ((FormController) form).getForm().getTransparent();
    if (isTransparent)
        style.append(";background:transparent;"); //$NON-NLS-1$

    add(new SimpleAttributeModifier("style", style.toString())); //$NON-NLS-1$

    final StringBuilder formStyle = new StringBuilder();
    if (width < size.width)
        formStyle.append("min-width:").append(width).append("px;"); //$NON-NLS-1$ //$NON-NLS-2$
    if (height < size.height)
        formStyle.append("min-height:").append(height).append("px;"); //$NON-NLS-1$ //$NON-NLS-2$

    enclosingFormSizeBehavior = null;
    enclosingFormComponent = null;
    if (formStyle.length() > 0) {
        ((MarkupContainer) formUI).visitChildren(new IVisitor<Component>() {
            @Override
            public Object component(Component component) {
                if ("servoywebform".equals(component.getId())) //$NON-NLS-1$
                {
                    enclosingFormComponent = component;
                    enclosingFormComponent
                            .add(enclosingFormSizeBehavior = new StyleAppendingModifier(new Model<String>() {
                                private static final long serialVersionUID = 1L;

                                @Override
                                public String getObject() {
                                    return formStyle.toString();
                                }
                            }));

                    return IVisitor.STOP_TRAVERSAL;
                }

                return IVisitor.CONTINUE_TRAVERSAL;
            }
        });
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.ServoySubmitPagingNavigationIncrementLink.java

License:Open Source License

/**
 * @see org.apache.wicket.markup.html.form.IFormSubmittingComponent#getInputName()
 *//* w w  w  .  jav  a 2 s .c om*/
public String getInputName() {

    // TODO: This is a copy & paste from the FormComponent class. 
    String id = getId();
    final PrependingStringBuffer inputName = new PrependingStringBuffer(id.length());
    Component c = this;
    while (true) {
        inputName.prepend(id);
        c = c.getParent();
        if (c == null || (c instanceof Form && ((Form) c).isRootForm()) || c instanceof Page) {
            break;
        }
        inputName.prepend(Component.PATH_SEPARATOR);
        id = c.getId();
    }
    return inputName.toString();
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebCellBasedView.java

License:Open Source License

public WebCellBasedView(final String id, final IApplication application, RuntimePortal scriptable,
        final Form form, final AbstractBase cellview, final IDataProviderLookup dataProviderLookup,
        final IScriptExecuter el, boolean addHeaders, final int startY, final int endY, final int sizeHint,
        int viewType) {
    super(id);/*  w  w w.  ja  va 2  s.c  o  m*/
    this.application = application;
    this.cellview = cellview;
    this.fc = el.getFormController();
    this.addHeaders = addHeaders;
    this.startY = startY;
    this.endY = endY;
    this.formDesignHeight = form.getSize().height;
    this.sizeHint = sizeHint;
    this.isListViewMode = viewType == IForm.LIST_VIEW || viewType == FormController.LOCKED_LIST_VIEW;
    this.bodyWidthHint = form.getWidth();

    double multiplier = Utils.getAsDouble(
            Settings.getInstance().getProperty("servoy.webclient.scrolling.tableview.multiplier", "2"));

    if (multiplier > 1.1) {
        NEW_PAGE_MULITPLIER = multiplier;
    } else {
        NEW_PAGE_MULITPLIER = 1.1;
    }

    useAJAX = Utils.getAsBoolean(application.getRuntimeProperties().get("useAJAX")); //$NON-NLS-1$
    useAnchors = Utils.getAsBoolean(application.getRuntimeProperties().get("enableAnchors")); //$NON-NLS-1$

    // a cell based view should just never version itself if in ajax mode
    // (all things like next page or rerenders are done on the actual page not a version you can go back to (url doesn't change)
    if (useAJAX)
        setVersioned(false);

    setScrollMode(
            Boolean.TRUE.equals(application.getClientProperty(IApplication.TABLEVIEW_WC_DEFAULT_SCROLLABLE)));
    isKeepLoadedRowsInScrollMode = Boolean.TRUE
            .equals(application.getClientProperty(IApplication.TABLEVIEW_WC_SCROLLABLE_KEEP_LOADED_ROWS));

    setOutputMarkupPlaceholderTag(true);

    dataRendererOnRenderWrapper = new DataRendererOnRenderWrapper(this);

    loadingInfo = new Label("info", "Loading ..."); //$NON-NLS-1$
    loadingInfo.setVisible(false);
    add(loadingInfo);

    if (!useAJAX)
        bodyHeightHint = sizeHint;

    String orientation = OrientationApplier.getHTMLContainerOrientation(application.getLocale(),
            application.getSolution().getTextOrientation());
    isLeftToRightOrientation = !OrientationApplier.RTL.equalsIgnoreCase(orientation);

    int tFormHeight = 0;
    Iterator<Part> partIte = form.getParts();
    while (partIte.hasNext()) {
        Part p = partIte.next();
        if (p.getPartType() == Part.BODY) {
            tFormHeight = p.getHeight() - startY;
            break;
        }
    }
    formBodySize = new Dimension(form.getWidth(), tFormHeight);

    ChangesRecorder jsChangeRecorder = new ChangesRecorder(null, null) {
        @Override
        public boolean isChanged() {
            boolean retval = false;
            if (super.isChanged()) {
                retval = true;
                //TODO: change this; we should not do this, but it is not re-rendered otherwise
                return retval;
            }

            if (!retval) {
                Iterator<Component> iterator = elementToColumnIdentifierComponent.values().iterator();
                while (iterator.hasNext()) {
                    Component object = iterator.next();
                    if (object instanceof IProviderStylePropertyChanges) {
                        if (((IProviderStylePropertyChanges) object).getStylePropertyChanges().isChanged()) {
                            retval = true;
                            break;
                        }
                    }
                }
            }
            if (retval) {
                MainPage page = (MainPage) getPage();
                page.getPageContributor().addTableToRender(WebCellBasedView.this);
                setRendered();
            }
            return false;
        }

        @Override
        public void setRendered() {
            super.setRendered();
            Iterator<Component> iterator = elementToColumnIdentifierComponent.values().iterator();
            while (iterator.hasNext()) {
                Component comp = iterator.next();
                if (comp instanceof IProviderStylePropertyChanges) {
                    ((IProviderStylePropertyChanges) comp).getStylePropertyChanges().setRendered();
                }
            }
        }
    };
    this.scriptable = scriptable;
    ((ChangesRecorder) scriptable.getChangesRecorder()).setAdditionalChangesRecorder(jsChangeRecorder);

    add(TooltipAttributeModifier.INSTANCE);

    final int scrollbars = (cellview instanceof ISupportScrollbars)
            ? ((ISupportScrollbars) cellview).getScrollbars()
            : 0;
    add(new StyleAppendingModifier(new Model<String>() {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            if (!isScrollMode() && findParent(IWebFormContainer.class) != null) {
                return ""; //$NON-NLS-1$
            }
            return scrollBarDefinitionToOverflowAttribute(scrollbars, isScrollMode(), false,
                    currentData == null || currentData.getSize() == 0);
        }
    }));
    if (cellview instanceof BaseComponent) {
        ComponentFactory.applyBasicComponentProperties(application, this, (BaseComponent) cellview,
                ComponentFactory.getStyleForBasicComponent(application, cellview, form));
    }

    boolean sortable = true;
    String initialSortString = null;
    int onRenderMethodID = 0;
    AbstractBase onRenderPersist = null;
    if (cellview instanceof Portal) {
        Portal p = (Portal) cellview;
        isListViewMode = p.getMultiLine();

        setRowBGColorScript(p.getRowBGColorCalculation(),
                p.getInstanceMethodArguments("rowBGColorCalculation")); //$NON-NLS-1$
        sortable = p.getSortable();
        initialSortString = p.getInitialSort();
        onRenderMethodID = p.getOnRenderMethodID();
        onRenderPersist = p;

        int portalAnchors = p.getAnchors();
        isAnchored = (((portalAnchors & IAnchorConstants.NORTH) > 0)
                && ((portalAnchors & IAnchorConstants.SOUTH) > 0))
                || (((portalAnchors & IAnchorConstants.EAST) > 0)
                        && ((portalAnchors & IAnchorConstants.WEST) > 0));
    } else if (cellview instanceof Form) {
        initialSortString = form.getInitialSort();
        onRenderMethodID = form.getOnRenderMethodID();
        onRenderPersist = form;
        isAnchored = true;
    }

    if (onRenderMethodID > 0) {
        dataRendererOnRenderWrapper.getRenderEventExecutor().setRenderCallback(
                Integer.toString(onRenderMethodID),
                Utils.parseJSExpressions(onRenderPersist.getInstanceMethodArguments("onRenderMethodID")));
        dataRendererOnRenderWrapper.getRenderEventExecutor()
                .setRenderScriptExecuter(fc != null ? fc.getScriptExecuter() : null);
    }

    initDragNDrop(fc, startY);

    if (sortable) {
        if (initialSortString != null) {
            StringTokenizer tokByComma = new StringTokenizer(initialSortString, ","); //$NON-NLS-1$
            while (tokByComma.hasMoreTokens()) {
                String initialSortFirstToken = tokByComma.nextToken();
                StringTokenizer tokBySpace = new StringTokenizer(initialSortFirstToken);
                if (tokBySpace.hasMoreTokens()) {
                    String initialSortColumnName = tokBySpace.nextToken();

                    if (tokBySpace.hasMoreTokens()) {
                        String sortDir = tokBySpace.nextToken();
                        boolean initialSortAsc = true;
                        if (sortDir.equalsIgnoreCase("DESC")) //$NON-NLS-1$
                            initialSortAsc = false;
                        initialSortColumnNames.put(initialSortColumnName, new Boolean(initialSortAsc));
                    }
                }
            }
        }
        // If no initial sort was specified, then default will be the first PK column.
        if (initialSortColumnNames.size() == 0) {
            try {
                String dataSource = null;
                if (cellview instanceof Portal) {
                    Portal p = (Portal) cellview;
                    String relation = p.getRelationName();
                    int lastDot = relation.lastIndexOf("."); //$NON-NLS-1$
                    if (lastDot >= 0) {
                        relation = relation.substring(lastDot + 1);
                    }
                    Relation rel = application.getFlattenedSolution().getRelation(relation);
                    if (rel != null) {
                        dataSource = rel.getForeignDataSource();
                    }
                } else {
                    dataSource = form.getDataSource();
                }
                if (dataSource != null) {
                    Iterator<String> pkColumnNames = application.getFoundSetManager().getTable(dataSource)
                            .getRowIdentColumnNames();
                    while (pkColumnNames.hasNext()) {
                        initialSortColumnNames.put(pkColumnNames.next(), Boolean.TRUE);
                    }
                }
            } catch (RepositoryException e) {
                // We just don't set the initial sort to the PK.
                Debug.log("Failed to get PK columns for table.", e); //$NON-NLS-1$
            }
        }
    }

    maxHeight = 0;
    try {
        if (isListViewMode() && !(cellview instanceof Portal)) {
            int headerHeight = 0;
            int titleHeaderHeight = 0;
            Iterator<Part> pIte = form.getParts();
            while (pIte.hasNext()) {
                Part p = pIte.next();
                if (p.getPartType() == Part.BODY) {
                    maxHeight = p.getHeight();
                } else if (p.getPartType() == Part.HEADER) {
                    headerHeight = p.getHeight();
                } else if (p.getPartType() == Part.TITLE_HEADER) {
                    titleHeaderHeight = p.getHeight();
                }
            }
            if (headerHeight != 0) {
                maxHeight = maxHeight - headerHeight;
            } else {
                maxHeight = maxHeight - titleHeaderHeight;
            }
        } else {
            int minElY = 0;
            boolean isMinElYSet = false;
            int height;
            Iterator<IPersist> components = cellview.getAllObjects(PositionComparator.XY_PERSIST_COMPARATOR);
            while (components.hasNext()) {
                IPersist element = components.next();
                if (element instanceof Field || element instanceof GraphicalComponent) {
                    if (element instanceof GraphicalComponent
                            && ((GraphicalComponent) element).getLabelFor() != null) {
                        if (isInView(cellview, ((GraphicalComponent) element).getLabelFor())) {
                            labelsFor.put(((GraphicalComponent) element).getLabelFor(), element);
                        }
                        continue;
                    }
                    Point l = ((IFormElement) element).getLocation();
                    if (l == null) {
                        continue;// unknown where to add
                    }
                    if (l.y >= startY && l.y < endY) {

                        if (isListViewMode()) {
                            height = l.y + ((IFormElement) element).getSize().height;
                            if (!isMinElYSet || minElY > l.y) {
                                minElY = l.y;
                                isMinElYSet = true;
                            }
                        } else {
                            height = ((IFormElement) element).getSize().height;
                        }
                        if (height > maxHeight)
                            maxHeight = height;
                    }
                }
            }
            maxHeight = maxHeight - minElY;
        }
        if (maxHeight == 0)
            maxHeight = 20;
    } catch (Exception ex1) {
        Debug.error("Error getting max size out of components", ex1); //$NON-NLS-1$
    }

    // Add the table
    tableContainerBody = new WebMarkupContainer("rowsContainerBody"); //$NON-NLS-1$
    tableContainerBody.setOutputMarkupId(true);

    table = new WebCellBasedViewListView("rows", data, 1, cellview, //$NON-NLS-1$
            dataProviderLookup, el, startY, endY, form);
    table.setReuseItems(true);

    tableContainerBody.add(table);
    add(tableContainerBody);

    final LinkedHashMap<String, IDataAdapter> dataadapters = new LinkedHashMap<String, IDataAdapter>();
    final SortedList<IPersist> columnTabSequence = new SortedList<IPersist>(TabSeqComparator.INSTANCE); // in fact ISupportTabSeq persists
    createComponents(application, form, cellview, dataProviderLookup, el, startY, endY, new ItemAdd() {
        public void add(IPersist element, Component comp) {

            if (element instanceof IFormElement && comp instanceof IComponent) {
                ((IComponent) comp).setLocation(((IFormElement) element).getLocation());
                ((IComponent) comp).setSize(((IFormElement) element).getSize());
            }

            elementToColumnIdentifierComponent.put(element, comp);
            if (cellview instanceof Form && element instanceof ISupportTabSeq
                    && ((ISupportTabSeq) element).getTabSeq() >= 0) {
                columnTabSequence.add(element);
            }
            if (comp instanceof IDisplayData) {
                String dataprovider = ((IDisplayData) comp).getDataProviderID();

                WebCellAdapter previous = (WebCellAdapter) dataadapters.get(dataprovider);
                if (previous == null) {
                    WebCellAdapter wca = new WebCellAdapter(dataprovider, WebCellBasedView.this);
                    dataadapters.put(dataprovider, wca);
                }
                if (dataprovider != null) {
                    if (initialSortColumnNames.containsKey(dataprovider))
                        initialSortedColumns.put(comp.getId(), initialSortColumnNames.get(dataprovider));
                }
            }
        }
    });
    for (int i = columnTabSequence.size() - 1; i >= 0; i--) {
        elementTabIndexes.put(columnTabSequence.get(i), Integer.valueOf(i));
    }

    // Add the (sortable) header (and define how to sort the different columns)
    if (addHeaders) {
        // elementToColumnHeader will be filled up by SortableCellViewHeaders when components in it are resolved
        headers = new SortableCellViewHeaders(form, this, "header", table, cellview, application, //$NON-NLS-1$
                initialSortedColumns, new IHeaders() {

                    public void registerHeader(IPersist matchingElement, Component headerComponent) {
                        SortableCellViewHeader sortableHeader = (SortableCellViewHeader) headerComponent;
                        // set headerComponent width
                        Component columnIdentifier = WebCellBasedView.this.elementToColumnIdentifierComponent
                                .get(matchingElement);

                        if (columnIdentifier instanceof IProviderStylePropertyChanges) {
                            String width = ((IProviderStylePropertyChanges) columnIdentifier)
                                    .getStylePropertyChanges().getJSProperty("offsetWidth"); //$NON-NLS-1$
                            if (width != null) {
                                sortableHeader
                                        .setWidth(Integer.parseInt(width.substring(0, width.length() - 2)));
                            } else if (matchingElement instanceof BaseComponent)
                                sortableHeader.setWidth(((BaseComponent) matchingElement).getSize().width);
                        }
                        sortableHeader.setTabSequenceIndex(ISupportWebTabSeq.SKIP);
                        sortableHeader.setScriptExecuter(el);
                        sortableHeader.setResizeClass(columnIdentifier.getId());
                        WebCellBasedView.this.registerHeader(matchingElement, headerComponent);
                    }
                });
        add(headers);
    }

    // Add a table navigator
    if (useAJAX) {
        add(pagingNavigator = new ServoyAjaxPagingNavigator("navigator", table)); //$NON-NLS-1$
        add(tableResizeBehavior = new ServoyTableResizeBehavior(startY, endY, cellview));
        if (isScrollMode())
            add(new HeaderHeightCalculationBehavior());
    } else {
        add(pagingNavigator = new ServoySubmitPagingNavigator("navigator", table)); //$NON-NLS-1$
    }

    //hide all further records (and navigator) if explicitly told that there should be no vertical scrollbar
    showPageNavigator = !((scrollbars
            & ISupportScrollbars.VERTICAL_SCROLLBAR_NEVER) == ISupportScrollbars.VERTICAL_SCROLLBAR_NEVER);

    try {
        if (cellview instanceof Portal) {
            relationName = ((Portal) cellview).getRelationName();
            Relation[] rels = application.getFlattenedSolution()
                    .getRelationSequence(((Portal) cellview).getRelationName());

            if (rels != null) {
                Relation r = rels[rels.length - 1];
                if (r != null) {
                    defaultSort = ((FoundSetManager) application.getFoundSetManager()).getSortColumns(
                            application.getFoundSetManager().getTable(r.getForeignDataSource()),
                            ((Portal) cellview).getInitialSort());
                }
            }
        } else {
            defaultSort = ((FoundSetManager) application.getFoundSetManager())
                    .getSortColumns(((Form) cellview).getDataSource(), ((Form) cellview).getInitialSort());
        }
    } catch (RepositoryException e) {
        Debug.error(e);
        defaultSort = new ArrayList<SortColumn>(1);
    }

    try {
        dal = new DataAdapterList(application, dataProviderLookup, elementToColumnIdentifierComponent,
                el.getFormController(), dataadapters, null);
    } catch (RepositoryException ex) {
        Debug.error(ex);
    }

    table.setPageabeMode(!isScrollMode());
    if (isScrollMode()) {
        tableContainerBody.add(new StyleAppendingModifier(new Model<String>() {
            private static final long serialVersionUID = 1L;

            @Override
            public String getObject() {
                int scrollPadding = 0;
                //ClientInfo info = Session.get().getClientInfo();
                //if (info instanceof WebClientInfo && ((WebClientInfo)info).getProperties().isBrowserInternetExplorer()) scrollPadding = 0;
                //else scrollPadding = SCROLLBAR_SIZE;
                return scrollBarDefinitionToOverflowAttribute(scrollbars, isScrollMode(), true,
                        currentData == null || currentData.getSize() == 0)
                        + "position: absolute; left: 0px; right: 0px; bottom: 0px; border-spacing: 0px; -webkit-overflow-scrolling: touch; top:" //$NON-NLS-1$
                        + scrollableHeaderHeight + "px; padding-right:" + scrollPadding + "px;"; //$NON-NLS-1$ //$NON-NLS-2$
            }
        }));
        tableContainerBody.add(new SimpleAttributeModifier("class", "rowsContainerBody")); //$NON-NLS-1$ //$NON-NLS-2$
        tableContainerBody.add(scrollBehavior = new ScrollBehavior("onscroll")); //$NON-NLS-1$
        tableContainerBody.add(topPlaceholderUpdater = new TopPlaceholderUpdater());
    }

    add(new StyleAppendingModifier(new Model<String>() {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            WebForm container = findParent(WebForm.class);
            if (container != null && container.getBorder() instanceof TitledBorder) {
                int offset = ComponentFactoryHelper.getTitledBorderHeight(container.getBorder());
                return "top: " + offset + "px;"; //$NON-NLS-1$ //$NON-NLS-2$
            }
            return ""; //$NON-NLS-1$
        }
    }) {
        @Override
        public boolean isEnabled(Component component) {
            WebForm container = component.findParent(WebForm.class);
            if (container != null && container.getBorder() instanceof TitledBorder) {
                return super.isEnabled(component);
            }
            return false;
        }
    });
    if (!Boolean.FALSE.equals(application.getClientProperty(IApplication.TABLEVIEW_WC_USE_KEY_NAVIGATION))) {
        add(new ServoyAjaxEventBehavior("onkeydown", null, true) {
            @Override
            protected void onEvent(AjaxRequestTarget target) {
                int i = fc.getFormModel().getSelectedIndex();
                boolean downArrow = Utils
                        .getAsBoolean(RequestCycle.get().getRequest().getParameter("downArrow"));
                if (downArrow) {
                    i++;
                } else {
                    i--;
                }
                if (i >= 0) {
                    fc.getFormModel().setSelectedIndex(i);
                    WebEventExecutor.generateResponse(target, getPage());
                }
            }

            @Override
            protected CharSequence generateCallbackScript(final CharSequence partialCall) {
                return super.generateCallbackScript(partialCall + "+Servoy.Utils.getArrowParams()"); //$NON-NLS-1$
            }

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

                    @Override
                    public CharSequence decorateScript(CharSequence script) {
                        return "return Servoy.Utils.testArrowKey(event, function() {" + script + "},'" //$NON-NLS-1$//$NON-NLS-2$
                                + getMarkupId() + "');";
                    }
                };
            }

            @Override
            protected boolean blockRequest() {
                return false;
            }

        });
    }
    if (!isListViewMode()) {
        add(new ServoyAjaxEventBehavior("onclick", null, true) {
            @Override
            protected void onEvent(AjaxRequestTarget target) {
                if (application.getFoundSetManager().getEditRecordList().isEditing()) {
                    application.getFoundSetManager().getEditRecordList().stopEditing(false);
                    WebEventExecutor.generateResponse(target, getPage());
                }
            }

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

                    @Override
                    public CharSequence decorateScript(CharSequence script) {
                        return "if ((event.target || event.srcElement) == this){ " + script + " }"; //$NON-NLS-1$
                    }
                };
            }

        });
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebCellBasedView.java

License:Open Source License

private void addClassToCellComponent(final Component c) {
    Model<String> componentClassModel = new Model<String>() {
        @Override//w w w.jav a 2s.c o m
        public String getObject() {
            return c.getId();
        }
    };

    c.add(new AttributeModifier("class", true, componentClassModel) //$NON-NLS-1$
    {
        @Override
        protected String newValue(final String currentValue, String replacementValue) {
            String currentClass = currentValue == null ? "" : currentValue; //$NON-NLS-1$
            String replacementClass = ""; //$NON-NLS-1$
            if (replacementValue != null) {
                replacementClass = replacementValue;

                if (currentClass.equals(replacementClass))
                    return currentClass.trim();

                // check if already added
                int replacementClassIdx = currentClass.indexOf(replacementClass);

                if ((replacementClassIdx != -1)
                        && (replacementClassIdx == 0 || currentClass.charAt(replacementClassIdx - 1) == ' ')
                        && (replacementClassIdx == currentClass.length() - replacementClass.length()
                                || currentClass
                                        .charAt(replacementClassIdx + replacementClass.length()) == ' ')) {
                    return currentClass.trim();
                }
            }

            String result = replacementClass + " " + currentClass; //$NON-NLS-1$
            return result.trim();
        }
    });
}

From source file:com.servoy.j2db.server.headlessclient.WebForm.java

License:Open Source License

@SuppressWarnings("unchecked")
public FormAnchorInfo getFormAnchorInfo() {
    formAnchorInfo = new FormAnchorInfo(formController.getName(), formController.getForm().getSize(),
            formController.getForm().getUUID());

    final Map<String, ISupportAnchors> elements = new HashMap<String, ISupportAnchors>();
    Iterator<IPersist> e1 = formController.getForm().getAllObjects();
    while (e1.hasNext()) {
        IPersist obj = e1.next();/*  ww  w . j  av  a2s .  com*/
        if (obj instanceof ISupportAnchors && obj instanceof ISupportBounds) {
            elements.put(ComponentFactory.getWebID(formController.getForm(), obj), (ISupportAnchors) obj);
        }
    }

    // In case we are in table view.
    if (view instanceof WebCellBasedView) {
        WebCellBasedView formPart = (WebCellBasedView) view;
        formAnchorInfo.addPart(Part.getDisplayName(Part.BODY), formPart.getMarkupId(), 50);
        formAnchorInfo.isTableView = true;
        formAnchorInfo.bodyContainerId = formPart.getMarkupId();
    }

    // Find the id of the form navigator, if any.
    visitChildren(Component.class, new IVisitor() {
        public Object component(Component component) {
            if (component instanceof WebDefaultRecordNavigator) {
                formAnchorInfo.navigatorWebId = component.getMarkupId();
                return IVisitor.CONTINUE_TRAVERSAL;
            } else if (component instanceof WebTabPanel) {
                return IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
            } else
                return IVisitor.CONTINUE_TRAVERSAL;
        }
    });

    visitChildren(WebDataRenderer.class, new IVisitor() {
        public Object component(Component component) {
            WebDataRenderer formPart = (WebDataRenderer) component;

            final FormPartAnchorInfo part = formAnchorInfo.addPart(formPart.getFormPartName(),
                    formPart.getMarkupId(), formPart.getSize().height);

            if (Part.getDisplayName(Part.BODY).equals(formPart.getFormPartName())) {
                Component parent = formPart.getParent();
                formAnchorInfo.bodyContainerId = parent.getMarkupId();
            }
            formPart.visitChildren(ISupportWebBounds.class, new IVisitor() {
                public Object component(Component comp) {
                    String id = comp.getId();
                    ISupportAnchors obj = elements.get(id);
                    if (obj != null) {
                        int anchors = obj.getAnchors();
                        if (((anchors > 0 && anchors != IAnchorConstants.DEFAULT))
                                || (comp instanceof WebTabPanel) || (comp instanceof IButton)) {
                            Rectangle r = ((ISupportWebBounds) comp).getWebBounds();
                            if (r != null) {
                                if (anchors == 0)
                                    anchors = IAnchorConstants.DEFAULT;

                                int hAlign = -1;
                                int vAlign = -1;
                                if (obj instanceof ISupportTextSetup) {
                                    ISupportTextSetup alignedObj = (ISupportTextSetup) obj;
                                    hAlign = alignedObj.getHorizontalAlignment();
                                    vAlign = alignedObj.getVerticalAlignment();
                                }

                                String imageDisplayURL = null;
                                boolean isRandomParamRemoved = false;
                                if (comp instanceof IImageDisplay) {
                                    Object[] aImageDisplayURL = WebBaseButton
                                            .getImageDisplayURL((IImageDisplay) comp, false);
                                    imageDisplayURL = (String) aImageDisplayURL[0];
                                    isRandomParamRemoved = ((Boolean) aImageDisplayURL[1]).booleanValue();
                                }
                                part.addAnchoredElement(comp.getMarkupId(), anchors, r, hAlign, vAlign,
                                        comp.getClass(), imageDisplayURL, isRandomParamRemoved);
                            }

                        }
                    }
                    return IVisitor.CONTINUE_TRAVERSAL;
                }
            });
            return IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
        }
    });

    return formAnchorInfo;
}