Example usage for com.vaadin.data Validator Validator

List of usage examples for com.vaadin.data Validator Validator

Introduction

In this page you can find the example usage for com.vaadin.data Validator Validator.

Prototype

Validator

Source Link

Usage

From source file:org.apache.openaz.xacml.admin.view.windows.EditPDPWindow.java

License:Apache License

protected void initializeText() {
    ////from  w  w w  . ja  v a 2  s.c o m
    // Initialize values
    //
    if (this.pdp != null) {
        this.textId.setValue(this.pdp.getId());
        this.textName.setValue(this.pdp.getName());
        this.textDescription.setValue(this.pdp.getDescription());
    }
    //
    //
    //
    this.textId.setRequiredError("You must enter a valid id for the PDP.");
    this.textId.setNullRepresentation("");
    this.textId.addValidator(new RegexpValidator("[\\w=,]", false,
            "Please enter a valid URL with no whitespace or \"=\" or \",\" characters."));
    this.textId.addValidator(new Validator() {
        private static final long serialVersionUID = 1L;

        @Override
        public void validate(Object value) throws InvalidValueException {
            //
            // Cannot be null
            //
            if (value == null || value.toString().length() == 0) {
                throw new InvalidValueException("ID cannot be null.");
            }
            //
            // Make sure its a valid URL
            //
            try {
                new URL(value.toString());
            } catch (MalformedURLException e) {
                throw new InvalidValueException(
                        "The PDP URL '" + value.toString() + "' is not a valid URL: '" + e.getMessage() + "'");
            }
        }
    });
    //
    //
    //
    this.textName.setNullRepresentation("");
    this.textName.addValidator(new Validator() {
        private static final long serialVersionUID = 1L;

        @Override
        public void validate(Object value) throws InvalidValueException {
            //
            // If the value is null, set it to the id
            //
            if (value == null || value.toString().length() == 0) {
                return;
            }
        }
    });
    //
    //
    //
    this.textDescription.setNullRepresentation("");
}

From source file:org.apache.openaz.xacml.admin.view.windows.PolicyNameEditorWindow.java

License:Apache License

/**
 * The constructor should first build the main layout, set the
 * composition root and then do any custom initialization.
 *
 * The constructor will not be automatically regenerated by the
 * visual editor.//from  w w w  .j  a v a2 s . c o m
 */
public PolicyNameEditorWindow(String filename, Object policyData, JPAContainer<PolicyAlgorithms> policyAlgs,
        JPAContainer<RuleAlgorithms> ruleAlgs) {
    buildMainLayout();
    setContent(mainLayout);

    this.mainLayout.setMargin(true);

    this.filename = filename;
    this.data = policyData;
    this.policyAlgorithms = policyAlgs;
    this.ruleAlgorithms = ruleAlgs;

    this.optionPolicySet.addItem("Policy Set");
    this.optionPolicySet.addItem("Policy");

    this.comboAlgorithms.setNewItemsAllowed(false);
    this.comboAlgorithms.setNullSelectionAllowed(false);
    this.comboAlgorithms.setItemCaptionMode(ItemCaptionMode.PROPERTY);
    this.comboAlgorithms.setItemCaptionPropertyId("xacmlId");
    //
    // Setup the policy filename
    //
    this.textFieldPolicyName.setImmediate(true);
    this.textFieldPolicyName.setNullRepresentation("");
    if (filename != null) {
        this.textFieldPolicyName.setValue(filename);
    }
    this.textFieldPolicyName.addValidator(new Validator() {
        private static final long serialVersionUID = 1L;

        @Override
        public void validate(Object value) throws InvalidValueException {
            if (value instanceof String) {
                String filename = (String) value;
                if (filename.endsWith(".xml")) {
                    filename = filename.substring(0, filename.length() - 4);
                }
                if (filename.length() == 0) {
                    throw new InvalidValueException("Invalid filename.");
                }
                if (filename.indexOf('.') != -1) {
                    throw new InvalidValueException("Please do not use a \'.\' in the filename.");
                }
            }
        }

    });
    this.textFieldPolicyName.setValidationVisible(true);
    //
    // Are we editing or creating?
    //
    if (this.data != null) {
        //
        // We are editing
        //
        if (this.data instanceof PolicySetType) {
            this.optionPolicySet.setValue("Policy Set");
            this.optionPolicySet.setVisible(false);
            this.textAreaDescription.setValue(((PolicySetType) this.data).getDescription());
            this.comboAlgorithms.setContainerDataSource(policyAlgs);
            for (Object object : this.policyAlgorithms.getItemIds()) {
                PolicyAlgorithms a = (PolicyAlgorithms) this.policyAlgorithms.getItem(object).getEntity();
                if (a.getXacmlId().equals(((PolicySetType) this.data).getPolicyCombiningAlgId())) {
                    this.comboAlgorithms.select(object);
                    break;
                }
            }
        }
        if (this.data instanceof PolicyType) {
            this.optionPolicySet.setValue("Policy");
            this.optionPolicySet.setVisible(false);
            this.textAreaDescription.setValue(((PolicyType) this.data).getDescription());
            this.comboAlgorithms.setContainerDataSource(ruleAlgs);
            for (Object object : this.ruleAlgorithms.getItemIds()) {
                RuleAlgorithms a = (RuleAlgorithms) this.ruleAlgorithms.getItem(object).getEntity();
                if (a.getXacmlId().equals(((PolicyType) this.data).getRuleCombiningAlgId())) {
                    this.comboAlgorithms.select(object);
                    break;
                }
            }
        }
    } else {
        //
        // Creating a new policy
        //
        this.optionPolicySet.setValue("Policy Set");
        this.comboAlgorithms.setContainerDataSource(policyAlgs);
        this.comboAlgorithms.setItemCaptionMode(ItemCaptionMode.PROPERTY);
        this.comboAlgorithms.setItemCaptionPropertyId("xacmlId");
        for (Object object : this.policyAlgorithms.getItemIds()) {
            PolicyAlgorithms a = (PolicyAlgorithms) this.policyAlgorithms.getItem(object).getEntity();
            if (a.getXacmlId().equals(XACML3.ID_POLICY_FIRST_APPLICABLE.stringValue())) {
                this.comboAlgorithms.select(object);
                break;
            }
        }

        this.optionPolicySet.addValueChangeListener(new ValueChangeListener() {
            private static final long serialVersionUID = 1L;

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (self.optionPolicySet.getValue().toString().equals("Policy Set")) {
                    self.comboAlgorithms.setContainerDataSource(self.policyAlgorithms);
                    for (Object object : self.policyAlgorithms.getItemIds()) {
                        PolicyAlgorithms a = (PolicyAlgorithms) self.policyAlgorithms.getItem(object)
                                .getEntity();
                        if (a.getXacmlId().equals(XACML3.ID_POLICY_FIRST_APPLICABLE.stringValue())) {
                            self.comboAlgorithms.select(object);
                            break;
                        }
                    }
                } else if (self.optionPolicySet.getValue().toString().equals("Policy")) {
                    self.comboAlgorithms.setContainerDataSource(self.ruleAlgorithms);
                    for (Object object : self.ruleAlgorithms.getItemIds()) {
                        RuleAlgorithms a = (RuleAlgorithms) self.ruleAlgorithms.getItem(object).getEntity();
                        if (a.getXacmlId().equals(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue())) {
                            self.comboAlgorithms.select(object);
                            break;
                        }
                    }
                }
            }

        });
    }

    this.buttonSave.setClickShortcut(KeyCode.ENTER);

    this.buttonSave.addClickListener(new ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            //
            // Make sure the policy filename was valid
            //
            if (self.textFieldPolicyName.isValid() == false) {
                return;
            }
            //
            // Grab the filename (NOTE: The user may or may not
            // have changed the name).
            //
            self.filename = self.textFieldPolicyName.getValue();
            //
            // Make sure the filename ends with an extension
            //
            if (self.filename.endsWith(".xml") == false) {
                self.filename = self.filename + ".xml";
            }
            //
            // Set ourselves as saved
            //
            self.isSaved = true;
            //
            // Now grab the policy file's data
            //
            if (self.data == null) {
                //
                // This is a brand new Policy
                //
                if (self.optionPolicySet.getValue().toString().equals("Policy Set")) {
                    PolicySetType policySet = new PolicySetType();
                    policySet.setVersion("1");
                    policySet.setPolicySetId(((XacmlAdminUI) getUI()).newPolicyID());
                    policySet.setTarget(new TargetType());
                    self.data = policySet;
                } else if (self.optionPolicySet.getValue().toString().equals("Policy")) {
                    PolicyType policy = new PolicyType();
                    policy.setVersion("1");
                    policy.setPolicyId(((XacmlAdminUI) getUI()).newPolicyID());
                    policy.setTarget(new TargetType());
                    self.data = policy;
                } else {
                    logger.error("Policy option NOT setup correctly.");
                }
            }
            if (self.data != null) {
                //
                // Save off everything
                //
                if (self.data instanceof PolicySetType) {
                    ((PolicySetType) self.data).setDescription(self.textAreaDescription.getValue());
                    Object a = self.comboAlgorithms.getValue();
                    PolicyAlgorithms alg = (PolicyAlgorithms) ((JPAContainerItem<?>) self.comboAlgorithms
                            .getItem(a)).getEntity();
                    ((PolicySetType) self.data).setPolicyCombiningAlgId(alg.getXacmlId());
                } else if (self.data instanceof PolicyType) {
                    ((PolicyType) self.data).setDescription(self.textAreaDescription.getValue());
                    Object a = self.comboAlgorithms.getValue();
                    RuleAlgorithms alg = (RuleAlgorithms) ((JPAContainerItem<?>) self.comboAlgorithms
                            .getItem(a)).getEntity();
                    ((PolicyType) self.data).setRuleCombiningAlgId(alg.getXacmlId());
                } else {
                    logger.error("Unsupported data object." + self.data.getClass().getCanonicalName());
                }
            }
            //
            // Now we can close the window
            //
            self.close();
        }
    });

    this.textFieldPolicyName.focus();
}

From source file:org.groom.review.ui.flows.LogFlowlet.java

License:Apache License

@Override
public void initialize() {
    entityManager = getSite().getSiteContext().getObject(EntityManager.class);

    final GridLayout gridLayout = new GridLayout(1, 3);
    gridLayout.setSizeFull();/*from  w  ww.  j  av  a 2s .c om*/
    gridLayout.setMargin(false);
    gridLayout.setSpacing(true);
    gridLayout.setRowExpandRatio(2, 1f);
    setViewContent(gridLayout);

    final HorizontalLayout filterLayout = new HorizontalLayout();
    filterLayout.setSpacing(true);
    filterLayout.setSizeUndefined();
    gridLayout.addComponent(filterLayout, 0, 0);

    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.setSizeUndefined();
    gridLayout.addComponent(buttonLayout, 0, 1);

    final Validator validator = new Validator() {
        @Override
        public void validate(Object o) throws InvalidValueException {
            final String value = (String) o;
            if (value.indexOf("..") != -1) {
                throw new InvalidValueException("..");
            }
            for (int i = 0; i < value.length(); i++) {
                final char c = value.charAt(i);
                if (!(Character.isLetter(c) || Character.isDigit(c) || "-./".indexOf(c) != -1)) {
                    throw new InvalidValueException("" + c);
                }
            }
        }
    };

    repositoryField = new ComboBox(getSite().localize("field-repository"));
    repositoryField.setNullSelectionAllowed(false);
    repositoryField.setTextInputAllowed(true);
    repositoryField.setNewItemsAllowed(false);
    repositoryField.setInvalidAllowed(false);
    final List<Repository> repositories = ReviewDao.getRepositories(entityManager,
            (Company) getSite().getSiteContext().getObject(Company.class));

    for (final Repository repository : repositories) {
        repositoryField.addItem(repository);
        repositoryField.setItemCaption(repository, repository.getPath());
        if (repositoryField.getItemIds().size() == 1) {
            repositoryField.setValue(repository);
        }
    }
    filterLayout.addComponent(repositoryField);

    sinceField = new TextField(getSite().localize("field-since"));
    sinceField.setValue("master");
    sinceField.setValidationVisible(true);
    sinceField.addValidator(validator);
    filterLayout.addComponent(sinceField);

    untilField = new TextField(getSite().localize("field-until"));
    untilField.setValidationVisible(true);
    untilField.addValidator(validator);
    filterLayout.addComponent(untilField);

    final BeanQueryFactory<CommitBeanQuery> beanQueryFactory = new BeanQueryFactory<CommitBeanQuery>(
            CommitBeanQuery.class);
    queryConfiguration = new HashMap<String, Object>();
    beanQueryFactory.setQueryConfiguration(queryConfiguration);

    final LazyQueryContainer container = new LazyQueryContainer(beanQueryFactory, "hash", 200, false);

    container.addContainerFilter(new Compare.Equal("branch", sinceField.getValue()));
    container.addContainerProperty("hash", String.class, null, true, false);
    container.addContainerProperty("committerDate", Date.class, null, true, false);
    container.addContainerProperty("committer", String.class, null, true, false);
    container.addContainerProperty("authorDate", Date.class, null, true, false);
    container.addContainerProperty("author", String.class, null, true, false);
    container.addContainerProperty("tags", String.class, null, true, false);
    container.addContainerProperty("subject", String.class, null, true, false);

    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    final Table table = new Table() {

        @Override
        protected String formatPropertyValue(Object rowId, Object colId, Property property) {
            Object v = property.getValue();
            if (v instanceof Date) {
                Date dateValue = (Date) v;
                return format.format(v);
            }
            return super.formatPropertyValue(rowId, colId, property);
        }

    };

    table.setWidth(100, Unit.PERCENTAGE);
    table.setHeight(UI.getCurrent().getPage().getBrowserWindowHeight() - 350, Unit.PIXELS);
    table.setContainerDataSource(container);
    table.setVisibleColumns(
            new Object[] { "hash", "committerDate", "committer", "authorDate", "author", "tags", "subject" });

    table.setColumnWidth("hash", 50);
    table.setColumnWidth("committerDate", 120);
    table.setColumnWidth("committer", 100);
    table.setColumnWidth("authorDate", 120);
    table.setColumnWidth("author", 100);
    table.setColumnWidth("tags", 100);

    table.setColumnHeaders(new String[] { getSite().localize("field-hash"),
            getSite().localize("field-committer-date"), getSite().localize("field-committer"),
            getSite().localize("field-author-date"), getSite().localize("field-author"),
            getSite().localize("field-tags"), getSite().localize("field-subject") });

    table.setColumnCollapsingAllowed(true);
    table.setColumnCollapsed("authorDate", true);
    table.setColumnCollapsed("author", true);
    table.setSelectable(true);
    table.setMultiSelect(true);
    table.setImmediate(true);

    gridLayout.addComponent(table, 0, 2);

    final Button refreshButton = new Button(getSite().localize("button-refresh"));
    buttonLayout.addComponent(refreshButton);
    refreshButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
    refreshButton.addStyleName("default");
    refreshButton.addClickListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            repository = (Repository) repositoryField.getValue();

            if (repository != null && sinceField.isValid() && untilField.isValid()) {
                queryConfiguration.put("repository", repository);
                final StringBuilder range = new StringBuilder(sinceField.getValue());
                if (untilField.getValue().length() > 0) {
                    range.append("..");
                    range.append(untilField);
                }
                container.removeAllContainerFilters();
                container.addContainerFilter(new Compare.Equal("range", range.toString()));
                container.refresh();
            }
        }
    });

    final Button fetchButton = new Button("Fetch");
    buttonLayout.addComponent(fetchButton);
    fetchButton.addClickListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            final Repository repository = (Repository) repositoryField.getValue();
            Notification.show("Executed fetch. " + Shell.execute("git fetch", repository.getPath()));
            refreshButton.click();
        }
    });

    final Button addReviewButton = getSite().getButton("add-review");
    addReviewButton.setEnabled(false);
    buttonLayout.addComponent(addReviewButton);
    addReviewButton.addClickListener(new ClickListener() {
        /** Serial version UID. */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            final Object[] selection = ((Set) table.getValue()).toArray();
            if (selection != null && selection.length == 2) {
                final String hashOne = (String) selection[0];
                final String hashTwo = (String) selection[1];
                final Commit commitOne = ((NestingBeanItem<Commit>) container.getItem(hashOne)).getBean();
                final Commit commitTwo = ((NestingBeanItem<Commit>) container.getItem(hashTwo)).getBean();

                final Commit sinceCommit;
                final Commit untilCommit;
                if (commitOne.getCommitterDate().getTime() > commitTwo.getCommitterDate().getTime()) {
                    sinceCommit = commitTwo;
                    untilCommit = commitOne;
                } else {
                    sinceCommit = commitOne;
                    untilCommit = commitTwo;
                }
                createReview(sinceCommit.getHash(), untilCommit.getHash());
            } else {
                final ReviewRangeDialog dialog = new ReviewRangeDialog(new ReviewRangeDialog.DialogListener() {
                    @Override
                    public void onOk(String sinceHash, String untilHash) {
                        if (sinceHash.length() > 0 && untilHash.length() > 0) {
                            createReview(sinceHash, untilHash);
                        }
                    }

                    @Override
                    public void onCancel() {
                    }
                }, ((selection != null && selection.length == 1) ? "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
                        : ""), ((selection != null && selection.length == 1) ? (String) selection[0] : ""));
                dialog.setCaption("Please enter final comment.");
                UI.getCurrent().addWindow(dialog);
                dialog.getSinceField().focus();
            }

        }
    });

    table.addValueChangeListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            final Set selection = (Set) table.getValue();
            addReviewButton.setEnabled(selection != null && (selection.size() == 1 || selection.size() == 2));
        }
    });

}

From source file:org.opencms.ui.dialogs.availability.CmsAvailabilityDialog.java

License:Open Source License

/**
 * Creates a new instance.<p>/*from   ww  w.  ja  va  2s.  c  o m*/
 *
 * @param dialogContext the dialog context
 */
public CmsAvailabilityDialog(I_CmsDialogContext dialogContext) {

    super();
    m_dialogContext = dialogContext;
    CmsObject cms = dialogContext.getCms();
    CmsVaadinUtils.readAndLocalizeDesign(this,
            OpenCms.getWorkplaceManager().getMessages(A_CmsUI.get().getLocale()), null);
    List<CmsResource> resources = dialogContext.getResources();
    m_notificationIntervalField.addValidator(new Validator() {

        /** Serial version id. */
        private static final long serialVersionUID = 1L;

        public void validate(Object value) throws InvalidValueException {

            String strValue = ((String) value).trim();
            if (!strValue.matches("[0-9]*")) {
                throw new InvalidValueException(
                        CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_VALIDATOR_EMPTY_OR_NUMBER_0));

            }

        }
    });

    boolean hasSiblings = false;
    for (CmsResource resource : m_dialogContext.getResources()) {
        hasSiblings |= resource.getSiblingCount() > 1;
        if (hasSiblings) {
            break;
        }
    }
    m_modifySiblingsField.setVisible(hasSiblings);

    if (resources.size() == 1) {
        CmsResource onlyResource = resources.get(0);
        if (onlyResource.getDateReleased() != CmsResource.DATE_RELEASED_DEFAULT) {
            m_releasedField.setValue(new Date(onlyResource.getDateReleased()));
        }
        if (onlyResource.getDateExpired() != CmsResource.DATE_EXPIRED_DEFAULT) {
            m_expiredField.setValue(new Date(onlyResource.getDateExpired()));
        }
        initNotification();
        Map<CmsPrincipalBean, String> responsibles = m_availabilityInfo.getResponsibles();
        if (!responsibles.isEmpty()) {
            m_responsiblesPanel.setVisible(true);
            m_notificationPanel.setVisible(true);
            for (Map.Entry<CmsPrincipalBean, String> entry : responsibles.entrySet()) {
                CmsPrincipalBean principal = entry.getKey();
                String icon = principal.isGroup() ? CmsWorkplace.getResourceUri("buttons/group.png")
                        : CmsWorkplace.getResourceUri("buttons/user.png");
                String subtitle = "";
                if (entry.getValue() != null) {
                    subtitle = cms.getRequestContext().removeSiteRoot(entry.getValue());
                }
                CmsResourceInfo infoWidget = new CmsResourceInfo(entry.getKey().getName(), subtitle, icon);
                m_responsiblesContainer.addComponent(infoWidget);

            }
        }
    } else {
        boolean showNotification = false;
        resourceLoop: for (CmsResource resource : resources) {
            try {
                List<CmsAccessControlEntry> aces = cms.getAccessControlEntries(cms.getSitePath(resource));
                for (CmsAccessControlEntry ace : aces) {
                    if (ace.isResponsible()) {
                        showNotification = true;
                        break resourceLoop;
                    }
                }
            } catch (CmsException e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
        m_notificationPanel.setVisible(showNotification);
    }
    m_notificationEnabledField.setValue(m_initialNotificationEnabled);
    m_notificationIntervalField.setValue(m_initialNotificationInterval);
    boolean hasFolders = false;
    for (CmsResource resource : resources) {
        if (resource.isFolder()) {
            hasFolders = true;
        }
    }
    m_subresourceModificationField.setVisible(hasFolders);
    initResetCheckbox(m_resetReleased, m_releasedField);
    initResetCheckbox(m_resetExpired, m_expiredField);
    m_okButton.addClickListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {

            submit();
        }

    });

    m_cancelButton.addClickListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {

            cancel();
        }
    });
    displayResourceInfo(m_dialogContext.getResources());

    setActionHandler(new CmsOkCancelActionHandler() {

        private static final long serialVersionUID = 1L;

        @Override
        protected void cancel() {

            CmsAvailabilityDialog.this.cancel();
        }

        @Override
        protected void ok() {

            submit();
        }
    });
}

From source file:org.opennms.features.topology.app.internal.operations.AddVertexToGroupOperation.java

License:Open Source License

@Override
public void execute(List<VertexRef> targets, final OperationContext operationContext) {
    if (targets == null || targets.isEmpty()) {
        return;/*from  w  w  w. j a  va2 s  .c o  m*/
    }

    final Logger log = LoggerFactory.getLogger(this.getClass());
    final GraphContainer graphContainer = operationContext.getGraphContainer();

    final Collection<VertexRef> vertices = removeChildren(operationContext.getGraphContainer(),
            determineTargets(targets.get(0), operationContext.getGraphContainer().getSelectionManager()));
    final Collection<Vertex> vertexIds = graphContainer.getBaseTopology().getRootGroup();
    final Collection<Vertex> groupIds = findGroups(graphContainer.getBaseTopology(), vertexIds);

    final UI window = operationContext.getMainWindow();

    final Window groupNamePrompt = new GroupWindow("Add This Item To a Group", "300px", "210px");

    // Define the fields for the form
    final PropertysetItem item = new PropertysetItem();
    item.addItemProperty("Group", new ObjectProperty<String>(null, String.class));

    // field factory for the form
    FormFieldFactory fieldFactory = new FormFieldFactory() {
        private static final long serialVersionUID = 2963683658636386720L;

        public Field<?> createField(Item item, Object propertyId, Component uiContext) {
            // Identify the fields by their Property ID.
            String pid = (String) propertyId;
            if ("Group".equals(pid)) {
                final ComboBox select = new ComboBox("Group");
                for (Vertex childId : groupIds) {
                    log.debug("Adding child: {}, {}", childId.getId(), childId.getLabel());
                    select.addItem(childId.getId());
                    select.setItemCaption(childId.getId(), childId.getLabel());
                }
                select.setNewItemsAllowed(false);
                select.setNullSelectionAllowed(false);
                select.setRequired(true);
                select.setRequiredError("You must select a group");
                select.addValidator(new Validator() {
                    private static final long serialVersionUID = -2466240291882827117L;

                    @Override
                    public void validate(Object value) throws InvalidValueException {
                        if (isValid(value))
                            return;
                        throw new InvalidValueException(String.format("You cannot add group '%s' to itself.",
                                select.getItemCaption(value)));
                    };

                    /**
                     * Ensures that if only one element is selected that this element cannot be added to itself.
                     * If there are more than one elements selected, we assume as valid. 
                     */
                    private boolean isValid(Object value) {
                        if (vertices.size() > 1)
                            return true; // more than 1 -> assume valid
                        final String groupId = (String) select.getValue();
                        // only one, check if we want to assign to ourself
                        for (VertexRef eachVertex : vertices) {
                            if (groupId.equals(eachVertex.getId())) {
                                return false;
                            }
                        }
                        return true;
                    }
                });
                return select;
            }
            return null; // Invalid field (property) name.
        }
    };

    // create the form
    final Form promptForm = new Form() {
        private static final long serialVersionUID = 8310646938173207767L;

        @Override
        public void commit() throws SourceException, InvalidValueException {
            super.commit();
            String groupId = (String) getField("Group").getValue();
            Vertex group = graphContainer.getBaseTopology()
                    .getVertex(graphContainer.getBaseTopology().getVertexNamespace(), groupId);
            log.debug("Field value: {}", group.getId());
            for (VertexRef eachChild : vertices) {
                if (eachChild == group) {
                    log.warn("Ignoring group:(id={},label={}), because otherwise we should add it to itself.",
                            eachChild.getId(), eachChild.getLabel());
                    continue;
                }
                log.debug("Adding item:(id={},label={}) to group:(id={},label={})", eachChild.getId(),
                        eachChild.getLabel(), group.getId(), group.getLabel());
                graphContainer.getBaseTopology().setParent(eachChild, group);
            }
            graphContainer.getBaseTopology().save();
            graphContainer.redoLayout();
        }
    };
    // Buffer changes to the datasource
    promptForm.setBuffered(true);
    // You must set the FormFieldFactory before you set the data source
    promptForm.setFormFieldFactory(fieldFactory);
    promptForm.setItemDataSource(item);
    promptForm.setDescription("Please select a group.");

    // Footer
    Button ok = new Button("OK");
    ok.addClickListener(new ClickListener() {

        private static final long serialVersionUID = 7388841001913090428L;

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                promptForm.validate();
                promptForm.commit();
                window.removeWindow(groupNamePrompt); // Close the prompt window
            } catch (InvalidValueException exception) {
                promptForm.setComponentError(
                        new UserError(exception.getMessage(), ContentMode.TEXT, ErrorLevel.WARNING));
            }
        }
    });

    Button cancel = new Button("Cancel");
    cancel.addClickListener(new ClickListener() {

        private static final long serialVersionUID = 8780989646038333243L;

        @Override
        public void buttonClick(ClickEvent event) {
            window.removeWindow(groupNamePrompt); // Close the prompt window
        }
    });

    promptForm.setFooter(new HorizontalLayout());
    promptForm.getFooter().addComponent(ok);
    promptForm.getFooter().addComponent(cancel);

    groupNamePrompt.setContent(promptForm);

    window.addWindow(groupNamePrompt);
}

From source file:org.sensorhub.ui.HttpServerConfigForm.java

License:Mozilla Public License

@Override
protected Field<?> buildAndBindField(String label, String propId, Property<?> prop) {
    Field<?> field = super.buildAndBindField(label, propId, prop);

    if (propId.equals(PROP_SERVLET_ROOT)) {
        field.addValidator(new StringLengthValidator(MSG_REQUIRED_FIELD, 2, 256, false));
    } else if (propId.equals(PROP_HTTP_PORT)) {
        field.setWidth(100, Unit.PIXELS);
        //((TextField)field).getConverter().
        field.addValidator(new Validator() {
            private static final long serialVersionUID = 1L;

            public void validate(Object value) throws InvalidValueException {
                int portNum = (Integer) value;
                if (portNum > 10000 || portNum <= 80)
                    throw new InvalidValueException(
                            "Port number must be an integer number greater than 80 and lower than 10000");
            }//from  w  w w . j  a v  a2 s  .  c o m
        });
    }

    return field;
}

From source file:ru.codeinside.adm.ui.ButtonCreateGroup.java

License:Mozilla Public License

private void showButtonCreateGroup() {

    removeAllComponents();/*from   w w  w .j a va 2 s . co  m*/

    final Button buttonCreateGroup = new Button(" ", new Button.ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            removeAllComponents();
            final Form groupForm = new Form();
            groupForm.addField(NAME, new TextField(NAME));
            groupForm.getField(NAME).setRequired(true);
            groupForm.getField(NAME).setRequiredError("  ");
            groupForm.getField(NAME)
                    .addValidator(new StringLengthValidator(
                            "      255 ?", 1,
                            255, false));
            groupForm.getField(NAME).addValidator(new Validator() {

                private static final long serialVersionUID = 1L;

                public void validate(Object value) throws InvalidValueException {
                    if (!isValid(value)) {
                        if (value != null && value.toString().matches("[0-9].{0,}")) {
                            throw new InvalidValueException(
                                    "   ?? ? ? ");
                        } else {
                            throw new InvalidValueException(
                                    "   ???  ?   ");
                        }
                    }
                }

                public boolean isValid(Object value) {
                    if (value == null || !(value instanceof String)) {
                        return false;
                    }

                    return ((String) value).matches("[aA-zZ][aA0-zZ9]{0,}");
                }
            });

            groupForm.addField(TITLE, new TextField(TITLE));
            groupForm.getField(TITLE).setRequired(true);
            groupForm.getField(TITLE).setRequiredError("  ");
            groupForm.getField(TITLE).addValidator(new StringLengthValidator(
                    "?      255 ?",
                    1, 255, false));
            groupForm.getField(TITLE).addValidator(new Validator() {

                private static final long serialVersionUID = 1L;

                public void validate(Object value) throws InvalidValueException {
                    if (!isValid(value)) {
                        throw new InvalidValueException(
                                "?    ???  ");
                    }
                }

                public boolean isValid(Object value) {
                    if (value == null || !(value instanceof String)) {
                        return false;
                    }
                    return (!((String) value).replace(" ", "").isEmpty());
                }
            });
            addComponent(groupForm);

            final Button apply = new Button("", new Button.ClickListener() {

                private static final long serialVersionUID = 1L;

                public void buttonClick(ClickEvent event) {
                    try {
                        groupForm.commit();
                        String name = groupForm.getField(NAME).getValue().toString();
                        String title = groupForm.getField(TITLE).getValue().toString();

                        Boolean social = (typeGroup == GroupTab.EMPLOYEE);
                        boolean gropIsExist = AdminServiceProvider.get().createGroup(name, title, social);
                        if (gropIsExist) {
                            tableGroup.addItem(name, title);
                            tableGroup.setValue(name);
                            getWindow().showNotification(" " + name + " ?");
                        } else {
                            getWindow().showNotification(
                                    " " + name + "  ??",
                                    Notification.TYPE_WARNING_MESSAGE);
                        }
                        showButtonCreateGroup();
                    } catch (Exception e) {

                    }
                }
            });

            final Button cancel = new Button("", new Button.ClickListener() {

                private static final long serialVersionUID = 1L;

                public void buttonClick(ClickEvent event) {
                    showButtonCreateGroup();
                }
            });

            HorizontalLayout buttons = new HorizontalLayout();
            buttons.setSpacing(true);
            buttons.addComponent(apply);
            buttons.addComponent(cancel);
            groupForm.getFooter().addComponent(buttons);
        }

    });
    addComponent(buttonCreateGroup);
}

From source file:ru.codeinside.adm.ui.LogSettings.java

License:Mozilla Public License

LogSettings() {

    logErrors = new OptionGroup("? ? :", Arrays.asList(Status.FAILURE.name()));
    logErrors.setItemCaption(Status.FAILURE.name(), "");
    logErrors.setImmediate(true);//from  www  .  j  a v a 2  s. co  m
    logErrors.setMultiSelect(true);

    logStatus = new OptionGroup("?  ?  '':", statusKeys());
    logStatus.setItemCaption(Status.REQUEST.name(), "?");
    logStatus.setItemCaption(Status.RESULT.name(), "");
    logStatus.setItemCaption(Status.PING.name(), "?");
    logStatus.setMultiSelect(true);
    logStatus.setImmediate(true);

    ipSet = new TextArea("? IP ?:");
    ipSet.setWordwrap(true);
    ipSet.setNullRepresentation("");
    ipSet.setWidth(100f, UNITS_PERCENTAGE);
    ipSet.setRows(10);

    tf = new TextField(" , :");
    tf.setRequired(true);
    tf.addValidator(new Validator() {
        public void validate(Object value) throws InvalidValueException {
            if (!isValid(value)) {
                throw new InvalidValueException(
                        "  ? ");
            }
        }

        public boolean isValid(Object value) {
            return value instanceof String && ((String) value).matches("[1-9][0-9]*");
        }
    });

    b1 = new Block("") {

        @Override
        void onLayout(Layout layout) {
            layout.addComponent(logErrors);
            layout.addComponent(logStatus);
        }

        @Override
        void onChange() {
            logErrors.setReadOnly(false);
            logStatus.setReadOnly(false);
        }

        @Override
        void onRefresh() {
            boolean _logErrors = AdminServiceProvider.getBoolProperty(API.LOG_ERRORS);
            if (_logErrors) {
                logErrors.setReadOnly(false);
                logErrors.setValue(Arrays.asList(Status.FAILURE.name()));
            } else {
                logErrors.setValue(Collections.emptySet());
            }
            logErrors.setReadOnly(true);

            String _logStatus = AdminServiceProvider.get().getSystemProperty(API.LOG_STATUS);
            if (_logStatus != null) {
                Set<String> set = new HashSet<String>();
                for (String key : statusKeys()) {
                    if (_logStatus.contains(key)) {
                        set.add(key);
                    }
                }
                logStatus.setReadOnly(false);
                logStatus.setValue(set);
            } else {
                logStatus.setValue(Collections.emptySet());
            }
            logStatus.setReadOnly(true);
        }

        @Override
        void onApply() {
            Collection logErrorsValue = (Collection) logErrors.getValue();
            boolean errorsEnabled = logErrorsValue.contains(Status.FAILURE.name());
            AdminServiceProvider.get().saveSystemProperty(API.LOG_ERRORS, Boolean.toString(errorsEnabled));
            LogCustomizer.setShouldWriteServerLogErrors(errorsEnabled);

            Collection logStatusValue = (Collection) logStatus.getValue();

            Set<Status> statuses = new TreeSet<Status>();

            if (logStatusValue.contains(Status.REQUEST.name())) {
                statuses.add(Status.REQUEST);
                statuses.add(Status.ACCEPT);
                statuses.add(Status.CANCEL);
            }

            if (logStatusValue.contains(Status.RESULT.name())) {
                statuses.add(Status.RESULT);
                statuses.add(Status.REJECT);
                statuses.add(Status.STATE);
                statuses.add(Status.NOTIFY);
            }

            if (logStatusValue.contains(Status.PING.name())) {
                statuses.add(Status.PING);
                statuses.add(Status.PROCESS);
                statuses.add(Status.PACKET);
            }

            StringBuilder statusBuilder = new StringBuilder();
            for (Status status : statuses) {
                if (statusBuilder.length() > 0) {
                    statusBuilder.append(", ");
                }
                statusBuilder.append(status);
            }
            String status = statusBuilder.toString();

            AdminServiceProvider.get().saveSystemProperty(API.LOG_STATUS, status);
            LogCustomizer.setServerLogStatus(status);

            boolean enabled = !status.isEmpty();
            LogCustomizer.setShouldWriteServerLog(enabled);
            AdminServiceProvider.get().saveSystemProperty(API.ENABLE_CLIENT_LOG, Boolean.toString(enabled));
        }
    };

    b2 = new Block("? ") {
        @Override
        void onLayout(Layout layout) {
            layout.addComponent(ipSet);
        }

        @Override
        void onRefresh() {
            String ips = AdminServiceProvider.get().getSystemProperty(API.SKIP_LOG_IPS);
            ipSet.setReadOnly(false);
            ipSet.setValue(ips);
            ipSet.setReadOnly(true);
        }

        @Override
        void onChange() {
            ipSet.setReadOnly(false);
        }

        @Override
        void onApply() {
            String value = (String) ipSet.getValue();
            TreeSet<String> items = new TreeSet<String>();
            if (value != null) {
                for (String item : value.split("[,;\\s]+")) {
                    items.add(item);
                }
                StringBuilder sb = new StringBuilder();
                for (String item : items) {
                    if (sb.length() > 0) {
                        sb.append(", ");
                    }
                    sb.append(item);
                }
                value = sb.toString();
            }
            AdminServiceProvider.get().saveSystemProperty(API.SKIP_LOG_IPS, value);
            LogCustomizer.setIgnoreSet(items);
        }
    };

    b3 = new Block("?   ") {
        @Override
        void onButtons(Layout layout) {
            layout.addComponent(new Button("? ", new Button.ClickListener() {
                @Override
                public void buttonClick(Button.ClickEvent event) {
                    LogScheduler.cleanLog();
                    getWindow().showNotification("?? ",
                            Window.Notification.TYPE_HUMANIZED_MESSAGE);
                }
            }));
        }

        @Override
        void onLayout(Layout layout) {
            layout.addComponent(tf);
        }

        @Override
        void onRefresh() {
            String logDepth = AdminServiceProvider.get().getSystemProperty(API.LOG_DEPTH);
            tf.setReadOnly(false);
            if (logDepth != null && logDepth.matches("[1-9][0-9]*")) {
                tf.setValue(logDepth);
            } else {
                tf.setValue(String.valueOf(API.DEFAULT_LOG_DEPTH));
            }
            tf.setReadOnly(true);
        }

        @Override
        void onChange() {
            tf.setReadOnly(false);
        }

        @Override
        void onApply() {
            tf.validate();
            AdminServiceProvider.get().saveSystemProperty(API.LOG_DEPTH, tf.getValue().toString());
        }
    };

    final CheckBox logSpSign = new CheckBox(" ? ");
    logSpSign.setValue(Boolean.valueOf(AdminServiceProvider.get().getSystemProperty(API.LOG_SP_SIGN)));
    logSpSign.addListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            AdminServiceProvider.get().saveSystemProperty(API.LOG_SP_SIGN,
                    String.valueOf(valueChangeEvent.getProperty().getValue()));
            notifySuccess();
        }
    });
    logSpSign.setImmediate(true);

    final CheckBox logOvSign = new CheckBox(" ? ");
    logOvSign.setValue(Boolean.valueOf(AdminServiceProvider.get().getSystemProperty(API.LOG_OV_SIGN)));
    logOvSign.addListener(new Property.ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent valueChangeEvent) {
            AdminServiceProvider.get().saveSystemProperty(API.LOG_OV_SIGN,
                    String.valueOf(valueChangeEvent.getProperty().getValue()));
            notifySuccess();
        }
    });
    logOvSign.setImmediate(true);

    Label userSignsLabel = new Label("? ?");
    userSignsLabel.addStyleName(Reindeer.LABEL_H2);

    VerticalLayout userSignsVl = new VerticalLayout();
    userSignsVl.setMargin(true);
    userSignsVl.setSpacing(true);
    userSignsVl.addComponent(userSignsLabel);
    userSignsVl.addComponent(logSpSign);
    userSignsVl.addComponent(logOvSign);

    Panel userSingsWrapper = new Panel();
    userSingsWrapper.setScrollable(true);
    userSingsWrapper.setContent(userSignsVl);
    userSingsWrapper.setSizeFull();

    VerticalLayout vl = new VerticalLayout();
    vl.addComponent(b1);
    vl.addComponent(userSingsWrapper);
    vl.setExpandRatio(b1, 0.7f);
    vl.setExpandRatio(userSingsWrapper, 0.3f);
    vl.setSizeFull();

    HorizontalLayout layout = new HorizontalLayout();
    layout.setSpacing(true);
    layout.addComponent(vl);
    layout.addComponent(b2);
    layout.addComponent(b3);
    layout.setSizeFull();
    layout.setExpandRatio(vl, 0.333f);
    layout.setExpandRatio(b2, 0.333f);
    layout.setExpandRatio(b3, 0.333f);

    Panel wrapper = new Panel(" ", layout);
    wrapper.addStyleName(Reindeer.PANEL_LIGHT);
    wrapper.setSizeFull();

    setCompositionRoot(wrapper);
    setSizeFull();
}

From source file:songstock.web.extensions.payments.creditcard.CreditCardForm.java

License:Open Source License

/**
 * The constructor should first build the main layout, set the composition
 * root and then do any custom initialization.
 * //from   ww  w.  jav a 2s .  c  o m
 * The constructor will not be automatically regenerated by the visual
 * editor.
 */
public CreditCardForm() {
    buildMainLayout();
    setCompositionRoot(mainLayout);

    // User code
    this.labelError.setValue("");
    this.labelError.setEnabled(false);

    comboBoxCardBrand.setRequiredError("Select the card's brand.");
    // Set card brands
    setCardBrands();

    textFieldCardNumber.setRequiredError("Type the card's number.");
    textFieldCardNumber.addValidator(new Validator() {

        @Override
        public void validate(Object value) throws InvalidValueException {
            if (textFieldCardNumber.getValue().length() != 16)
                throw new InvalidValueException("The credit card number must have 16 characters");
        }
    });
    textFieldCardholder.setRequiredError("Type the cardholder's name.");

    comboBoxExpirationDateMonth.setRequiredError("Select the card's expiration month.");
    // Set months
    setExpirationMonths();
    comboBoxExpirationDateMonth.addValidator(new Validator() {

        @Override
        public void validate(Object value) throws InvalidValueException {
            Calendar cal = GregorianCalendar.getInstance();
            cal.setTime(new Date());
            int currentYear = cal.get(Calendar.YEAR);
            int currentMonth = cal.get(Calendar.MONTH) + 1;
            if (comboBoxExpirationDateMonth.getValue() != null && comboBoxExpirationDateYear.getValue() != null
                    && Integer.parseInt(comboBoxExpirationDateYear.getValue().toString()) == currentYear
                    && Integer.parseInt(comboBoxExpirationDateMonth.getValue().toString()) < currentMonth)
                throw new InvalidValueException("The credit card expired!");
        }
    });

    comboBoxExpirationDateYear.setRequiredError("Select the card's expiration year.");
    // Set years
    setExpirationYears();
    comboBoxExpirationDateYear.addValidator(new Validator() {

        @Override
        public void validate(Object value) throws InvalidValueException {
            Calendar cal = GregorianCalendar.getInstance();
            cal.setTime(new Date());
            int currentYear = cal.get(Calendar.YEAR);
            int currentMonth = cal.get(Calendar.MONTH) + 1;
            if (comboBoxExpirationDateMonth.getValue() != null && comboBoxExpirationDateYear.getValue() != null
                    && Integer.parseInt(comboBoxExpirationDateMonth.getValue().toString()) == currentMonth
                    && Integer.parseInt(comboBoxExpirationDateYear.getValue().toString()) < currentYear)
                throw new InvalidValueException("The credit card expired!");
        }
    });

    textFieldCardVerificationCode.setRequiredError("Type the card's verification code.");
    textFieldCardVerificationCode.addValidator(new Validator() {

        @Override
        public void validate(Object value) throws InvalidValueException {
            if (!textFieldCardVerificationCode.getValue().matches("[0-9]+"))
                throw new InvalidValueException("The verification code must contain numbers only");
        }
    });
    textFieldBillingAddress.setRequiredError("Type the billing address.");
    textFieldZipCode.setRequiredError("Type the billing address's zip code.");
    textFieldCity.setRequiredError("Type the billing address's city.");
    textFieldState.setRequiredError("Type the billing address's state.");

    comboBoxCountry.setRequiredError("Select the billing address's country.");
    // Set countries
    setCountries();

    textFieldPhoneNumber.setRequiredError("Type the billing address's phone number.");
    textFieldPhoneNumber.addValidator(new Validator() {

        @Override
        public void validate(Object value) throws InvalidValueException {
            if (!textFieldPhoneNumber.getValue().matches("[0-9]+"))
                throw new InvalidValueException("The phone number must contain numbers only");
        }
    });

    this.buttonPay.addClickListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            doPay();
        }
    });
}