Example usage for java.util EnumSet noneOf

List of usage examples for java.util EnumSet noneOf

Introduction

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

Prototype

public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) 

Source Link

Document

Creates an empty enum set with the specified element type.

Usage

From source file:com.couchbase.lite.AttachmentsTest.java

@SuppressWarnings("unchecked")
public void testAttachments() throws Exception {

    String testAttachmentName = "test_attachment";

    BlobStore attachments = database.getAttachments();

    Assert.assertEquals(0, attachments.count());
    Assert.assertEquals(new HashSet<Object>(), attachments.allKeys());

    Status status = new Status();
    Map<String, Object> rev1Properties = new HashMap<String, Object>();
    rev1Properties.put("foo", 1);
    rev1Properties.put("bar", false);
    RevisionInternal rev1 = database.putRevision(new RevisionInternal(rev1Properties, database), null, false,
            status);/*  w w w.  j  a  v a 2s  .c  om*/

    Assert.assertEquals(Status.CREATED, status.getCode());

    byte[] attach1 = "This is the body of attach1".getBytes();
    database.insertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach1), rev1.getSequence(),
            testAttachmentName, "text/plain", rev1.getGeneration());
    Assert.assertEquals(Status.CREATED, status.getCode());

    //We must set the no_attachments column for the rev to false, as we are using an internal
    //private API call above (database.insertAttachmentForSequenceWithNameAndType) which does
    //not set the no_attachments column on revs table
    try {
        ContentValues args = new ContentValues();
        args.put("no_attachments=", false);
        database.getDatabase().update("revs", args, "sequence=?",
                new String[] { String.valueOf(rev1.getSequence()) });
    } catch (SQLException e) {
        Log.e(Database.TAG, "Error setting rev1 no_attachments to false", e);
        throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
    }

    Attachment attachment = database.getAttachmentForSequence(rev1.getSequence(), testAttachmentName);
    Assert.assertEquals("text/plain", attachment.getContentType());
    InputStream is = attachment.getContent();
    byte[] data = IOUtils.toByteArray(is);
    is.close();
    Assert.assertTrue(Arrays.equals(attach1, data));

    Map<String, Object> innerDict = new HashMap<String, Object>();
    innerDict.put("content_type", "text/plain");
    innerDict.put("digest", "sha1-gOHUOBmIMoDCrMuGyaLWzf1hQTE=");
    innerDict.put("length", 27);
    innerDict.put("stub", true);
    innerDict.put("revpos", 1);
    Map<String, Object> attachmentDict = new HashMap<String, Object>();
    attachmentDict.put(testAttachmentName, innerDict);

    Map<String, Object> attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(
            rev1.getSequence(), EnumSet.noneOf(Database.TDContentOptions.class));
    Assert.assertEquals(attachmentDict, attachmentDictForSequence);

    RevisionInternal gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(),
            EnumSet.noneOf(Database.TDContentOptions.class));
    Map<String, Object> gotAttachmentDict = (Map<String, Object>) gotRev1.getProperties().get("_attachments");
    Assert.assertEquals(attachmentDict, gotAttachmentDict);

    // Check the attachment dict, with attachments included:
    innerDict.remove("stub");
    innerDict.put("data", Base64.encodeBytes(attach1));
    attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(rev1.getSequence(),
            EnumSet.of(Database.TDContentOptions.TDIncludeAttachments));
    Assert.assertEquals(attachmentDict, attachmentDictForSequence);

    gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(),
            EnumSet.of(Database.TDContentOptions.TDIncludeAttachments));
    gotAttachmentDict = (Map<String, Object>) gotRev1.getProperties().get("_attachments");
    Assert.assertEquals(attachmentDict, gotAttachmentDict);

    // Add a second revision that doesn't update the attachment:
    Map<String, Object> rev2Properties = new HashMap<String, Object>();
    rev2Properties.put("_id", rev1.getDocId());
    rev2Properties.put("foo", 2);
    rev2Properties.put("bazz", false);
    RevisionInternal rev2 = database.putRevision(new RevisionInternal(rev2Properties, database),
            rev1.getRevId(), false, status);
    Assert.assertEquals(Status.CREATED, status.getCode());

    database.copyAttachmentNamedFromSequenceToSequence(testAttachmentName, rev1.getSequence(),
            rev2.getSequence());

    // Add a third revision of the same document:
    Map<String, Object> rev3Properties = new HashMap<String, Object>();
    rev3Properties.put("_id", rev2.getDocId());
    rev3Properties.put("foo", 2);
    rev3Properties.put("bazz", false);
    RevisionInternal rev3 = database.putRevision(new RevisionInternal(rev3Properties, database),
            rev2.getRevId(), false, status);
    Assert.assertEquals(Status.CREATED, status.getCode());

    byte[] attach2 = "<html>And this is attach2</html>".getBytes();
    database.insertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach2), rev3.getSequence(),
            testAttachmentName, "text/html", rev2.getGeneration());

    // Check the 2nd revision's attachment:
    Attachment attachment2 = database.getAttachmentForSequence(rev2.getSequence(), testAttachmentName);

    Assert.assertEquals("text/plain", attachment2.getContentType());
    InputStream is2 = attachment2.getContent();
    data = IOUtils.toByteArray(is2);
    is2.close();
    Assert.assertTrue(Arrays.equals(attach1, data));

    // Check the 3rd revision's attachment:
    Attachment attachment3 = database.getAttachmentForSequence(rev3.getSequence(), testAttachmentName);
    Assert.assertEquals("text/html", attachment3.getContentType());
    InputStream is3 = attachment3.getContent();
    data = IOUtils.toByteArray(is3);
    is3.close();
    Assert.assertTrue(Arrays.equals(attach2, data));

    Map<String, Object> attachmentDictForRev3 = (Map<String, Object>) database
            .getAttachmentsDictForSequenceWithContent(rev3.getSequence(),
                    EnumSet.noneOf(Database.TDContentOptions.class))
            .get(testAttachmentName);
    if (attachmentDictForRev3.containsKey("follows")) {
        if (((Boolean) attachmentDictForRev3.get("follows")).booleanValue() == true) {
            throw new RuntimeException("Did not expected attachment dict 'follows' key to be true");
        } else {
            throw new RuntimeException("Did not expected attachment dict to have 'follows' key");
        }
    }

    // Examine the attachment store:
    Assert.assertEquals(2, attachments.count());
    Set<BlobKey> expected = new HashSet<BlobKey>();
    expected.add(BlobStore.keyForBlob(attach1));
    expected.add(BlobStore.keyForBlob(attach2));

    Assert.assertEquals(expected, attachments.allKeys());

    database.compact(); // This clears the body of the first revision
    Assert.assertEquals(1, attachments.count());

    Set<BlobKey> expected2 = new HashSet<BlobKey>();
    expected2.add(BlobStore.keyForBlob(attach2));
    Assert.assertEquals(expected2, attachments.allKeys());
}

From source file:org.apache.accumulo.core.util.shell.commands.FateCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
        throws ParseException, KeeperException, InterruptedException, IOException {
    Instance instance = shellState.getInstance();
    String[] args = cl.getArgs();
    if (args.length <= 0) {
        throw new ParseException("Must provide a command to execute");
    }/*from  w w  w .  j  ava2s  .co m*/
    String cmd = args[0];
    boolean failedCommand = false;

    AdminUtil<FateCommand> admin = new AdminUtil<FateCommand>(false);

    String path = ZooUtil.getRoot(instance) + Constants.ZFATE;
    String masterPath = ZooUtil.getRoot(instance) + Constants.ZMASTER_LOCK;
    IZooReaderWriter zk = getZooReaderWriter(shellState.getInstance(),
            cl.getOptionValue(secretOption.getOpt()));
    ZooStore<FateCommand> zs = new ZooStore<FateCommand>(path, zk);

    if ("fail".equals(cmd)) {
        if (args.length <= 1) {
            throw new ParseException("Must provide transaction ID");
        }
        for (int i = 1; i < args.length; i++) {
            if (!admin.prepFail(zs, zk, masterPath, args[i])) {
                System.out.printf("Could not fail transaction: %s%n", args[i]);
                failedCommand = true;
            }
        }
    } else if ("delete".equals(cmd)) {
        if (args.length <= 1) {
            throw new ParseException("Must provide transaction ID");
        }
        for (int i = 1; i < args.length; i++) {
            if (admin.prepDelete(zs, zk, masterPath, args[i])) {
                admin.deleteLocks(zs, zk, ZooUtil.getRoot(instance) + Constants.ZTABLE_LOCKS, args[i]);
            } else {
                System.out.printf("Could not delete transaction: %s%n", args[i]);
                failedCommand = true;
            }
        }
    } else if ("list".equals(cmd) || "print".equals(cmd)) {
        // Parse transaction ID filters for print display
        Set<Long> filterTxid = null;
        if (args.length >= 2) {
            filterTxid = new HashSet<Long>(args.length);
            for (int i = 1; i < args.length; i++) {
                try {
                    Long val = Long.parseLong(args[i], 16);
                    filterTxid.add(val);
                } catch (NumberFormatException nfe) {
                    // Failed to parse, will exit instead of displaying everything since the intention was to potentially filter some data
                    System.out.printf("Invalid transaction ID format: %s%n", args[i]);
                    return 1;
                }
            }
        }

        // Parse TStatus filters for print display
        EnumSet<TStatus> filterStatus = null;
        if (cl.hasOption(statusOption.getOpt())) {
            filterStatus = EnumSet.noneOf(TStatus.class);
            String[] tstat = cl.getOptionValues(statusOption.getOpt());
            for (int i = 0; i < tstat.length; i++) {
                try {
                    filterStatus.add(TStatus.valueOf(tstat[i]));
                } catch (IllegalArgumentException iae) {
                    System.out.printf("Invalid transaction status name: %s%n", tstat[i]);
                    return 1;
                }
            }
        }

        StringBuilder buf = new StringBuilder(8096);
        Formatter fmt = new Formatter(buf);
        admin.print(zs, zk, ZooUtil.getRoot(instance) + Constants.ZTABLE_LOCKS, fmt, filterTxid, filterStatus);
        shellState.printLines(Collections.singletonList(buf.toString()).iterator(), true);
    } else {
        throw new ParseException("Invalid command option");
    }

    return failedCommand ? 1 : 0;
}

From source file:org.apereo.portal.xml.stream.IndentingXMLEventWriter.java

/** Note that an element was started. */
protected void afterStartElement() {
    afterMarkup();//  ww w  .j  a v a  2s .com
    ++depth;
    scopeState.push(EnumSet.noneOf(StackState.class));
}

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

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

    super();/*w w w. ja v  a2s .c om*/

    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:com.couchbase.touchdb.testapp.tests.HeavyAttachments.java

@SuppressWarnings("unchecked")
public void buildAttachments(boolean heavyAttachments, boolean pushAttachments) throws Exception {

    TDBlobStore attachments = database.getAttachments();

    Assert.assertEquals(0, attachments.count());
    Assert.assertEquals(new HashSet<Object>(), attachments.allKeys());

    TDStatus status = new TDStatus();
    Map<String, Object> rev1Properties = new HashMap<String, Object>();
    rev1Properties.put("foo", 1);
    rev1Properties.put("bar", false);
    TDRevision rev1 = database.putRevision(new TDRevision(rev1Properties), null, false, status);

    Assert.assertEquals(TDStatus.CREATED, status.getCode());

    byte[] attach1 = "This is the body of attach1".getBytes();
    status = database.insertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach1),
            rev1.getSequence(), "attach", "text/plain", rev1.getGeneration());
    Assert.assertEquals(TDStatus.CREATED, status.getCode());

    TDAttachment attachment = database.getAttachmentForSequence(rev1.getSequence(), "attach", status);
    Assert.assertEquals(TDStatus.OK, status.getCode());
    Assert.assertEquals("text/plain", attachment.getContentType());
    byte[] data = IOUtils.toByteArray(attachment.getContentStream());
    Assert.assertTrue(Arrays.equals(attach1, data));

    Map<String, Object> innerDict = new HashMap<String, Object>();
    innerDict.put("content_type", "text/plain");
    innerDict.put("digest", "sha1-gOHUOBmIMoDCrMuGyaLWzf1hQTE=");
    innerDict.put("length", 27);
    innerDict.put("stub", true);
    innerDict.put("revpos", 1);
    Map<String, Object> attachmentDict = new HashMap<String, Object>();
    attachmentDict.put("attach", innerDict);

    Map<String, Object> attachmentDictForSequence = database
            .getAttachmentsDictForSequenceWithContent(rev1.getSequence(), false);
    Assert.assertEquals(attachmentDict, attachmentDictForSequence);

    TDRevision gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(),
            EnumSet.noneOf(TDDatabase.TDContentOptions.class));
    Map<String, Object> gotAttachmentDict = (Map<String, Object>) gotRev1.getProperties().get("_attachments");
    Assert.assertEquals(attachmentDict, gotAttachmentDict);

    // Check the attachment dict, with attachments included:
    innerDict.remove("stub");
    innerDict.put("data", Base64.encodeBytes(attach1));
    attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), true);
    Assert.assertEquals(attachmentDict, attachmentDictForSequence);

    gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(),
            EnumSet.of(TDDatabase.TDContentOptions.TDIncludeAttachments));
    gotAttachmentDict = (Map<String, Object>) gotRev1.getProperties().get("_attachments");
    Assert.assertEquals(attachmentDict, gotAttachmentDict);

    // Add a second revision that doesn't update the attachment:
    Map<String, Object> rev2Properties = new HashMap<String, Object>();
    rev2Properties.put("_id", rev1.getDocId());
    rev2Properties.put("foo", 2);
    rev2Properties.put("bazz", false);
    TDRevision rev2 = database.putRevision(new TDRevision(rev2Properties), rev1.getRevId(), false, status);
    Assert.assertEquals(TDStatus.CREATED, status.getCode());

    status = database.copyAttachmentNamedFromSequenceToSequence("attach", rev1.getSequence(),
            rev2.getSequence());//from   www  . ja v  a2 s.c o  m
    Assert.assertEquals(TDStatus.OK, status.getCode());

    // Add a third revision of the same document:
    Map<String, Object> rev3Properties = new HashMap<String, Object>();
    rev3Properties.put("_id", rev2.getDocId());
    rev3Properties.put("foo", 2);
    rev3Properties.put("bazz", false);
    TDRevision rev3 = database.putRevision(new TDRevision(rev3Properties), rev2.getRevId(), false, status);
    Assert.assertEquals(TDStatus.CREATED, status.getCode());

    byte[] attach2 = "<html>And this is attach2</html>".getBytes();
    status = database.insertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach2),
            rev3.getSequence(), "attach", "text/html", rev2.getGeneration());
    Assert.assertEquals(TDStatus.CREATED, status.getCode());

    // Check the 2nd revision's attachment:
    TDAttachment attachment2 = database.getAttachmentForSequence(rev2.getSequence(), "attach", status);
    Assert.assertEquals(TDStatus.OK, status.getCode());
    Assert.assertEquals("text/plain", attachment2.getContentType());
    data = IOUtils.toByteArray(attachment2.getContentStream());
    Assert.assertTrue(Arrays.equals(attach1, data));

    // Check the 3rd revision's attachment:
    TDAttachment attachment3 = database.getAttachmentForSequence(rev3.getSequence(), "attach", status);
    Assert.assertEquals(TDStatus.OK, status.getCode());
    Assert.assertEquals("text/html", attachment3.getContentType());
    data = IOUtils.toByteArray(attachment3.getContentStream());
    Assert.assertTrue(Arrays.equals(attach2, data));

    // Examine the attachment store:
    Assert.assertEquals(2, attachments.count());
    Set<TDBlobKey> expected = new HashSet<TDBlobKey>();
    expected.add(TDBlobStore.keyForBlob(attach1));
    expected.add(TDBlobStore.keyForBlob(attach2));

    Assert.assertEquals(expected, attachments.allKeys());

    status = database.compact(); // This clears the body of the first revision
    Assert.assertEquals(TDStatus.OK, status.getCode());
    Assert.assertEquals(1, attachments.count());

    Set<TDBlobKey> expected2 = new HashSet<TDBlobKey>();
    expected2.add(TDBlobStore.keyForBlob(attach2));
    Assert.assertEquals(expected2, attachments.allKeys());
    TDRevision lastRev = rev3;

    if (heavyAttachments) {
        int numberOfImagesOkayOn512Ram = 4;
        int numberOfImagesOkayOn768Ram = 6;
        int numberOfImagesOkayOn1024Ram = 8;

        lastRev = attachImages(numberOfImagesOkayOn1024Ram, rev3);
        /* query the db for that doc */
        TDRevision largerRev = database.getDocumentWithIDAndRev(lastRev.getDocId(), lastRev.getRevId(),
                EnumSet.noneOf(TDDatabase.TDContentOptions.class));
        attachmentDict = (Map<String, Object>) largerRev.getProperties().get("_attachments");
        Assert.assertNotNull(attachmentDict);
    }
    if (pushAttachments) {
        URL remote = getReplicationURL();
        deleteRemoteDB(remote);
        final TDReplicator repl = database.getReplicator(remote, true, false, server.getWorkExecutor());
        ((TDPusher) repl).setCreateTarget(true);
        try {
            runTestOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // Push them to the remote:
                    repl.start();
                    Assert.assertTrue(repl.isRunning());
                }
            });
        } catch (Throwable e) {
            e.printStackTrace();
        }

        while (repl.isRunning()) {
            Log.i(TAG, "Waiting for replicator to finish");
            Thread.sleep(1000);
        }

        /* Ensure that the last version of the doc is the last thing replicated. */
        Assert.assertTrue(lastRev.getRevId().startsWith(repl.getLastSequence()));

    }

}

From source file:com.github.fge.ftpfs.io.commonsnetimpl.CommonsNetFtpAgent.java

private static EnumSet<AccessMode> calculateAccess(final FTPFile file) {
    final EnumSet<AccessMode> ret = EnumSet.noneOf(AccessMode.class);
    if (file.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION))
        ret.add(AccessMode.READ);
    if (file.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION))
        ret.add(AccessMode.WRITE);
    if (file.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION))
        ret.add(AccessMode.EXECUTE);
    return ret;/*  ww  w  . j a v a2s.c o m*/
}

From source file:org.icgc.dcc.submission.sftp.fs.HdfsSshFile.java

@Override
public Map<Attribute, Object> getAttributes(boolean followLinks) throws IOException {
    val map = new HashMap<Attribute, Object>();
    map.put(Size, getSize());/*from  w  w w  .j a va2 s .  c  o m*/
    map.put(IsDirectory, isDirectory());
    map.put(IsRegularFile, isFile());
    map.put(IsSymbolicLink, false);
    map.put(LastModifiedTime, getLastModified());
    map.put(LastAccessTime, getLastModified());
    map.put(Group, FILE_SYSTEM_GROUP);
    map.put(Owner, FILE_SYSTEM_OWNER);

    val p = EnumSet.noneOf(Permission.class);
    if (isReadable()) {
        p.add(UserRead);
        p.add(GroupRead);
        p.add(OthersRead);
    }
    if (isWritable()) {
        p.add(UserWrite);
        p.add(GroupWrite);
        p.add(OthersWrite);
    }
    if (isExecutable()) {
        p.add(UserExecute);
        p.add(GroupExecute);
        p.add(OthersExecute);
    }

    map.put(Permissions, p);

    return map;
}

From source file:de.grobox.liberario.fragments.ProductDialogFragment.java

private EnumSet<Product> getProductsFromItems(Set<ProductItem> items) {
    EnumSet<Product> products = EnumSet.noneOf(Product.class);
    for (ProductItem item : items) {
        products.add(item.product);/* w  w  w.  j  a v a  2  s  .c  o m*/
    }
    return products;
}

From source file:com.ryantenney.metrics.spring.reporter.DatadogReporterFactoryBean.java

@SuppressWarnings("resource")
@Override//ww  w . ja  va 2s.co  m
protected DatadogReporter createInstance() {
    final DatadogReporter.Builder reporter = DatadogReporter.forRegistry(getMetricRegistry());

    final Transport transport;
    String transportName = getProperty(TRANSPORT);
    if ("http".equalsIgnoreCase(transportName)) {
        HttpTransport.Builder builder = new HttpTransport.Builder();
        builder.withApiKey(getProperty(API_KEY));
        if (hasProperty(CONNECT_TIMEOUT)) {
            builder.withConnectTimeout(getProperty(CONNECT_TIMEOUT, Integer.class));
        }
        if (hasProperty(SOCKET_TIMEOUT)) {
            builder.withSocketTimeout(getProperty(SOCKET_TIMEOUT, Integer.class));
        }
        transport = builder.build();
    } else if ("udp".equalsIgnoreCase(transportName) || "statsd".equalsIgnoreCase(transportName)) {
        UdpTransport.Builder builder = new UdpTransport.Builder();
        if (hasProperty(STATSD_HOST)) {
            builder.withStatsdHost(getProperty(STATSD_HOST));
        }
        if (hasProperty(STATSD_PORT)) {
            builder.withPort(getProperty(STATSD_PORT, Integer.class));
        }
        if (hasProperty(STATSD_PREFIX)) {
            builder.withPrefix(getProperty(STATSD_PREFIX));
        }
        transport = builder.build();
    } else {
        throw new IllegalArgumentException("Invalid Datadog Transport: " + transportName);
    }
    reporter.withTransport(transport);

    if (hasProperty(TAGS)) {
        reporter.withTags(asList(StringUtils.tokenizeToStringArray(getProperty(TAGS), ",", true, true)));
    }

    if (StringUtils.hasText(getProperty(HOST))) {
        reporter.withHost(getProperty(HOST));
    } else if ("true".equalsIgnoreCase(getProperty(EC2_HOST))) {
        try {
            reporter.withEC2Host();
        } catch (IOException e) {
            throw new IllegalStateException("DatadogReporter.Builder.withEC2Host threw an exception", e);
        }
    }

    if (hasProperty(EXPANSION)) {
        String configString = getProperty(EXPANSION).trim().toUpperCase(Locale.ENGLISH);
        final EnumSet<Expansion> expansions;
        if ("ALL".equals(configString)) {
            expansions = Expansion.ALL;
        } else {
            expansions = EnumSet.noneOf(Expansion.class);
            for (String expandedMetricStr : StringUtils.tokenizeToStringArray(configString, ",", true, true)) {
                expansions.add(Expansion.valueOf(expandedMetricStr.replace(' ', '_')));
            }
        }
        reporter.withExpansions(expansions);
    }

    if (hasProperty(DYNAMIC_TAG_CALLBACK_REF)) {
        reporter.withDynamicTagCallback(getPropertyRef(DYNAMIC_TAG_CALLBACK_REF, DynamicTagsCallback.class));
    }

    if (hasProperty(METRIC_NAME_FORMATTER_REF)) {
        reporter.withMetricNameFormatter(getPropertyRef(METRIC_NAME_FORMATTER_REF, MetricNameFormatter.class));
    }

    if (hasProperty(PREFIX)) {
        reporter.withPrefix(getProperty(PREFIX));
    }

    if (hasProperty(DURATION_UNIT)) {
        reporter.convertDurationsTo(getProperty(DURATION_UNIT, TimeUnit.class));
    }

    if (hasProperty(RATE_UNIT)) {
        reporter.convertRatesTo(getProperty(RATE_UNIT, TimeUnit.class));
    }

    if (hasProperty(CLOCK_REF)) {
        reporter.withClock(getPropertyRef(CLOCK_REF, Clock.class));
    }

    reporter.filter(getMetricFilter());

    return reporter.build();
}

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

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

    super();/*from w w  w .  j a  v  a2  s .c om*/

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

    mapConnBundleTOs = new HashMap<String, Map<String, Map<String, ConnBundleTO>>>();
    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<ConnInstanceTO>(FORM);
    connectorForm.setModel(new CompoundPropertyModel<ConnInstanceTO>(connInstanceTO));
    connectorForm.setOutputMarkupId(true);
    add(connectorForm);

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

    final Form<ConnInstanceTO> connectorPropForm = new Form<ConnInstanceTO>("connectorPropForm");
    connectorPropForm.setModel(new CompoundPropertyModel<ConnInstanceTO>(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<String>("location", "location",
            new Model<String>(bundleTO == null ? null : bundleTO.getLocation()));
    ((DropDownChoice<String>) location.getField()).setNullValid(true);
    location.setStyleSheet("long_dynamicsize");
    location.setChoices(new ArrayList<String>(mapConnBundleTOs.keySet()));
    location.setRequired(true);
    location.addRequiredLabel();
    location.setOutputMarkupId(true);
    location.setEnabled(connInstanceTO.getId() == 0);
    location.getField().setOutputMarkupId(true);
    connectorForm.add(location);

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

    final AjaxDropDownChoicePanel<String> version = new AjaxDropDownChoicePanel<String>("version", "version",
            new Model<String>(bundleTO == null ? null : bundleTO.getVersion()));
    version.setStyleSheet("long_dynamicsize");
    version.setChoices(bundleTO == null ? new ArrayList<String>()
            : new ArrayList<String>(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<Integer>("connRequestTimeout",
            "connRequestTimeout", Integer.class,
            new PropertyModel<Integer>(connInstanceTO, "connRequestTimeout"), 0, null);
    connRequestTimeout.getField().add(new RangeValidator<Integer>(0, Integer.MAX_VALUE));
    connectorForm.add(connRequestTimeout);

    if (connInstanceTO.getPoolConf() == null) {
        connInstanceTO.setPoolConf(new ConnPoolConfTO());
    }
    final SpinnerFieldPanel<Integer> poolMaxObjects = new SpinnerFieldPanel<Integer>("poolMaxObjects",
            "poolMaxObjects", Integer.class,
            new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxObjects"), 0, null);
    poolMaxObjects.getField().add(new RangeValidator<Integer>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxObjects);
    final SpinnerFieldPanel<Integer> poolMinIdle = new SpinnerFieldPanel<Integer>("poolMinIdle", "poolMinIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "minIdle"), 0, null);
    poolMinIdle.getField().add(new RangeValidator<Integer>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMinIdle);
    final SpinnerFieldPanel<Integer> poolMaxIdle = new SpinnerFieldPanel<Integer>("poolMaxIdle", "poolMaxIdle",
            Integer.class, new PropertyModel<Integer>(connInstanceTO.getPoolConf(), "maxIdle"), 0, null);
    poolMaxIdle.getField().add(new RangeValidator<Integer>(0, Integer.MAX_VALUE));
    connectorForm.add(poolMaxIdle);
    final SpinnerFieldPanel<Long> poolMaxWait = new SpinnerFieldPanel<Long>("poolMaxWait", "poolMaxWait",
            Long.class, new PropertyModel<Long>(connInstanceTO.getPoolConf(), "maxWait"), 0L, null);
    poolMaxWait.getField().add(new RangeValidator<Long>(0L, Long.MAX_VALUE));
    connectorForm.add(poolMaxWait);
    final SpinnerFieldPanel<Long> poolMinEvictableIdleTime = new SpinnerFieldPanel<Long>(
            "poolMinEvictableIdleTime", "poolMinEvictableIdleTime", Long.class,
            new PropertyModel<Long>(connInstanceTO.getPoolConf(), "minEvictableIdleTimeMillis"), 0L, null);
    poolMinEvictableIdleTime.getField().add(new RangeValidator<Long>(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<String>(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<String>(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 AltListView<ConnConfProperty>("connectorProperties",
            new PropertyModel<List<ConnConfProperty>>(this, "properties")) {

        private static final long serialVersionUID = 9101744072914090143L;

        @Override
        @SuppressWarnings({ "unchecked", "rawtypes" })
        protected void populateItem(final ListItem<ConnConfProperty> item) {
            final ConnConfProperty property = item.getModelObject();

            final Label label = new Label("connPropAttrSchema",
                    StringUtils.isBlank(property.getSchema().getDisplayName()) ? property.getSchema().getName()
                            : property.getSchema().getDisplayName());
            item.add(label);

            final FieldPanel field;
            boolean required = false;
            boolean isArray = false;
            if (property.getSchema().isConfidential()
                    || Constants.GUARDED_STRING.equalsIgnoreCase(property.getSchema().getType())
                    || Constants.GUARDED_BYTE_ARRAY.equalsIgnoreCase(property.getSchema().getType())) {

                field = new AjaxPasswordFieldPanel("panel", label.getDefaultModelObjectAsString(),
                        new Model<String>());

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

                required = property.getSchema().isRequired();
            } else {
                Class<?> propertySchemaClass;

                try {
                    propertySchemaClass = ClassUtils.forName(property.getSchema().getType(),
                            ClassUtils.getDefaultClassLoader());
                    if (ClassUtils.isPrimitiveOrWrapper(propertySchemaClass)) {
                        propertySchemaClass = org.apache.commons.lang3.ClassUtils
                                .primitiveToWrapper(propertySchemaClass);
                    }
                } catch (Exception e) {
                    LOG.error("Error parsing attribute type", e);
                    propertySchemaClass = String.class;
                }
                if (ClassUtils.isAssignable(Number.class, propertySchemaClass)) {
                    field = new SpinnerFieldPanel<Number>("panel", label.getDefaultModelObjectAsString(),
                            (Class<Number>) propertySchemaClass, new Model<Number>(), null, null);

                    required = property.getSchema().isRequired();
                } else if (ClassUtils.isAssignable(Boolean.class, propertySchemaClass)) {
                    field = new AjaxCheckBoxPanel("panel", label.getDefaultModelObjectAsString(),
                            new Model<Boolean>());
                } else {
                    field = new AjaxTextFieldPanel("panel", label.getDefaultModelObjectAsString(),
                            new Model<String>());

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

                if (propertySchemaClass.isArray()) {
                    isArray = true;
                }
            }

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

            if (required) {
                field.addRequiredLabel();
            }

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

                item.add(new MultiFieldPanel<String>("panel",
                        new PropertyModel<List<String>>(property, "values"), field));
            } else {
                field.setNewModel(property.getValues());
                item.add(field);
            }

            final AjaxCheckBoxPanel overridable = new AjaxCheckBoxPanel("connPropAttrOverridable",
                    "connPropAttrOverridable", new PropertyModel<Boolean>(property, "overridable"));

            item.add(overridable);
            connInstanceTO.getConfiguration().add(property);
        }
    };
    connPropView.setOutputMarkupId(true);
    connectorPropForm.add(connPropView);

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

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            connInstanceTO.setBundleName(bundleTO.getBundleName());
            connInstanceTO.setVersion(bundleTO.getVersion());
            connInstanceTO.setConnectorName(bundleTO.getConnectorName());

            if (restClient.check(connInstanceTO)) {
                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<ConnectorCapability>(
            "capabilitiesPalette", new PropertyModel<List<ConnectorCapability>>(this, "selectedCapabilities"),
            capabilities);
    connectorForm.add(capabilitiesPalette);

    // form - submit / cancel buttons
    final AjaxButton submit = new IndicatingAjaxButton(APPLY, new Model<String>(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()
                    .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.getId() == 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.getId() == 0 ? xmlRolesReader.getAllAllowedRoles("Connectors", "create")
            : xmlRolesReader.getAllAllowedRoles("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);
}