Example usage for java.util EnumSet copyOf

List of usage examples for java.util EnumSet copyOf

Introduction

In this page you can find the example usage for java.util EnumSet copyOf.

Prototype

public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) 

Source Link

Document

Creates an enum set initialized from the specified collection.

Usage

From source file:org.xwiki.security.authorization.Right.java

@Override
public Set<EntityType> getTargetedEntityType() {
    List<EntityType> levels = new ArrayList<EntityType>();
    for (Map.Entry<EntityType, Set<Right>> entry : ENABLED_RIGHTS.entrySet()) {
        if (entry.getValue().contains(this)) {
            levels.add(entry.getKey());/*  w w  w .  ja  v  a2  s .co m*/
        }
    }
    if (levels.contains(null) && levels.contains(EntityType.WIKI)) {
        levels.remove(null);
    } else {
        return null;
    }
    return EnumSet.copyOf(levels);
}

From source file:com.hortonworks.streamline.streams.security.service.SecurityCatalogService.java

public boolean checkUserPermissions(String objectNamespace, Long objectId, Long userId,
        EnumSet<Permission> required) {
    User user = getUser(userId);/*from w  w  w  . j  av  a 2 s  .c  o  m*/
    if (user == null) {
        return false;
    }
    EnumSet<Permission> remaining = EnumSet.copyOf(required);
    // try direct user acl entry first
    List<QueryParam> qps = QueryParam.params(AclEntry.OBJECT_NAMESPACE, objectNamespace, AclEntry.OBJECT_ID,
            String.valueOf(objectId), AclEntry.SID_TYPE, USER.toString(), AclEntry.SID_ID,
            String.valueOf(userId));
    Collection<AclEntry> acls = listAcls(qps);
    if (acls.size() > 1) {
        throw new IllegalStateException("More than one ACL entry for " + qps);
    } else if (acls.size() == 1) {
        AclEntry aclEntry = acls.iterator().next();
        remaining.removeAll(aclEntry.getPermissions());
    }
    // try role based permissions next
    if (!remaining.isEmpty() && user.getRoles() != null) {
        qps = QueryParam.params(AclEntry.OBJECT_NAMESPACE, objectNamespace, AclEntry.OBJECT_ID,
                String.valueOf(objectId), AclEntry.SID_TYPE, AclEntry.SidType.ROLE.toString());
        acls = listAcls(qps);
        Set<Role> userRoles = getAllUserRoles(user);
        Iterator<AclEntry> it = acls.iterator();
        while (!remaining.isEmpty() && it.hasNext()) {
            AclEntry roleEntry = it.next();
            if (userRoles.contains(getRole(roleEntry.getSidId()))) {
                remaining.removeAll(roleEntry.getPermissions());
            }
        }
    }
    return remaining.isEmpty();
}

From source file:edu.wisc.ssec.mcidasv.data.hydra.Statistics.java

private static EnumSet<DescribeParams> parseParams(List<String> ps) {
    Set<DescribeParams> params = Collections.emptySet();
    if (ps != null) {
        params = new HashSet<>(ps.size());
        for (String p : ps) {
            params.add(DescribeParams.valueOf(p.toUpperCase()));
        }/* ww  w  .  j  ava 2  s .c  o  m*/
    }
    return EnumSet.copyOf(params);
}

From source file:forge.game.spellability.SpellAbility.java

public final void addOptionalCost(OptionalCost cost) {
    // Optional costs are added to swallow copies of original SAs,
    // Thus, to protect the original's set from changes, we make a copy right here.
    optionalCosts = EnumSet.copyOf(optionalCosts);
    optionalCosts.add(cost);/*from w  ww. ja v  a  2s  .  c  o m*/
}

From source file:org.photovault.imginfo.PhotoInfo.java

/**
 Find instance that is preferred for use in particular situation. This function 
 seeks for an image that has at least a given resolution, has certain
 operations already applied and is available.
 @param requiredOpers Set of operations that must be applied correctly 
 in the returned image (but not that the operations need not be applied if 
 this photo does not specify some operation. So even if this is non-empty
 it is possible that the method returns original image!
 @param allowedOpers Set of operations that may be applied to the returned
 image/* w  w w.  ja va  2 s .  c o m*/
 @param minWidth Minimum width of the returned image in pixels
 @param minHeight Minimum height of the returned image in pixels
 @param maxWidth Maximum width of the returned image in pixels
 @param maxHeight Maximum height of the returned image in pixels
 @return Image that best matches the given criteria or <code>null</code>
 if no suct image exists or is not available.
 */
public ImageDescriptorBase getPreferredImage(Set<ImageOperations> requiredOpers,
        Set<ImageOperations> allowedOpers, int minWidth, int minHeight, int maxWidth, int maxHeight) {
    ImageDescriptorBase preferred = null;
    EnumSet<ImageOperations> appliedPreferred = null;

    // We are not interested in operations that are not specified for this photo
    EnumSet<ImageOperations> specifiedOpers = getAppliedOperations();
    requiredOpers = EnumSet.copyOf(requiredOpers);
    requiredOpers.removeAll(EnumSet.complementOf(specifiedOpers));

    /*
     Would the original be OK?
     */
    if (requiredOpers.size() == 0 && original.getWidth() <= maxWidth && original.getHeight() <= maxHeight
            && original.getFile().findAvailableCopy() != null) {
        preferred = original;
        appliedPreferred = EnumSet.noneOf(ImageOperations.class);
    }

    // Calculate minimum & maimum scaling of resolution compared to original
    double minScale = ((double) minWidth) / ((double) original.getWidth());
    double maxScale = ((double) maxHeight) / ((double) original.getHeight());
    if (allowedOpers.contains(ImageOperations.CROP)) {
        Dimension croppedSize = getCroppedSize();
        double aspectRatio = croppedSize.getWidth() / croppedSize.getHeight();
        double miw = minWidth;
        double mih = minHeight;
        double maw = maxWidth;
        double mah = maxHeight;
        if (mih == 0.0 || (miw / mih) > aspectRatio) {
            mih = miw / aspectRatio;
        }
        if (mih > 0.0 && (miw / mih) < aspectRatio) {
            miw = mih * aspectRatio;
        }
        if (maw / mah > aspectRatio) {
            maw = mah * aspectRatio;
        }
        if (maw / mah < aspectRatio) {
            mah = maw / aspectRatio;
        }
        miw = Math.floor(miw);
        mih = Math.floor(mih);
        maw = Math.ceil(maw);
        mah = Math.ceil(mah);
        minScale = ((double) miw) / ((double) croppedSize.getWidth());
        maxScale = ((double) maw) / ((double) croppedSize.getWidth());
    }

    // Check the copies
    Set<CopyImageDescriptor> copies = original.getCopies();
    for (CopyImageDescriptor copy : copies) {
        double scale = ((double) copy.getWidth()) / ((double) original.getWidth());
        if (copy.getAppliedOperations().contains(ImageOperations.CROP)) {
            scale = ((double) copy.getWidth()) / ((double) getCroppedSize().getWidth());
        }
        if (scale >= minScale && scale <= maxScale && copy.getFile().findAvailableCopy() != null) {
            EnumSet<ImageOperations> applied = copy.getAppliedOperations();
            if (applied.containsAll(requiredOpers) && allowedOpers.containsAll(applied)
                    && isConsistentWithCurrentSettings(copy)) {

                // This is a potential one
                if (preferred == null || !appliedPreferred.containsAll(applied)) {
                    preferred = copy;
                    appliedPreferred = applied;
                }
            }
        }
    }
    return preferred;
}

From source file:org.syncope.console.pages.ConnectorModalPage.java

public ConnectorModalPage(final PageReference callerPageRef, final ModalWindow window,
        final ConnInstanceTO connectorTO) {

    super();/*w  w  w.  j av  a2 s. com*/

    selectedCapabilities = new ArrayList(connectorTO.getId() == 0 ? EnumSet.noneOf(ConnectorCapability.class)
            : connectorTO.getCapabilities());

    final IModel<List<ConnectorCapability>> capabilities = new LoadableDetachableModel<List<ConnectorCapability>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<ConnectorCapability> load() {
            return Arrays.asList(ConnectorCapability.values());
        }
    };

    final IModel<List<ConnBundleTO>> bundles = new LoadableDetachableModel<List<ConnBundleTO>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<ConnBundleTO> load() {
            return restClient.getAllBundles();
        }
    };

    bundleTO = getSelectedBundleTO(bundles.getObject(), connectorTO);
    properties = getProperties(bundleTO, connectorTO);

    final AjaxTextFieldPanel connectorName = new AjaxTextFieldPanel("connectorName", "connector name",
            new PropertyModel<String>(connectorTO, "connectorName"), false);

    connectorName.setOutputMarkupId(true);
    connectorName.setEnabled(false);

    final AjaxTextFieldPanel displayName = new AjaxTextFieldPanel("displayName", "display name",
            new PropertyModel<String>(connectorTO, "displayName"), false);

    displayName.setOutputMarkupId(true);
    displayName.addRequiredLabel();

    final AjaxTextFieldPanel version = new AjaxTextFieldPanel("version", "version",
            new PropertyModel<String>(connectorTO, "version"), false);

    displayName.setOutputMarkupId(true);
    version.setEnabled(false);

    final AjaxDropDownChoicePanel<ConnBundleTO> bundle = new AjaxDropDownChoicePanel<ConnBundleTO>("bundle",
            "bundle", new Model<ConnBundleTO>(bundleTO), false);

    bundle.setStyleShet("long_dynamicsize");

    bundle.setChoices(bundles.getObject());

    bundle.setChoiceRenderer(new ChoiceRenderer<ConnBundleTO>() {

        private static final long serialVersionUID = -1945543182376191187L;

        @Override
        public Object getDisplayValue(final ConnBundleTO object) {
            return object.getBundleName() + " " + object.getVersion();
        }

        @Override
        public String getIdValue(final ConnBundleTO object, final int index) {
            // idValue must include version as well in order to cope
            // with multiple version of the same bundle.
            return object.getBundleName() + "#" + object.getVersion();
        }
    });

    ((DropDownChoice) bundle.getField()).setNullValid(true);
    bundle.setRequired(true);

    bundle.getField().add(new AjaxFormComponentUpdatingBehavior("onchange") {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            //reset all informations stored in connectorTO
            connectorTO.setConfiguration(new HashSet<ConnConfProperty>());

            ((DropDownChoice) bundle.getField()).setNullValid(false);
            target.add(bundle.getField());

            target.add(connectorName);
            target.add(version);

            target.add(propertiesContainer);
        }
    });

    bundle.getField().setModel(new IModel<ConnBundleTO>() {

        private static final long serialVersionUID = -3736598995576061229L;

        @Override
        public ConnBundleTO getObject() {
            return bundleTO;
        }

        @Override
        public void setObject(final ConnBundleTO object) {
            if (object != null && connectorTO != null) {
                connectorTO.setBundleName(object.getBundleName());
                connectorTO.setVersion(object.getVersion());
                connectorTO.setConnectorName(object.getConnectorName());
                properties = getProperties(object, connectorTO);
                bundleTO = object;
            }
        }

        @Override
        public void detach() {
        }
    });

    bundle.addRequiredLabel();
    bundle.setEnabled(connectorTO.getId() == 0);

    final ListView<ConnConfProperty> view = new ListView<ConnConfProperty>("connectorProperties",
            new PropertyModel(this, "properties")) {

        private static final long serialVersionUID = 9101744072914090143L;

        @Override
        protected void populateItem(final ListItem<ConnConfProperty> item) {
            final ConnConfProperty property = item.getModelObject();

            final Label label = new Label("connPropAttrSchema",
                    property.getSchema().getDisplayName() == null
                            || property.getSchema().getDisplayName().isEmpty() ? property.getSchema().getName()
                                    : property.getSchema().getDisplayName());

            item.add(label);

            final FieldPanel field;

            boolean required = false;

            boolean isArray = false;

            if (GUARDED_STRING.equalsIgnoreCase(property.getSchema().getType())
                    || GUARDED_BYTE_ARRAY.equalsIgnoreCase(property.getSchema().getType())) {

                field = new AjaxPasswordFieldPanel("panel", label.getDefaultModelObjectAsString(), new Model(),
                        true);

                ((PasswordTextField) field.getField()).setResetPassword(false);

                required = property.getSchema().isRequired();

            } else {
                Class propertySchemaClass;

                try {
                    propertySchemaClass = ClassUtils.forName(property.getSchema().getType(),
                            ClassUtils.getDefaultClassLoader());
                } catch (Exception e) {
                    LOG.error("Error parsing attribute type", e);
                    propertySchemaClass = String.class;
                }

                if (NUMBER.contains(propertySchemaClass)) {
                    field = new AjaxNumberFieldPanel("panel", label.getDefaultModelObjectAsString(),
                            new Model(), ClassUtils.resolvePrimitiveIfNecessary(propertySchemaClass), true);

                    required = property.getSchema().isRequired();
                } else if (Boolean.class.equals(propertySchemaClass)
                        || boolean.class.equals(propertySchemaClass)) {
                    field = new AjaxCheckBoxPanel("panel", label.getDefaultModelObjectAsString(), new Model(),
                            true);
                } else {

                    field = new AjaxTextFieldPanel("panel", label.getDefaultModelObjectAsString(), new Model(),
                            true);

                    required = property.getSchema().isRequired();
                }

                if (String[].class.equals(propertySchemaClass)) {
                    isArray = true;
                }
            }

            field.setTitle(property.getSchema().getHelpMessage());

            if (isArray) {
                field.removeRequiredLabel();

                if (property.getValues().isEmpty()) {
                    property.getValues().add(null);
                }

                item.add(new MultiValueSelectorPanel<String>("panel",
                        new PropertyModel<List<String>>(property, "values"), String.class, field));
            } else {
                if (required) {
                    field.addRequiredLabel();
                }

                field.setNewModel(property.getValues());
                item.add(field);
            }

            final AjaxCheckBoxPanel overridable = new AjaxCheckBoxPanel("connPropAttrOverridable",
                    "connPropAttrOverridable", new PropertyModel(property, "overridable"), true);

            item.add(overridable);
            connectorTO.getConfiguration().add(property);
        }
    };

    final Form connectorForm = new Form("form");
    connectorForm.setModel(new CompoundPropertyModel(connectorTO));

    final Form connectorPropForm = new Form("connectorPropForm");
    connectorPropForm.setModel(new CompoundPropertyModel(connectorTO));
    connectorPropForm.setOutputMarkupId(true);

    propertiesContainer = new WebMarkupContainer("container");
    propertiesContainer.setOutputMarkupId(true);
    propertiesContainer.add(connectorPropForm);

    connectorForm.add(propertiesContainer);
    connectorPropForm.add(view);

    final AjaxLink check = new IndicatingAjaxLink("check", new ResourceModel("check")) {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {

            connectorTO.setBundleName(bundleTO.getBundleName());
            connectorTO.setVersion(bundleTO.getVersion());

            if (restClient.check(connectorTO).booleanValue()) {
                info(getString("success_connection"));
            } else {
                error(getString("error_connection"));
            }

            target.add(feedbackPanel);
        }
    };

    connectorPropForm.add(check);

    final AjaxButton submit = new IndicatingAjaxButton("apply", new Model(getString("submit"))) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form form) {

            final ConnInstanceTO conn = (ConnInstanceTO) form.getDefaultModelObject();

            conn.setBundleName(bundleTO.getBundleName());

            // Set the model object's capabilites to
            // capabilitiesPalette's converted Set
            if (!selectedCapabilities.isEmpty()) {
                // exception if selectedCapabilities is empy
                conn.setCapabilities(EnumSet.copyOf(selectedCapabilities));
            } else {
                conn.setCapabilities(EnumSet.noneOf(ConnectorCapability.class));
            }
            try {
                if (connectorTO.getId() == 0) {
                    restClient.create(conn);
                } else {
                    restClient.update(conn);
                }

                ((Resources) callerPageRef.getPage()).setModalResult(true);
                window.close(target);
            } catch (SyncopeClientCompositeErrorException e) {
                error(getString("error") + ":" + e.getMessage());
                target.add(feedbackPanel);
                ((Resources) callerPageRef.getPage()).setModalResult(false);
                LOG.error("While creating or updating connector {}", conn);
            }
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form form) {

            target.add(feedbackPanel);
        }
    };

    String roles = connectorTO.getId() == 0 ? xmlRolesReader.getAllAllowedRoles("Connectors", "create")
            : xmlRolesReader.getAllAllowedRoles("Connectors", "update");

    MetaDataRoleAuthorizationStrategy.authorize(submit, ENABLE, roles);

    connectorForm.add(connectorName);
    connectorForm.add(displayName);
    connectorForm.add(bundle);
    connectorForm.add(version);

    capabilitiesPalette = new CheckBoxMultipleChoice("capabilitiesPalette",
            new PropertyModel(this, "selectedCapabilities"), capabilities);
    connectorForm.add(capabilitiesPalette);

    connectorForm.add(submit);

    add(connectorForm);
}

From source file:io.pcp.parfait.dxm.PcpMmvWriter.java

public void setFlags(Set<MmvFlag> flags) {
    this.flags = EnumSet.copyOf(flags);
}

From source file:org.lockss.exporter.kbart.KbartExportFilter.java

/**
 * Get the set of fields from the filter's field ordering which were omitted 
 * due to being empty./*  w w w.  j a va 2 s.  c  om*/
 * @return the set of empty fields which were omitted from the ordering
 */
public Set<Field> getOmittedEmptyFields() {
    Set<Field> empties = EnumSet.copyOf(columnOrdering.getFields());
    empties.retainAll(emptyFields);
    return empties;
}

From source file:org.apache.syncope.client.console.pages.ConnectorModalPage.java

public ConnectorModalPage(final PageReference pageRef, final ModalWindow window,
        final ConnInstanceTO connInstanceTO) {

    super();/*  ww  w .j  ava2  s  . c  om*/

    this.add(new Label("new",
            connInstanceTO.getKey() == 0 ? new ResourceModel("new") : new Model<>(StringUtils.EMPTY)));
    this.add(new Label("key", connInstanceTO.getKey() == 0 ? StringUtils.EMPTY : connInstanceTO.getKey()));

    // general data setup
    selectedCapabilities = new ArrayList<>(
            connInstanceTO.getKey() == 0 ? EnumSet.noneOf(ConnectorCapability.class)
                    : connInstanceTO.getCapabilities());

    mapConnBundleTOs = new HashMap<>();
    for (ConnBundleTO connBundleTO : restClient.getAllBundles()) {
        // by location
        if (!mapConnBundleTOs.containsKey(connBundleTO.getLocation())) {
            mapConnBundleTOs.put(connBundleTO.getLocation(), new HashMap<String, Map<String, ConnBundleTO>>());
        }
        final Map<String, Map<String, ConnBundleTO>> byLocation = mapConnBundleTOs
                .get(connBundleTO.getLocation());

        // by name
        if (!byLocation.containsKey(connBundleTO.getBundleName())) {
            byLocation.put(connBundleTO.getBundleName(), new HashMap<String, ConnBundleTO>());
        }
        final Map<String, ConnBundleTO> byName = byLocation.get(connBundleTO.getBundleName());

        // by version
        if (!byName.containsKey(connBundleTO.getVersion())) {
            byName.put(connBundleTO.getVersion(), connBundleTO);
        }
    }

    bundleTO = getSelectedBundleTO(connInstanceTO);
    properties = fillProperties(bundleTO, connInstanceTO);

    // form - first tab
    final Form<ConnInstanceTO> connectorForm = new Form<>(FORM);
    connectorForm.setModel(new CompoundPropertyModel<>(connInstanceTO));
    connectorForm.setOutputMarkupId(true);
    add(connectorForm);

    propertiesContainer = new WebMarkupContainer("container");
    propertiesContainer.setOutputMarkupId(true);
    connectorForm.add(propertiesContainer);

    final Form<ConnInstanceTO> connectorPropForm = new Form<>("connectorPropForm");
    connectorPropForm.setModel(new CompoundPropertyModel<>(connInstanceTO));
    connectorPropForm.setOutputMarkupId(true);
    propertiesContainer.add(connectorPropForm);

    final AjaxTextFieldPanel displayName = new AjaxTextFieldPanel("displayName", "display name",
            new PropertyModel<String>(connInstanceTO, "displayName"));
    displayName.setOutputMarkupId(true);
    displayName.addRequiredLabel();
    connectorForm.add(displayName);

    final AjaxDropDownChoicePanel<String> location = new AjaxDropDownChoicePanel<>("location", "location",
            new Model<>(bundleTO == null ? null : bundleTO.getLocation()));
    ((DropDownChoice<String>) location.getField()).setNullValid(true);
    location.setStyleSheet("long_dynamicsize");
    location.setChoices(new ArrayList<>(mapConnBundleTOs.keySet()));
    location.setRequired(true);
    location.addRequiredLabel();
    location.setOutputMarkupId(true);
    location.setEnabled(connInstanceTO.getKey() == 0);
    location.getField().setOutputMarkupId(true);
    connectorForm.add(location);

    final AjaxDropDownChoicePanel<String> connectorName = new AjaxDropDownChoicePanel<>("connectorName",
            "connectorName", new Model<>(bundleTO == null ? null : bundleTO.getBundleName()));
    ((DropDownChoice<String>) connectorName.getField()).setNullValid(true);
    connectorName.setStyleSheet("long_dynamicsize");
    connectorName.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<>(mapConnBundleTOs.get(connInstanceTO.getLocation()).keySet()));
    connectorName.setRequired(true);
    connectorName.addRequiredLabel();
    connectorName.setEnabled(connInstanceTO.getLocation() != null);
    connectorName.setOutputMarkupId(true);
    connectorName.setEnabled(connInstanceTO.getKey() == 0);
    connectorName.getField().setOutputMarkupId(true);
    connectorForm.add(connectorName);

    final AjaxDropDownChoicePanel<String> version = new AjaxDropDownChoicePanel<>("version", "version",
            new Model<>(bundleTO == null ? null : bundleTO.getVersion()));
    version.setStyleSheet("long_dynamicsize");
    version.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<>(mapConnBundleTOs.get(connInstanceTO.getLocation())
                    .get(connInstanceTO.getBundleName()).keySet()));
    version.setRequired(true);
    version.addRequiredLabel();
    version.setEnabled(connInstanceTO.getBundleName() != null);
    version.setOutputMarkupId(true);
    version.addRequiredLabel();
    version.getField().setOutputMarkupId(true);
    connectorForm.add(version);

    final SpinnerFieldPanel<Integer> connRequestTimeout = new SpinnerFieldPanel<>("connRequestTimeout",
            "connRequestTimeout", Integer.class,
            new PropertyModel<Integer>(connInstanceTO, "connRequestTimeout"), 0, null);
    connRequestTimeout.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(connRequestTimeout);

    if (connInstanceTO.getPoolConf() == null) {
        connInstanceTO.setPoolConf(new ConnPoolConfTO());
    }
    final SpinnerFieldPanel<Integer> poolMaxObjects = new SpinnerFieldPanel<>("poolMaxObjects",
            "poolMaxObjects", Integer.class,
            new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxObjects"), 0, null);
    poolMaxObjects.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxObjects);
    final SpinnerFieldPanel<Integer> poolMinIdle = new SpinnerFieldPanel<>("poolMinIdle", "poolMinIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "minIdle"), 0, null);
    poolMinIdle.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMinIdle);
    final SpinnerFieldPanel<Integer> poolMaxIdle = new SpinnerFieldPanel<>("poolMaxIdle", "poolMaxIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxIdle"), 0, null);
    poolMaxIdle.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxIdle);
    final SpinnerFieldPanel<Long> poolMaxWait = new SpinnerFieldPanel<>("poolMaxWait", "poolMaxWait",
            Long.class, new PropertyModel<Long>(connInstanceTO.getPoolConf(), "maxWait"), 0L, null);
    poolMaxWait.getField().add(new RangeValidator<>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMaxWait);
    final SpinnerFieldPanel<Long> poolMinEvictableIdleTime = new SpinnerFieldPanel<>("poolMinEvictableIdleTime",
            "poolMinEvictableIdleTime", Long.class,
            new PropertyModel<Long>(connInstanceTO.getPoolConf(), "minEvictableIdleTimeMillis"), 0L, null);
    poolMinEvictableIdleTime.getField().add(new RangeValidator<>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMinEvictableIdleTime);

    // form - first tab - onchange()
    location.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            ((DropDownChoice<String>) location.getField()).setNullValid(false);
            connInstanceTO.setLocation(location.getModelObject());
            target.add(location);

            connectorName.setChoices(new ArrayList<>(mapConnBundleTOs.get(location.getModelObject()).keySet()));
            connectorName.setEnabled(true);
            connectorName.getField().setModelValue(null);
            target.add(connectorName);

            version.setChoices(new ArrayList<String>());
            version.getField().setModelValue(null);
            version.setEnabled(false);
            target.add(version);

            properties.clear();
            target.add(propertiesContainer);
        }
    });
    connectorName.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            ((DropDownChoice<String>) connectorName.getField()).setNullValid(false);
            connInstanceTO.setBundleName(connectorName.getModelObject());
            target.add(connectorName);

            List<String> versions = new ArrayList<>(mapConnBundleTOs.get(location.getModelObject())
                    .get(connectorName.getModelObject()).keySet());
            version.setChoices(versions);
            version.setEnabled(true);
            if (versions.size() == 1) {
                selectVersion(target, connInstanceTO, version, versions.get(0));
                version.getField().setModelObject(versions.get(0));
            } else {
                version.getField().setModelValue(null);
                properties.clear();
                target.add(propertiesContainer);
            }
            target.add(version);
        }
    });
    version.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            selectVersion(target, connInstanceTO, version, version.getModelObject());
        }
    });

    // form - second tab (properties)
    final ListView<ConnConfProperty> connPropView = new ConnConfPropertyListView("connectorProperties",
            new PropertyModel<List<ConnConfProperty>>(this, "properties"), true,
            connInstanceTO.getConfiguration());
    connPropView.setOutputMarkupId(true);
    connectorPropForm.add(connPropView);

    final AjaxButton check = new IndicatingAjaxButton("check", new ResourceModel("check")) {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ConnInstanceTO conn = (ConnInstanceTO) form.getModelObject();

            // ensure that connector bundle information is in sync
            conn.setBundleName(bundleTO.getBundleName());
            conn.setVersion(bundleTO.getVersion());
            conn.setConnectorName(bundleTO.getConnectorName());

            if (restClient.check(conn)) {
                info(getString("success_connection"));
            } else {
                error(getString("error_connection"));
            }

            feedbackPanel.refresh(target);
        }
    };
    connectorPropForm.add(check);

    // form - third tab (capabilities)
    final IModel<List<ConnectorCapability>> capabilities = new LoadableDetachableModel<List<ConnectorCapability>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<ConnectorCapability> load() {
            return Arrays.asList(ConnectorCapability.values());
        }
    };
    CheckBoxMultipleChoice<ConnectorCapability> capabilitiesPalette = new CheckBoxMultipleChoice<>(
            "capabilitiesPalette", new PropertyModel<List<ConnectorCapability>>(this, "selectedCapabilities"),
            capabilities);

    capabilitiesPalette.add(new AjaxFormChoiceComponentUpdatingBehavior() {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
        }
    });

    connectorForm.add(capabilitiesPalette);

    // form - submit / cancel buttons
    final AjaxButton submit = new IndicatingAjaxButton(APPLY, new Model<>(getString(SUBMIT))) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ConnInstanceTO conn = (ConnInstanceTO) form.getModelObject();

            conn.setConnectorName(bundleTO.getConnectorName());
            conn.setBundleName(bundleTO.getBundleName());
            conn.setVersion(bundleTO.getVersion());
            conn.getConfiguration().clear();
            conn.getConfiguration().addAll(connPropView.getModelObject());

            // Set the model object's capabilities to capabilitiesPalette's converted Set
            conn.getCapabilities().clear();
            conn.getCapabilities()
                    .addAll(selectedCapabilities.isEmpty() ? EnumSet.noneOf(ConnectorCapability.class)
                            : EnumSet.copyOf(selectedCapabilities));

            // Reset pool configuration if all fields are null
            if (conn.getPoolConf() != null && conn.getPoolConf().getMaxIdle() == null
                    && conn.getPoolConf().getMaxObjects() == null && conn.getPoolConf().getMaxWait() == null
                    && conn.getPoolConf().getMinEvictableIdleTimeMillis() == null
                    && conn.getPoolConf().getMinIdle() == null) {

                conn.setPoolConf(null);
            }

            try {
                if (connInstanceTO.getKey() == 0) {
                    restClient.create(conn);
                } else {
                    restClient.update(conn);
                }

                ((Resources) pageRef.getPage()).setModalResult(true);
                window.close(target);
            } catch (SyncopeClientException e) {
                error(getString(Constants.ERROR) + ": " + e.getMessage());
                feedbackPanel.refresh(target);
                ((Resources) pageRef.getPage()).setModalResult(false);
                LOG.error("While creating or updating connector {}", conn, e);
            }
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form<?> form) {
            feedbackPanel.refresh(target);
        }
    };
    String roles = connInstanceTO.getKey() == 0 ? xmlRolesReader.getEntitlement("Connectors", "create")
            : xmlRolesReader.getEntitlement("Connectors", "update");
    MetaDataRoleAuthorizationStrategy.authorize(submit, ENABLE, roles);
    connectorForm.add(submit);

    final IndicatingAjaxButton cancel = new IndicatingAjaxButton(CANCEL, new ResourceModel(CANCEL)) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            window.close(target);
        }
    };
    cancel.setDefaultFormProcessing(false);
    connectorForm.add(cancel);
}

From source file:org.apache.syncope.client.console.panels.ConnectorModal.java

public ConnectorModal(final ModalWindow window, final PageReference pageRef,
        final ConnInstanceTO connInstanceTO) {

    super(window, pageRef);

    this.add(new Label("new",
            connInstanceTO.getKey() == 0 ? new ResourceModel("new") : new Model<>(StringUtils.EMPTY)));
    this.add(new Label("key", connInstanceTO.getKey() == 0 ? StringUtils.EMPTY : connInstanceTO.getKey()));

    // general data setup
    selectedCapabilities = new ArrayList<>(
            connInstanceTO.getKey() == 0 ? EnumSet.noneOf(ConnectorCapability.class)
                    : connInstanceTO.getCapabilities());

    mapConnBundleTOs = new HashMap<>();
    for (ConnBundleTO connBundleTO : connectorRestClient.getAllBundles()) {
        // by location
        if (!mapConnBundleTOs.containsKey(connBundleTO.getLocation())) {
            mapConnBundleTOs.put(connBundleTO.getLocation(), new HashMap<String, Map<String, ConnBundleTO>>());
        }//from   w w  w  . j  a va2  s .  com
        final Map<String, Map<String, ConnBundleTO>> byLocation = mapConnBundleTOs
                .get(connBundleTO.getLocation());

        // by name
        if (!byLocation.containsKey(connBundleTO.getBundleName())) {
            byLocation.put(connBundleTO.getBundleName(), new HashMap<String, ConnBundleTO>());
        }
        final Map<String, ConnBundleTO> byName = byLocation.get(connBundleTO.getBundleName());

        // by version
        if (!byName.containsKey(connBundleTO.getVersion())) {
            byName.put(connBundleTO.getVersion(), connBundleTO);
        }
    }

    bundleTO = getSelectedBundleTO(connInstanceTO);
    properties = fillProperties(bundleTO, connInstanceTO);

    // form - first tab
    final Form<ConnInstanceTO> connectorForm = new Form<>(FORM);
    connectorForm.setModel(new CompoundPropertyModel<>(connInstanceTO));
    connectorForm.setOutputMarkupId(true);
    add(connectorForm);

    propertiesContainer = new WebMarkupContainer("container");
    propertiesContainer.setOutputMarkupId(true);
    connectorForm.add(propertiesContainer);

    final Form<ConnInstanceTO> connectorPropForm = new Form<>("connectorPropForm");
    connectorPropForm.setModel(new CompoundPropertyModel<>(connInstanceTO));
    connectorPropForm.setOutputMarkupId(true);
    propertiesContainer.add(connectorPropForm);

    final AjaxTextFieldPanel displayName = new AjaxTextFieldPanel("displayName", "display name",
            new PropertyModel<String>(connInstanceTO, "displayName"));
    displayName.setOutputMarkupId(true);
    displayName.addRequiredLabel();
    connectorForm.add(displayName);

    final AjaxDropDownChoicePanel<String> location = new AjaxDropDownChoicePanel<>("location", "location",
            new Model<>(bundleTO == null ? null : bundleTO.getLocation()));
    ((DropDownChoice<String>) location.getField()).setNullValid(true);
    location.setStyleSheet("long_dynamicsize");
    location.setChoices(new ArrayList<>(mapConnBundleTOs.keySet()));
    location.setRequired(true);
    location.addRequiredLabel();
    location.setOutputMarkupId(true);
    location.setEnabled(connInstanceTO.getKey() == 0);
    location.getField().setOutputMarkupId(true);
    connectorForm.add(location);

    final AjaxDropDownChoicePanel<String> connectorName = new AjaxDropDownChoicePanel<>("connectorName",
            "connectorName", new Model<>(bundleTO == null ? null : bundleTO.getBundleName()));
    ((DropDownChoice<String>) connectorName.getField()).setNullValid(true);
    connectorName.setStyleSheet("long_dynamicsize");
    connectorName.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<>(mapConnBundleTOs.get(connInstanceTO.getLocation()).keySet()));
    connectorName.setRequired(true);
    connectorName.addRequiredLabel();
    connectorName.setEnabled(connInstanceTO.getLocation() != null);
    connectorName.setOutputMarkupId(true);
    connectorName.setEnabled(connInstanceTO.getKey() == 0);
    connectorName.getField().setOutputMarkupId(true);
    connectorForm.add(connectorName);

    final AjaxDropDownChoicePanel<String> version = new AjaxDropDownChoicePanel<>("version", "version",
            new Model<>(bundleTO == null ? null : bundleTO.getVersion()));
    version.setStyleSheet("long_dynamicsize");
    version.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<>(mapConnBundleTOs.get(connInstanceTO.getLocation())
                    .get(connInstanceTO.getBundleName()).keySet()));
    version.setRequired(true);
    version.addRequiredLabel();
    version.setEnabled(connInstanceTO.getBundleName() != null);
    version.setOutputMarkupId(true);
    version.addRequiredLabel();
    version.getField().setOutputMarkupId(true);
    connectorForm.add(version);

    final SpinnerFieldPanel<Integer> connRequestTimeout = new SpinnerFieldPanel<>("connRequestTimeout",
            "connRequestTimeout", Integer.class,
            new PropertyModel<Integer>(connInstanceTO, "connRequestTimeout"), 0, null);
    connRequestTimeout.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(connRequestTimeout);

    if (connInstanceTO.getPoolConf() == null) {
        connInstanceTO.setPoolConf(new ConnPoolConfTO());
    }
    final SpinnerFieldPanel<Integer> poolMaxObjects = new SpinnerFieldPanel<>("poolMaxObjects",
            "poolMaxObjects", Integer.class,
            new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxObjects"), 0, null);
    poolMaxObjects.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxObjects);
    final SpinnerFieldPanel<Integer> poolMinIdle = new SpinnerFieldPanel<>("poolMinIdle", "poolMinIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "minIdle"), 0, null);
    poolMinIdle.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMinIdle);
    final SpinnerFieldPanel<Integer> poolMaxIdle = new SpinnerFieldPanel<>("poolMaxIdle", "poolMaxIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxIdle"), 0, null);
    poolMaxIdle.getField().add(new RangeValidator<>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxIdle);
    final SpinnerFieldPanel<Long> poolMaxWait = new SpinnerFieldPanel<>("poolMaxWait", "poolMaxWait",
            Long.class, new PropertyModel<Long>(connInstanceTO.getPoolConf(), "maxWait"), 0L, null);
    poolMaxWait.getField().add(new RangeValidator<>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMaxWait);
    final SpinnerFieldPanel<Long> poolMinEvictableIdleTime = new SpinnerFieldPanel<>("poolMinEvictableIdleTime",
            "poolMinEvictableIdleTime", Long.class,
            new PropertyModel<Long>(connInstanceTO.getPoolConf(), "minEvictableIdleTimeMillis"), 0L, null);
    poolMinEvictableIdleTime.getField().add(new RangeValidator<>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMinEvictableIdleTime);

    // form - first tab - onchange()
    location.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            ((DropDownChoice<String>) location.getField()).setNullValid(false);
            connInstanceTO.setLocation(location.getModelObject());
            target.add(location);

            connectorName.setChoices(new ArrayList<>(mapConnBundleTOs.get(location.getModelObject()).keySet()));
            connectorName.setEnabled(true);
            connectorName.getField().setModelValue(null);
            target.add(connectorName);

            version.setChoices(new ArrayList<String>());
            version.getField().setModelValue(null);
            version.setEnabled(false);
            target.add(version);

            properties.clear();
            target.add(propertiesContainer);
        }
    });
    connectorName.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            ((DropDownChoice<String>) connectorName.getField()).setNullValid(false);
            connInstanceTO.setBundleName(connectorName.getModelObject());
            target.add(connectorName);

            List<String> versions = new ArrayList<>(mapConnBundleTOs.get(location.getModelObject())
                    .get(connectorName.getModelObject()).keySet());
            version.setChoices(versions);
            version.setEnabled(true);
            if (versions.size() == 1) {
                selectVersion(target, connInstanceTO, version, versions.get(0));
                version.getField().setModelObject(versions.get(0));
            } else {
                version.getField().setModelValue(null);
                properties.clear();
                target.add(propertiesContainer);
            }
            target.add(version);
        }
    });
    version.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            selectVersion(target, connInstanceTO, version, version.getModelObject());
        }
    });

    // form - second tab (properties)
    final ListView<ConnConfProperty> connPropView = new ConnConfPropertyListView("connectorProperties",
            new PropertyModel<List<ConnConfProperty>>(this, "properties"), true,
            connInstanceTO.getConfiguration());
    connPropView.setOutputMarkupId(true);
    connectorPropForm.add(connPropView);

    final AjaxButton check = new IndicatingAjaxButton("check", new ResourceModel("check")) {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ConnInstanceTO conn = (ConnInstanceTO) form.getModelObject();

            // ensure that connector bundle information is in sync
            conn.setBundleName(bundleTO.getBundleName());
            conn.setVersion(bundleTO.getVersion());
            conn.setConnectorName(bundleTO.getConnectorName());

            if (connectorRestClient.check(conn)) {
                info(getString("success_connection"));
            } else {
                error(getString("error_connection"));
            }

            feedbackPanel.refresh(target);
        }
    };
    connectorPropForm.add(check);

    // form - third tab (capabilities)
    final IModel<List<ConnectorCapability>> capabilities = new LoadableDetachableModel<List<ConnectorCapability>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<ConnectorCapability> load() {
            return Arrays.asList(ConnectorCapability.values());
        }
    };
    CheckBoxMultipleChoice<ConnectorCapability> capabilitiesPalette = new CheckBoxMultipleChoice<>(
            "capabilitiesPalette", new PropertyModel<List<ConnectorCapability>>(this, "selectedCapabilities"),
            capabilities);

    capabilitiesPalette.add(new AjaxFormChoiceComponentUpdatingBehavior() {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
        }
    });

    connectorForm.add(capabilitiesPalette);

    // form - submit / cancel buttons
    final AjaxButton submit = new IndicatingAjaxButton(APPLY, new Model<>(getString(SUBMIT))) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            final ConnInstanceTO conn = (ConnInstanceTO) form.getModelObject();

            conn.setConnectorName(bundleTO.getConnectorName());
            conn.setBundleName(bundleTO.getBundleName());
            conn.setVersion(bundleTO.getVersion());
            conn.getConfiguration().clear();
            conn.getConfiguration().addAll(connPropView.getModelObject());

            // Set the model object's capabilities to capabilitiesPalette's converted Set
            conn.getCapabilities().clear();
            conn.getCapabilities()
                    .addAll(selectedCapabilities.isEmpty() ? EnumSet.noneOf(ConnectorCapability.class)
                            : EnumSet.copyOf(selectedCapabilities));

            // Reset pool configuration if all fields are null
            if (conn.getPoolConf() != null && conn.getPoolConf().getMaxIdle() == null
                    && conn.getPoolConf().getMaxObjects() == null && conn.getPoolConf().getMaxWait() == null
                    && conn.getPoolConf().getMinEvictableIdleTimeMillis() == null
                    && conn.getPoolConf().getMinIdle() == null) {

                conn.setPoolConf(null);
            }

            try {
                if (connInstanceTO.getKey() == 0) {
                    connectorRestClient.create(conn);
                } else {
                    connectorRestClient.update(conn);
                }

                ((BasePage) pageRef.getPage()).setModalResult(true);
                window.close(target);
            } catch (SyncopeClientException e) {
                error(getString(Constants.ERROR) + ": " + e.getMessage());
                feedbackPanel.refresh(target);
                ((BasePage) pageRef.getPage()).setModalResult(false);
                LOG.error("While creating or updating connector {}", conn, e);
            }
        }

        @Override
        protected void onError(final AjaxRequestTarget target, final Form<?> form) {
            feedbackPanel.refresh(target);
        }
    };
    String entitlements = connInstanceTO.getKey() == 0 ? Entitlement.CONNECTOR_CREATE
            : Entitlement.CONNECTOR_UPDATE;

    MetaDataRoleAuthorizationStrategy.authorize(submit, ENABLE, entitlements);
    connectorForm.add(submit);

    final IndicatingAjaxButton cancel = new IndicatingAjaxButton(CANCEL, new ResourceModel(CANCEL)) {

        private static final long serialVersionUID = -958724007591692537L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
            window.close(target);
        }
    };
    cancel.setDefaultFormProcessing(false);
    connectorForm.add(cancel);
}