http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- USERS & GROUPS CRUDS -->
- <bean id="newUser" class="org.argeo.security.ui.admin.commands.NewUser"
+ <bean id="newUser" class="org.argeo.security.ui.admin.internal.commands.NewUser"
scope="prototype">
<property name="userAdminWrapper" ref="userAdminWrapper" />
</bean>
- <bean id="newGroup" class="org.argeo.security.ui.admin.commands.NewGroup"
+ <bean id="newGroup" class="org.argeo.security.ui.admin.internal.commands.NewGroup"
scope="prototype">
<property name="userAdminWrapper" ref="userAdminWrapper" />
</bean>
- <bean id="deleteUsers" class="org.argeo.security.ui.admin.commands.DeleteUsers"
+ <bean id="deleteUsers" class="org.argeo.security.ui.admin.internal.commands.DeleteUsers"
scope="prototype">
<property name="userAdminWrapper" ref="userAdminWrapper" />
</bean>
- <bean id="deleteGroups" class="org.argeo.security.ui.admin.commands.DeleteGroups"
+ <bean id="deleteGroups" class="org.argeo.security.ui.admin.internal.commands.DeleteGroups"
scope="prototype">
<property name="userAdminWrapper" ref="userAdminWrapper" />
</bean>
- <!-- <bean id="userBatchUpdate" class="org.argeo.security.ui.admin.commands.UserBatchUpdate"
+ <!-- <bean id="userBatchUpdate" class="org.argeo.security.ui.admin.internal.commands.UserBatchUpdate"
scope="prototype"> <property name="repository" ref="nodeRepository" /> <property
name="userAdminService" ref="userAdminService" /> </bean> -->
<!-- TRANSACTIONS -->
<bean id="userTransactionHandler"
- class="org.argeo.security.ui.admin.commands.UserTransactionHandler"
+ class="org.argeo.security.ui.admin.internal.commands.UserTransactionHandler"
scope="prototype">
<property name="userAdminWrapper" ref="userAdminWrapper" />
</bean>
\r
\r
<bean id="userTransactionProvider"\r
- class="org.argeo.security.ui.admin.internal.UserTransactionProvider"\r
+ class="org.argeo.security.ui.admin.internal.providers.UserTransactionProvider"\r
scope="singleton" lazy-init="false">\r
<property name="userTransaction" ref="userTransaction" />\r
</bean>\r
<!-- Editors -->
- <bean id="userEditor" class="org.argeo.security.ui.admin.editors.UserEditor"
+ <bean id="userEditor" class="org.argeo.security.ui.admin.internal.parts.UserEditor"
scope="prototype">
<property name="userAdminWrapper" ref="userAdminWrapper" />
</bean>
<!-- Force the refresh when the various listener are not enough -->
<command
- defaultHandler="org.argeo.security.ui.admin.commands.ForceRefresh"
+ defaultHandler="org.argeo.security.ui.admin.internal.commands.ForceRefresh"
id="org.argeo.security.ui.admin.forceRefresh"
name="Force Refresh">
</command>
provider="org.argeo.eclipse.spring.SpringExtensionFactory" >
<!-- <sourceProvider
- provider="org.argeo.security.ui.admin.internal.UserTransactionProvider">
+ provider="org.argeo.security.ui.admin.internal.providers.UserTransactionProvider">
--> <variable
name="org.argeo.security.ui.admin.userTransactionState"
priorityLevel="workbench">
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.commands;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.argeo.security.ui.admin.internal.UiAdminUtils;
-import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Deletes the selected groups */
-public class DeleteGroups extends AbstractHandler {
- public final static String ID = SecurityAdminPlugin.PLUGIN_ID
- + ".deleteGroups";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- @SuppressWarnings("unchecked")
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection = HandlerUtil.getCurrentSelection(event);
- if (selection.isEmpty())
- return null;
-
- List<Group> groups = new ArrayList<Group>();
- Iterator<Group> it = ((IStructuredSelection) selection).iterator();
- StringBuilder builder = new StringBuilder();
- while (it.hasNext()) {
- Group currGroup = it.next();
- String groupName = UiAdminUtils.getUsername(currGroup);
- // TODO add checks
- builder.append(groupName).append("; ");
- groups.add(currGroup);
- }
-
- if (!MessageDialog.openQuestion(HandlerUtil.getActiveShell(event),
- "Delete Groups",
- "Are you sure that you " + "want to delete these groups?\n"
- + builder.substring(0, builder.length() - 2)))
- return null;
-
- userAdminWrapper.beginTransactionIfNeeded();
- UserAdmin userAdmin = userAdminWrapper.getUserAdmin();
- for (Group group : groups) {
- userAdmin.removeRole(group.getName());
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_REMOVED, group));
- }
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.commands;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.argeo.security.ui.admin.internal.UiAdminUtils;
-import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Deletes the selected users */
-public class DeleteUsers extends AbstractHandler {
- public final static String ID = SecurityAdminPlugin.PLUGIN_ID
- + ".deleteUsers";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- @SuppressWarnings("unchecked")
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection = HandlerUtil.getCurrentSelection(event);
- if (selection.isEmpty())
- return null;
-
- Iterator<User> it = ((IStructuredSelection) selection).iterator();
- List<User> users = new ArrayList<User>();
- StringBuilder builder = new StringBuilder();
-
- while (it.hasNext()) {
- User currUser = it.next();
- String userName = UiAdminUtils.getUsername(currUser);
- if (UiAdminUtils.isCurrentUser(currUser)) {
- MessageDialog.openError(HandlerUtil.getActiveShell(event),
- "Deletion forbidden",
- "You cannot delete your own user this way.");
- return null;
- }
- builder.append(userName).append("; ");
- users.add(currUser);
- }
-
- if (!MessageDialog.openQuestion(
- HandlerUtil.getActiveShell(event),
- "Delete Users",
- "Are you sure that you want to delete these users?\n"
- + builder.substring(0, builder.length() - 2)))
- return null;
-
- userAdminWrapper.beginTransactionIfNeeded();
- UserAdmin userAdmin = userAdminWrapper.getUserAdmin();
- for (User user : users) {
- userAdmin.removeRole(user.getName());
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_REMOVED, user));
- }
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.commands;
-
-import org.argeo.security.ui.admin.internal.parts.GroupsView;
-import org.argeo.security.ui.admin.internal.parts.UsersView;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Retrieve the active view or editor and call forceRefresh method if defined */
-public class ForceRefresh extends AbstractHandler {
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- IWorkbenchWindow iww = HandlerUtil.getActiveWorkbenchWindow(event);
- if (iww == null)
- return null;
- IWorkbenchPage activePage = iww.getActivePage();
- IWorkbenchPart part = activePage.getActivePart();
- if (part instanceof UsersView)
- ((UsersView) part).refresh();
- else if (part instanceof GroupsView)
- ((GroupsView) part).refresh();
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.commands;
-
-import java.util.Dictionary;
-
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.argeo.security.ui.admin.internal.UiAdminUtils;
-import org.argeo.security.ui.admin.internal.UserAdminConstants;
-import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Create a new group. */
-public class NewGroup extends AbstractHandler {
- public final static String ID = SecurityAdminPlugin.PLUGIN_ID + ".newGroup";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
- private UserAdmin userAdmin;
-
- // TODO implement a dynamic choice of the base dn
- private String getDn(String cn) {
- return "cn=" + cn + ",dc=example,dc=com";
- }
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- NewGroupWizard newGroupWizard = new NewGroupWizard();
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), newGroupWizard);
- dialog.setTitle("Create a new group");
- dialog.open();
- return null;
- }
-
- private class NewGroupWizard extends Wizard {
-
- // pages
- private MainGroupInfoWizardPage mainGroupInfo;
-
- // End user fields
- private Text dNameTxt, commonNameTxt, descriptionTxt;
-
- public NewGroupWizard() {
- }
-
- @Override
- public void addPages() {
- mainGroupInfo = new MainGroupInfoWizardPage();
- addPage(mainGroupInfo);
-
- setWindowTitle("Create a new group");
- // mainGroupInfo.setMessage(message, WizardPage.WARNING);
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- String commonName = commonNameTxt.getText();
- try {
- userAdminWrapper.beginTransactionIfNeeded();
- Group group = (Group) userAdmin.createRole(getDn(commonName),
- Role.GROUP);
- Dictionary props = group.getProperties();
- String descStr = descriptionTxt.getText();
- if (UiAdminUtils.notNull(descStr))
- props.put(UserAdminConstants.KEY_DESC, descStr);
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_CREATED, group));
- return true;
- } catch (Exception e) {
- ErrorFeedback.show("Cannot create new group " + commonName, e);
- return false;
- }
- }
-
- private class MainGroupInfoWizardPage extends WizardPage implements
- ModifyListener, ArgeoNames {
- private static final long serialVersionUID = -3150193365151601807L;
-
- public MainGroupInfoWizardPage() {
- super("Main");
- setTitle("General information");
- setMessage("Please provide a common name and a free description");
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite bodyCmp = new Composite(parent, SWT.NONE);
- bodyCmp.setLayout(new GridLayout(2, false));
- dNameTxt = EclipseUiUtils.createGridLT(bodyCmp,
- "Distinguished name", this);
- dNameTxt.setEnabled(false);
- commonNameTxt = EclipseUiUtils.createGridLT(bodyCmp,
- "Common name", this);
- commonNameTxt.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = -1435351236582736843L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- String name = commonNameTxt.getText();
- if (name.trim().equals("")) {
- dNameTxt.setText("");
- } else {
- dNameTxt.setText(getDn(name));
- }
- }
- });
-
- Label descLbl = new Label(bodyCmp, SWT.LEAD);
- descLbl.setText("Description");
- descLbl.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false,
- false));
- descriptionTxt = new Text(bodyCmp, SWT.LEAD | SWT.MULTI
- | SWT.WRAP | SWT.BORDER);
- descriptionTxt.setLayoutData(EclipseUiUtils.fillAll());
- descriptionTxt.addModifyListener(this);
-
- setControl(bodyCmp);
-
- // Initialize buttons
- setPageComplete(false);
- getContainer().updateButtons();
- }
-
- @Override
- public void modifyText(ModifyEvent event) {
- String message = checkComplete();
- if (message != null) {
- setMessage(message, WizardPage.ERROR);
- setPageComplete(false);
- } else {
- setMessage("Complete", WizardPage.INFORMATION);
- setPageComplete(true);
- }
- getContainer().updateButtons();
- }
-
- /** @return error message or null if complete */
- protected String checkComplete() {
- String name = commonNameTxt.getText();
-
- if (name.trim().equals(""))
- return "Common name must not be empty";
- Role role = userAdmin.getRole(getDn(name));
- if (role != null)
- return "Group " + name + " already exists";
- return null;
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible)
- commonNameTxt.setFocus();
- }
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- this.userAdmin = userAdminWrapper.getUserAdmin();
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.commands;
-
-import java.util.Dictionary;
-
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.security.UserAdminService;
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.argeo.security.ui.admin.internal.UiAdminUtils;
-import org.argeo.security.ui.admin.internal.UserAdminConstants;
-import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Open a wizard that enables creation of a new user. */
-public class NewUser extends AbstractHandler {
- // private final static Log log = LogFactory.getLog(NewUser.class);
- public final static String ID = SecurityAdminPlugin.PLUGIN_ID + ".newUser";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- // TODO implement a dynamic choice of the base dn
- private String getDn(String uid) {
- return "uid=" + uid + ",ou=users,dc=example,dc=com";
- }
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- NewUserWizard newUserWizard = new NewUserWizard();
- WizardDialog dialog = new WizardDialog(
- HandlerUtil.getActiveShell(event), newUserWizard);
-
- dialog.open();
-
- // // Force refresh until the listener are implemented
- // if (Window.OK == dialog.open())
- // forceRefresh(event);
- return null;
- }
-
- // private void forceRefresh(ExecutionEvent event) {
- // IWorkbenchWindow iww = HandlerUtil.getActiveWorkbenchWindow(event);
- // if (iww == null)
- // return;
- // IWorkbenchPage activePage = iww.getActivePage();
- // IWorkbenchPart part = activePage.getActivePart();
- // if (part instanceof UsersView)
- // ((UsersView) part).refresh();
- // }
-
- private class NewUserWizard extends Wizard {
-
- // pages
- private MainUserInfoWizardPage mainUserInfo;
-
- // End user fields
- private Text dNameTxt, usernameTxt, firstNameTxt, lastNameTxt,
- primaryMailTxt, pwd1Txt, pwd2Txt;
-
- public NewUserWizard() {
- }
-
- @Override
- public void addPages() {
- mainUserInfo = new MainUserInfoWizardPage();
- addPage(mainUserInfo);
- String message = "Dummy wizard to ease user creation tests:\n Mail and last name are automatically "
- + "generated form the uid. Password are defauted to 'demo'.";
- mainUserInfo.setMessage(message, WizardPage.WARNING);
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
- String username = mainUserInfo.getUsername();
- try {
- userAdminWrapper.beginTransactionIfNeeded();
- char[] password = mainUserInfo.getPassword();
- User user = (User) userAdminWrapper.getUserAdmin().createRole(
- getDn(username), Role.USER);
-
- Dictionary props = user.getProperties();
-
- String lastNameStr = lastNameTxt.getText();
- if (UiAdminUtils.notNull(lastNameStr))
- props.put(UserAdminConstants.KEY_LASTNAME, lastNameStr);
-
- String firstNameStr = firstNameTxt.getText();
- if (UiAdminUtils.notNull(firstNameStr))
- props.put(UserAdminConstants.KEY_FIRSTNAME, firstNameStr);
-
- String cn = UiAdminUtils
- .getDefaultCn(firstNameStr, lastNameStr);
- if (UiAdminUtils.notNull(cn))
- props.put(UserAdminConstants.KEY_CN, cn);
-
- String mailStr = primaryMailTxt.getText();
- if (UiAdminUtils.notNull(mailStr))
- props.put(UserAdminConstants.KEY_MAIL, mailStr);
-
- user.getCredentials().put(null, password);
-
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_CREATED, user));
- return true;
- } catch (Exception e) {
- ErrorFeedback.show("Cannot create new user " + username, e);
- return false;
- }
- }
-
- private class MainUserInfoWizardPage extends WizardPage implements
- ModifyListener, ArgeoNames {
- private static final long serialVersionUID = -3150193365151601807L;
-
- public MainUserInfoWizardPage() {
- super("Main");
- setTitle("Required Information");
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- dNameTxt = EclipseUiUtils.createGridLT(composite,
- "Distinguished name", this);
- dNameTxt.setEnabled(false);
- usernameTxt = EclipseUiUtils.createGridLT(composite,
- "Local ID", this);
- usernameTxt.addModifyListener(new ModifyListener() {
- private static final long serialVersionUID = -1435351236582736843L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- String name = usernameTxt.getText();
- if (name.trim().equals("")) {
- dNameTxt.setText("");
- lastNameTxt.setText("");
- primaryMailTxt.setText("");
- pwd1Txt.setText("");
- pwd2Txt.setText("");
- } else {
- dNameTxt.setText(getDn(name));
- lastNameTxt.setText(name.toUpperCase());
- primaryMailTxt.setText(name + "@example.com");
- pwd1Txt.setText("demo");
- pwd2Txt.setText("demo");
- }
- }
- });
-
- primaryMailTxt = EclipseUiUtils.createGridLT(composite,
- "Email", this);
- firstNameTxt = EclipseUiUtils.createGridLT(composite,
- "First name", this);
- lastNameTxt = EclipseUiUtils.createGridLT(composite,
- "Last name", this);
- pwd1Txt = EclipseUiUtils.createGridLP(composite, "Password",
- this);
- pwd2Txt = EclipseUiUtils.createGridLP(composite,
- "Repeat password", this);
- setControl(composite);
-
- // Initialize buttons
- setPageComplete(false);
- getContainer().updateButtons();
- }
-
- @Override
- public void modifyText(ModifyEvent event) {
- String message = checkComplete();
- if (message != null) {
- setMessage(message, WizardPage.ERROR);
- setPageComplete(false);
- } else {
- setMessage("Complete", WizardPage.INFORMATION);
- setPageComplete(true);
- }
- getContainer().updateButtons();
- }
-
- /** @return error message or null if complete */
- protected String checkComplete() {
- String name = usernameTxt.getText();
-
- if (name.trim().equals(""))
- return "User name must not be empty";
- Role role = userAdminWrapper.getUserAdmin()
- .getRole(getDn(name));
- if (role != null)
- return "User " + name + " already exists";
- if (!primaryMailTxt.getText().matches(
- UserAdminService.EMAIL_PATTERN))
- return "Not a valid email address";
- if (lastNameTxt.getText().trim().equals(""))
- return "Specify a last name";
- if (pwd1Txt.getText().trim().equals(""))
- return "Specify a password";
- if (pwd2Txt.getText().trim().equals(""))
- return "Repeat the password";
- if (!pwd2Txt.getText().equals(pwd1Txt.getText()))
- return "Passwords are different";
- return null;
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible)
- usernameTxt.setFocus();
- }
-
- public String getUsername() {
- return usernameTxt.getText();
- }
-
- public char[] getPassword() {
- return pwd1Txt.getTextChars();
- }
-
- }
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.commands;
-
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/** Save the currently edited Argeo user. */
-public class SaveArgeoUser extends AbstractHandler {
- public final static String ID = SecurityAdminPlugin.PLUGIN_ID
- + ".saveArgeoUser";
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- try {
- IWorkbenchPart iwp = HandlerUtil.getActiveWorkbenchWindow(event)
- .getActivePage().getActivePart();
-
- if (!(iwp instanceof IEditorPart))
- return null;
- IEditorPart editor = (IEditorPart) iwp;
- editor.doSave(null);
- } catch (Exception e) {
- MessageDialog.openError(Display.getDefault().getActiveShell(),
- "Error", "Cannot save user: " + e.getMessage());
- }
- return null;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.commands;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-
-/** Launch a wizard to update various properties about users in JCR. */
-public class UserBatchUpdate extends AbstractHandler {
- // private Repository repository;
- // private UserAdminService userAdminService;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- // Session session = null;
- // try {
- // session = repository.login();
- // UserBatchUpdateWizard userBatchUpdateWizard = new
- // UserBatchUpdateWizard(
- // session, userAdminService);
- // WizardDialog dialog = new WizardDialog(
- // HandlerUtil.getActiveShell(event), userBatchUpdateWizard);
- // dialog.open();
- // } catch (Exception e) {
- // throw new ExecutionException("Cannot open wizard", e);
- // } finally {
- // JcrUtils.logoutQuietly(session);
- // }
- return null;
- }
-
-// public void setRepository(Repository repository) {
-// this.repository = repository;
-// }
- //
- // public void setUserAdminService(UserAdminService userAdminService) {
- // this.userAdminService = userAdminService;
- // }
-
- // public void setJcrSecurityModel(JcrSecurityModel jcrSecurityModel) {
- // this.jcrSecurityModel = jcrSecurityModel;
- // }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.commands;
-
-import javax.transaction.Status;
-import javax.transaction.UserTransaction;
-
-import org.argeo.ArgeoException;
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.argeo.security.ui.admin.internal.UiAdminUtils;
-import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Manage the transaction that is bound to the current perspective */
-public class UserTransactionHandler extends AbstractHandler {
- public final static String ID = SecurityAdminPlugin.PLUGIN_ID
- + ".userTransactionHandler";
-
- public final static String PARAM_COMMAND_ID = "param.commandId";
-
- public final static String TRANSACTION_BEGIN = "transaction.begin";
- public final static String TRANSACTION_COMMIT = "transaction.commit";
- public final static String TRANSACTION_ROLLBACK = "transaction.rollback";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- String commandId = event.getParameter(PARAM_COMMAND_ID);
- UserTransaction userTransaction = userAdminWrapper.getUserTransaction();
- try {
- if (TRANSACTION_BEGIN.equals(commandId)) {
- if (userTransaction.getStatus() != Status.STATUS_NO_TRANSACTION)
- throw new ArgeoException("A transaction already exists");
- else
- userTransaction.begin();
- } else if (TRANSACTION_COMMIT.equals(commandId)) {
- if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION)
- throw new ArgeoException("No transaction.");
- else
- userTransaction.commit();
- } else if (TRANSACTION_ROLLBACK.equals(commandId)) {
- if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION)
- throw new ArgeoException("No transaction to rollback.");
- else {
- userTransaction.rollback();
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_CHANGED, null));
- }
- }
- UiAdminUtils.notifyTransactionStateChange(userTransaction);
- } catch (ArgeoException e) {
- throw e;
- } catch (Exception e) {
- throw new ArgeoException("Unable to call " + commandId + " on "
- + userTransaction, e);
- }
- return null;
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.editors;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/** Editor input for an Argeo user. */
-public class ArgeoUserEditorInput implements IEditorInput {
- private final String username;
-
- public ArgeoUserEditorInput(String username) {
- this.username = username;
- }
-
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return username != null;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return username != null ? username : "<new user>";
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public String getToolTipText() {
- return username != null ? username : "<new user>";
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof ArgeoUserEditorInput))
- return false;
- if (((ArgeoUserEditorInput) obj).getUsername() == null)
- return false;
- return ((ArgeoUserEditorInput) obj).getUsername().equals(username);
- }
-
- public String getUsername() {
- return username;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.editors;
-
-import java.util.Arrays;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.RepositoryException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.jcr.ArgeoNames;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.SectionPart;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-
-/** Display/edit the properties common to all Argeo users */
-public class DefaultUserMainPage extends FormPage implements ArgeoNames {
- final static String ID = "argeoUserEditor.mainPage";
-
- private final static Log log = LogFactory.getLog(DefaultUserMainPage.class);
- private Node userProfile;
-
- private char[] newPassword;
-
- public DefaultUserMainPage(FormEditor editor, Node userProfile) {
- super(editor, ID, "Main");
- this.userProfile = userProfile;
- }
-
- protected void createFormContent(final IManagedForm mf) {
- try {
- ScrolledForm form = mf.getForm();
- refreshFormTitle(form);
- GridLayout mainLayout = new GridLayout(1, true);
- form.getBody().setLayout(mainLayout);
-
- createGeneralPart(form.getBody());
- createPassworPart(form.getBody());
- } catch (RepositoryException e) {
- throw new ArgeoException("Cannot create form content", e);
- }
- }
-
- /** Creates the general section */
- protected void createGeneralPart(Composite parent)
- throws RepositoryException {
- FormToolkit tk = getManagedForm().getToolkit();
- Section section = tk.createSection(parent, Section.TITLE_BAR);
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- section.setText("General");
- Composite body = tk.createComposite(section, SWT.WRAP);
- section.setClient(body);
- GridLayout layout = new GridLayout(2, false);
- body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- body.setLayout(layout);
-
- final Text commonName = createLT(body, "Displayed Name",
- getProperty(Property.JCR_TITLE));
- final Text firstName = createLT(body, "First name",
- getProperty(ARGEO_FIRST_NAME));
- final Text lastName = createLT(body, "Last name",
- getProperty(ARGEO_LAST_NAME));
- final Text email = createLT(body, "Email",
- getProperty(ARGEO_PRIMARY_EMAIL));
- final Text description = createLMT(body, "Description",
- getProperty(Property.JCR_DESCRIPTION));
-
- // create form part (controller)
- AbstractFormPart part = new SectionPart(section) {
- public void commit(boolean onSave) {
- try {
- userProfile.getSession().getWorkspace().getVersionManager()
- .checkout(userProfile.getPath());
- userProfile.setProperty(Property.JCR_TITLE,
- commonName.getText());
- userProfile.setProperty(ARGEO_FIRST_NAME,
- firstName.getText());
- userProfile
- .setProperty(ARGEO_LAST_NAME, lastName.getText());
- userProfile.setProperty(ARGEO_PRIMARY_EMAIL,
- email.getText());
- userProfile.setProperty(Property.JCR_DESCRIPTION,
- description.getText());
- userProfile.getSession().save();
- userProfile.getSession().getWorkspace().getVersionManager()
- .checkin(userProfile.getPath());
- super.commit(onSave);
- refreshFormTitle(getManagedForm().getForm());
- if (log.isTraceEnabled())
- log.trace("General part committed");
- } catch (RepositoryException e) {
- throw new ArgeoException("Cannot commit", e);
- }
- }
- };
- // if (username != null)
- // username.addModifyListener(new FormPartML(part));
- commonName.addModifyListener(new FormPartML(part));
- firstName.addModifyListener(new FormPartML(part));
- lastName.addModifyListener(new FormPartML(part));
- email.addModifyListener(new FormPartML(part));
- description.addModifyListener(new FormPartML(part));
- getManagedForm().addPart(part);
- }
-
- private void refreshFormTitle(ScrolledForm form) throws RepositoryException {
- form.setText(getProperty(Property.JCR_TITLE)
- + (userProfile.getProperty(ARGEO_ENABLED).getBoolean() ? ""
- : " [DISABLED]"));
- }
-
- /** @return the property, or the empty string if not set */
- protected String getProperty(String name) throws RepositoryException {
- return userProfile.hasProperty(name) ? userProfile.getProperty(name)
- .getString() : "";
- }
-
- /** Creates the password section */
- protected void createPassworPart(Composite parent) {
- FormToolkit tk = getManagedForm().getToolkit();
- Section section = tk.createSection(parent, Section.TITLE_BAR);
- section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- section.setText("Password");
-
- Composite body = tk.createComposite(section, SWT.WRAP);
- section.setClient(body);
- GridLayout layout = new GridLayout(2, false);
- body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- body.setLayout(layout);
-
- // add widgets (view)
- final Text password1 = createLP(body, "New password", "");
- final Text password2 = createLP(body, "Repeat password", "");
- // create form part (controller)
- AbstractFormPart part = new SectionPart(section) {
-
- public void commit(boolean onSave) {
- if (!password1.getText().equals("")
- || !password2.getText().equals("")) {
- if (password1.getText().equals(password2.getText())) {
- newPassword = password1.getText().toCharArray();
- password1.setText("");
- password2.setText("");
- super.commit(onSave);
- } else {
- password1.setText("");
- password2.setText("");
- throw new ArgeoException("Passwords are not equals");
- }
- }
- }
-
- };
- password1.addModifyListener(new FormPartML(part));
- password2.addModifyListener(new FormPartML(part));
- getManagedForm().addPart(part);
- }
-
- /** Creates label and text. */
- protected Text createLT(Composite body, String label, String value) {
- FormToolkit toolkit = getManagedForm().getToolkit();
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return text;
- }
-
- /** Creates label and multiline text. */
- protected Text createLMT(Composite body, String label, String value) {
- FormToolkit toolkit = getManagedForm().getToolkit();
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER | SWT.MULTI);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
- return text;
- }
-
- /** Creates label and password. */
- protected Text createLP(Composite body, String label, String value) {
- FormToolkit toolkit = getManagedForm().getToolkit();
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER | SWT.PASSWORD);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return text;
- }
-
- private class FormPartML implements ModifyListener {
- private static final long serialVersionUID = 6299808129505381333L;
- private AbstractFormPart formPart;
-
- public FormPartML(AbstractFormPart generalPart) {
- this.formPart = generalPart;
- }
-
- public void modifyText(ModifyEvent e) {
- formPart.markDirty();
- }
-
- }
-
- public String getNewPassword() {
- if (newPassword != null)
- return new String(newPassword);
- else
- return null;
- }
-
- public void resetNewPassword() {
- if (newPassword != null)
- Arrays.fill(newPassword, 'x');
- newPassword = null;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.editors;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.jcr.RepositoryException;
-
-import org.argeo.ArgeoException;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.security.ui.admin.internal.ColumnDefinition;
-import org.argeo.security.ui.admin.internal.CommonNameLP;
-import org.argeo.security.ui.admin.internal.MailLP;
-import org.argeo.security.ui.admin.internal.RoleIconLP;
-import org.argeo.security.ui.admin.internal.UserAdminConstants;
-import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.argeo.security.ui.admin.internal.UserNameLP;
-import org.argeo.security.ui.admin.internal.UserTableDefaultDClickListener;
-import org.argeo.security.ui.admin.internal.UserTableViewer;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerDropAdapter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.SectionPart;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Display/edit main properties of a given group */
-public class GroupMainPage extends FormPage implements ArgeoNames {
- final static String ID = "GroupEditor.mainPage";
-
- private final UserEditor editor;
- private UserAdminWrapper userAdminWrapper;
-
- // Local configuration
- private final int PRE_TITLE_INDENT = 10;
-
- public GroupMainPage(FormEditor editor, UserAdminWrapper userAdminWrapper) {
- super(editor, ID, "Main");
- this.editor = (UserEditor) editor;
- this.userAdminWrapper = userAdminWrapper;
- }
-
- protected void createFormContent(final IManagedForm mf) {
- try {
- ScrolledForm form = mf.getForm();
- refreshFormTitle();
-
- // Body
- Composite body = form.getBody();
- GridLayout mainLayout = new GridLayout();
- body.setLayout(mainLayout);
- appendOverviewPart(body);
- appendMembersPart(body);
- } catch (RepositoryException e) {
- throw new ArgeoException("Cannot create form content", e);
- }
- }
-
- /** Creates the general section */
- protected void appendOverviewPart(Composite parent) {
- FormToolkit tk = getManagedForm().getToolkit();
- Composite body = addSection(tk, parent, "Main information");
- GridLayout layout = new GridLayout(2, false);
- body.setLayout(layout);
-
- Text distinguishedName = createLT(body, "Group Name",
- editor.getProperty(UserAdminConstants.KEY_UID));
- distinguishedName.setEnabled(false);
-
- final Text commonName = createLT(body, "Common Name",
- editor.getProperty(UserAdminConstants.KEY_CN));
- commonName.setEnabled(false);
-
- // create form part (controller)
- AbstractFormPart part = new SectionPart((Section) body.getParent()) {
- public void commit(boolean onSave) {
- super.commit(onSave);
- }
- };
- getManagedForm().addPart(part);
- }
-
- /** Filtered table with members. Has drag & drop ability */
- protected void appendMembersPart(Composite parent)
- throws RepositoryException {
-
- FormToolkit tk = getManagedForm().getToolkit();
- Section section = tk.createSection(parent, Section.TITLE_BAR);
- section.setLayoutData(EclipseUiUtils.fillAll());
- section.setText("Members of group "
- + editor.getProperty(UserAdminConstants.KEY_CN));
-
- // Composite body = tk.createComposite(section, SWT.NONE);
- Composite body = new Composite(section, SWT.NO_FOCUS);
- section.setClient(body);
- body.setLayoutData(EclipseUiUtils.fillAll());
-
- createMemberPart(body);
-
- // create form part (controller)
- AbstractFormPart part = new SectionPart(section) {
- public void commit(boolean onSave) {
- super.commit(onSave);
- }
- };
-
- getManagedForm().addPart(part);
- }
-
- // UI Objects
- private UserTableViewer userTableViewerCmp;
- private TableViewer userViewer;
- private List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
-
- public void createMemberPart(Composite parent) {
- parent.setLayout(EclipseUiUtils.noSpaceGridLayout());
- // Define the displayed columns
- columnDefs.add(new ColumnDefinition(new RoleIconLP(), "", 0, 24));
- columnDefs.add(new ColumnDefinition(new UserNameLP(),
- "Distinguished Name", 240));
- columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Common Name",
- 150));
- columnDefs.add(new ColumnDefinition(new MailLP(), "Primary Mail", 150));
-
- // Create and configure the table
- userTableViewerCmp = new MyUserTableViewer(parent, SWT.MULTI
- | SWT.H_SCROLL | SWT.V_SCROLL, userAdminWrapper.getUserAdmin());
-
- userTableViewerCmp.setColumnDefinitions(columnDefs);
- userTableViewerCmp.populate(true, false);
- // userTableViewerCmp.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
- // false, false));
- userTableViewerCmp.setLayoutData(EclipseUiUtils.fillAll());
-
- // Links
- userViewer = userTableViewerCmp.getTableViewer();
- userViewer.addDoubleClickListener(new UserTableDefaultDClickListener());
- // Really?
- userTableViewerCmp.refresh();
-
- // Drag and drop
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- userViewer.addDropSupport(operations, tt,
- new GroupDropListener(userViewer, userAdminWrapper,
- (Group) editor.getDisplayedUser()));
- }
-
- private class MyUserTableViewer extends UserTableViewer {
- private static final long serialVersionUID = 8467999509931900367L;
-
- public MyUserTableViewer(Composite parent, int style,
- UserAdmin userAdmin) {
- super(parent, style, userAdmin, true);
- }
-
- @Override
- protected List<User> listFilteredElements(String filter) {
- Group group = (Group) editor.getDisplayedUser();
- Role[] roles = group.getMembers();
- List<User> users = new ArrayList<User>();
- for (Role role : roles)
- // if (role.getType() == Role.GROUP)
- users.add((User) role);
- return users;
- }
- }
-
- private void refreshFormTitle() throws RepositoryException {
- getManagedForm().getForm().setText(
- editor.getProperty(UserAdminConstants.KEY_CN));
- }
-
- /**
- * Defines this table as being a potential target to add group membership
- * (roles) to this user
- */
- private class GroupDropListener extends ViewerDropAdapter {
- private static final long serialVersionUID = 2893468717831451621L;
-
- private final UserAdminWrapper userAdminWrapper;
- private final Group myGroup;
-
- public GroupDropListener(Viewer viewer,
- UserAdminWrapper userAdminWrapper, Group group) {
- super(viewer);
- this.userAdminWrapper = userAdminWrapper;
- this.myGroup = group;
- }
-
- @Override
- public boolean validateDrop(Object target, int operation,
- TransferData transferType) {
- // Target is always OK in a list only view
- // TODO check if not a string
- boolean validDrop = true;
- return validDrop;
- }
-
- @Override
- public void drop(DropTargetEvent event) {
- // TODO Is there an opportunity to perform ceck before?
-
- String newUserName = (String) event.data;
- UserAdmin myUserAdmin = userAdminWrapper.getUserAdmin();
- Role role = myUserAdmin.getRole(newUserName);
- if (role.getType() == Role.USER) {
- // TODO check if the user is already member of this group
- userAdminWrapper.beginTransactionIfNeeded();
- User user = (User) role;
- myGroup.addMember(user);
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_CHANGED, myGroup));
- } else if (role.getType() == Role.GROUP) {
- Group newGroup = (Group) role;
-
- Shell shell = getViewer().getControl().getShell();
- // Sanity checks
- if (myGroup == newGroup) { // Equality
- MessageDialog.openError(shell, "Forbidden addition ",
- "A group cannot be a member of itself.");
- return;
- }
-
- // Cycle
- String myName = myGroup.getName();
- List<User> myMemberships = editor.getFlatGroups(myGroup);
- if (myMemberships.contains(newGroup)) {
- MessageDialog.openError(shell, "Forbidden addition: cycle",
- "Cannot add " + newUserName + " to group " + myName
- + ". This would create a cycle");
- return;
- }
-
- // Already member
- List<User> newGroupMemberships = editor.getFlatGroups(newGroup);
- if (newGroupMemberships.contains(myGroup)) {
- MessageDialog.openError(shell, "Forbidden addition",
- "Cannot add " + newUserName + " to group " + myName
- + ", this membership already exists");
- return;
- }
-
- userAdminWrapper.beginTransactionIfNeeded();
- // TODO implement the dirty state
- myGroup.addMember(newGroup);
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_CHANGED, myGroup));
- }
- super.drop(event);
- }
-
- @Override
- public boolean performDrop(Object data) {
- userTableViewerCmp.refresh();
- return true;
- }
- }
-
- // LOCAL HELPERS
- private Composite addSection(FormToolkit tk, Composite parent, String title) {
- Section section = tk.createSection(parent, Section.TITLE_BAR);
- GridData gd = EclipseUiUtils.fillWidth();
- gd.verticalAlignment = PRE_TITLE_INDENT;
- section.setLayoutData(gd);
- section.setText(title);
- Composite body = tk.createComposite(section, SWT.WRAP);
- body.setLayoutData(EclipseUiUtils.fillAll());
- section.setClient(body);
- return body;
- }
-
- /** Creates label and text. */
- protected Text createLT(Composite body, String label, String value) {
- FormToolkit toolkit = getManagedForm().getToolkit();
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return text;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.editors;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.argeo.ArgeoException;
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.argeo.security.ui.admin.internal.UserAdminConstants;
-import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.osgi.service.useradmin.Authorization;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Editor for a user, might be a user or a group. */
-public class UserEditor extends FormEditor implements UserAdminConstants {
- private static final long serialVersionUID = 8357851520380820241L;
-
- public final static String ID = SecurityAdminPlugin.PLUGIN_ID
- + ".userEditor";
-
- /* DEPENDENCY INJECTION */
- private UserAdminWrapper userAdminWrapper;
- private UserAdmin userAdmin;
-
- // Context
- private User user;
- private String username;
-
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- super.init(site, input);
- username = ((UserEditorInput) getEditorInput()).getUsername();
- user = (User) userAdmin.getRole(username);
-
- String commonName = getProperty(KEY_CN);
-
- setPartName(commonName != null ? commonName : "username");
-
- // TODO: following has been disabled because it causes NPE after a
- // login/logout on RAP
- // Image titleIcon = user.getType() == Role.GROUP ?
- // SecurityAdminImages.ICON_GROUP
- // : SecurityAdminImages.ICON_USER;
- // setTitleImage(titleIcon);
- }
-
- /**
- * returns the list of all authorisation for the given user or of the
- * current displayed user if parameter is null
- */
- protected List<User> getFlatGroups(User aUser) {
- Authorization currAuth;
- if (aUser == null)
- currAuth = userAdmin.getAuthorization(this.user);
- else
- currAuth = userAdmin.getAuthorization(aUser);
-
- String[] roles = currAuth.getRoles();
-
- List<User> groups = new ArrayList<User>();
- for (String roleStr : roles) {
- User currRole = (User) userAdmin.getRole(roleStr);
- if (!groups.contains(currRole))
- groups.add(currRole);
- }
- return groups;
- }
-
- /** Exposes the user (or group) that is displayed by the current editor */
- protected User getDisplayedUser() {
- return user;
- }
-
- void updateEditorTitle(String title) {
- setPartName(title);
- }
-
- protected void addPages() {
- try {
- if (user.getType() == Role.GROUP)
- addPage(new GroupMainPage(this, userAdminWrapper));
- else
- addPage(new UserMainPage(this, userAdminWrapper));
- } catch (Exception e) {
- throw new ArgeoException("Cannot add pages", e);
- }
- }
-
- protected String getProperty(String key) {
- Object obj = user.getProperties().get(key);
- if (obj != null)
- return (String) obj;
- else
- return "";
- }
-
- /**
- * Updates the property in the working copy. The transaction must be
- * explicitly committed to persist the update.
- */
- @SuppressWarnings("unchecked")
- protected void setProperty(String key, String value) {
- user.getProperties().put(key, value);
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- userAdminWrapper.beginTransactionIfNeeded();
- commitPages(true);
- firePropertyChange(PROP_DIRTY);
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_REMOVED, user));
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- public void refresh() {
-
- }
-
- @Override
- public void dispose() {
- super.dispose();
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
- this.userAdminWrapper = userAdminWrapper;
- this.userAdmin = userAdminWrapper.getUserAdmin();
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.editors;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/**
- * Editor input for an user defined by unique name (usually a distinguished
- * name).
- */
-public class UserEditorInput implements IEditorInput {
- private final String username;
-
- public UserEditorInput(String username) {
- this.username = username;
- }
-
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- public boolean exists() {
- return username != null;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- public String getName() {
- return username != null ? username : "<new user>";
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public String getToolTipText() {
- return username != null ? username : "<new user>";
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof UserEditorInput))
- return false;
- if (((UserEditorInput) obj).getUsername() == null)
- return false;
- return ((UserEditorInput) obj).getUsername().equals(username);
- }
-
- public String getUsername() {
- return username;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.editors;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.argeo.ArgeoException;
-import org.argeo.eclipse.ui.EclipseUiUtils;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.security.ui.admin.internal.ColumnDefinition;
-import org.argeo.security.ui.admin.internal.CommonNameLP;
-import org.argeo.security.ui.admin.internal.RoleIconLP;
-import org.argeo.security.ui.admin.internal.UserAdminConstants;
-import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.argeo.security.ui.admin.internal.UserNameLP;
-import org.argeo.security.ui.admin.internal.UserTableDefaultDClickListener;
-import org.argeo.security.ui.admin.internal.UserTableViewer;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerDropAdapter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.SectionPart;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.osgi.service.useradmin.Group;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-import org.osgi.service.useradmin.UserAdminEvent;
-
-/** Display/edit the properties common to all users */
-public class UserMainPage extends FormPage implements ArgeoNames {
- final static String ID = "argeoUserEditor.mainPage";
-
- // private final static Log log = LogFactory.getLog(UserMainPage.class);
-
- private final UserEditor editor;
- private UserAdminWrapper userAdminWrapper;
-
- private char[] newPassword;
-
- // Local configuration
- private final int PRE_TITLE_INDENT = 10;
-
- public UserMainPage(FormEditor editor, UserAdminWrapper userAdminWrapper) {
- super(editor, ID, "Main");
- this.editor = (UserEditor) editor;
- this.userAdminWrapper = userAdminWrapper;
- }
-
- public String getNewPassword() {
- if (newPassword != null)
- return new String(newPassword);
- else
- return null;
- }
-
- public void resetNewPassword() {
- if (newPassword != null)
- Arrays.fill(newPassword, 'x');
- newPassword = null;
- }
-
- protected void createFormContent(final IManagedForm mf) {
- ScrolledForm form = mf.getForm();
- // Form page main title
- form.setText(editor.getProperty(UserAdminConstants.KEY_CN));
-
- // Body
- Composite body = form.getBody();
- GridLayout mainLayout = new GridLayout(1, true);
- body.setLayout(mainLayout);
- appendOverviewPart(body);
- appendPasswordPart(body);
- appendMemberOfPart(body);
- }
-
- /** Creates the general section */
- protected void appendOverviewPart(Composite parent) {
- FormToolkit tk = getManagedForm().getToolkit();
- Composite body = addSection(tk, parent, "Main information");
- body.setLayout(new GridLayout(2, false));
-
- Text distinguishedName = createLT(body, "User Name",
- editor.getProperty(UserAdminConstants.KEY_UID));
- distinguishedName.setEnabled(false);
-
- final Text commonName = createLT(body, "Common Name",
- editor.getProperty(UserAdminConstants.KEY_CN));
- commonName.setEnabled(false);
-
- final Text firstName = createLT(body, "First name",
- editor.getProperty(UserAdminConstants.KEY_FIRSTNAME));
-
- final Text lastName = createLT(body, "Last name",
- editor.getProperty(UserAdminConstants.KEY_LASTNAME));
-
- final Text email = createLT(body, "Email",
- editor.getProperty(UserAdminConstants.KEY_MAIL));
-
- // create form part (controller)
- AbstractFormPart part = new SectionPart((Section) body.getParent()) {
- public void commit(boolean onSave) {
- // TODO check changed ?
- // TODO Sanity checks
-
- editor.setProperty(UserAdminConstants.KEY_FIRSTNAME,
- firstName.getText());
- editor.setProperty(UserAdminConstants.KEY_LASTNAME,
- lastName.getText());
- editor.setProperty(UserAdminConstants.KEY_CN,
- commonName.getText());
- // TODO check mail validity
- editor.setProperty(UserAdminConstants.KEY_MAIL, email.getText());
-
- // Enable common name ?
- // editor.setProperty(UserAdminConstants.KEY_CN,
- // email.getText());
- super.commit(onSave);
- }
- };
-
- ModifyListener cnML = new ModifyListener() {
- private static final long serialVersionUID = 4298649222869835486L;
-
- @Override
- public void modifyText(ModifyEvent event) {
- String first = firstName.getText();
- String last = lastName.getText();
- String cn = first.trim() + " " + last.trim() + " ";
- cn = cn.trim();
- commonName.setText(cn);
- getManagedForm().getForm().setText(cn);
- editor.updateEditorTitle(cn);
- }
- };
- firstName.addModifyListener(cnML);
- lastName.addModifyListener(cnML);
- firstName.addModifyListener(new FormPartML(part));
- lastName.addModifyListener(new FormPartML(part));
- email.addModifyListener(new FormPartML(part));
- getManagedForm().addPart(part);
- }
-
- /** Creates the password section */
- protected void appendPasswordPart(Composite parent) {
- FormToolkit tk = getManagedForm().getToolkit();
- Composite body = addSection(tk, parent, "Password");
-
- // Section section = tk.createSection(parent, Section.TITLE_BAR);
- // section.setLayoutData(EclipseUiUtils.fillWidth());
- // section.setText("Password");
- // Composite body = tk.createComposite(section, SWT.NO_FOCUS);
- // section.setClient(body);
- // body.setLayoutData(EclipseUiUtils.fillWidth());
-
- body.setLayout(new GridLayout(2, false));
- // add widgets (view)
- final Text password1 = createLP(body, "New password", "");
- final Text password2 = createLP(body, "Repeat password", "");
- // create form part (controller)
- AbstractFormPart part = new SectionPart((Section) body.getParent()) {
-
- public void commit(boolean onSave) {
- if (!password1.getText().equals("")
- || !password2.getText().equals("")) {
- if (password1.getText().equals(password2.getText())) {
- newPassword = password1.getText().toCharArray();
- // TODO real set password
- password1.setText("");
- password2.setText("");
- super.commit(onSave);
- } else {
- password1.setText("");
- password2.setText("");
- throw new ArgeoException("Passwords are not equals");
- }
- }
- }
-
- };
- password1.addModifyListener(new FormPartML(part));
- password2.addModifyListener(new FormPartML(part));
- getManagedForm().addPart(part);
- }
-
- private UserTableViewer userTableViewerCmp;
- private TableViewer userViewer;
-
- private void appendMemberOfPart(Composite parent) {
- FormToolkit tk = getManagedForm().getToolkit();
- Composite body = addSection(tk, parent, "Roles");
- body.setLayout(EclipseUiUtils.noSpaceGridLayout());
-
- // Define the displayed columns
- List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
- columnDefs.add(new ColumnDefinition(new RoleIconLP(), "", 0, 24));
- columnDefs.add(new ColumnDefinition(new UserNameLP(),
- "Distinguished Name", 300));
- columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Common Name",
- 150));
-
- // Create and configure the table
- userTableViewerCmp = new MyUserTableViewer(body, SWT.MULTI
- | SWT.H_SCROLL | SWT.V_SCROLL, userAdminWrapper.getUserAdmin());
-
- userTableViewerCmp.setColumnDefinitions(columnDefs);
- userTableViewerCmp.populate(true, false);
- GridData gd = EclipseUiUtils.fillAll();
- gd.heightHint = 300;
- userTableViewerCmp.setLayoutData(gd);
-
- // Links
- userViewer = userTableViewerCmp.getTableViewer();
- userViewer.addDoubleClickListener(new UserTableDefaultDClickListener());
- // Really?
- userTableViewerCmp.refresh();
-
- // Drag and drop
- int operations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
- userViewer.addDropSupport(operations, tt, new GroupDropListener(
- userViewer, userAdminWrapper.getUserAdmin(), editor.getDisplayedUser()));
-
- }
-
- private class MyUserTableViewer extends UserTableViewer {
- private static final long serialVersionUID = 8467999509931900367L;
-
- public MyUserTableViewer(Composite parent, int style,
- UserAdmin userAdmin) {
- super(parent, style, userAdmin, true);
- }
-
- @Override
- protected List<User> listFilteredElements(String filter) {
- return (List<User>) editor.getFlatGroups(null);
- }
- }
-
- /**
- * Defines this table as being a potential target to add group membership
- * (roles) to this user
- */
- private class GroupDropListener extends ViewerDropAdapter {
- private static final long serialVersionUID = 2893468717831451621L;
-
- private final UserAdmin myUserAdmin;
- private final User myUser;
-
- public GroupDropListener(Viewer viewer, UserAdmin userAdmin, User user) {
- super(viewer);
- this.myUserAdmin = userAdmin;
- this.myUser = user;
- }
-
- @Override
- public boolean validateDrop(Object target, int operation,
- TransferData transferType) {
- // Target is always OK in a list only view
- // TODO check if not a string
- boolean validDrop = true;
- return validDrop;
- }
-
- @Override
- public void drop(DropTargetEvent event) {
- String name = (String) event.data;
- Role role = myUserAdmin.getRole(name);
- // TODO this check should be done before.
- if (role.getType() == Role.GROUP) {
- // TODO check if the user is already member of this group
- userAdminWrapper.beginTransactionIfNeeded();
- Group group = (Group) role;
- group.addMember(myUser);
- userAdminWrapper.notifyListeners(new UserAdminEvent(null,
- UserAdminEvent.ROLE_CHANGED, group));
- }
- super.drop(event);
- }
-
- @Override
- public boolean performDrop(Object data) {
- userTableViewerCmp.refresh();
- return true;
- }
- }
-
- // LOCAL HELPERS
- /** Appends a section with a title */
- private Composite addSection(FormToolkit tk, Composite parent, String title) {
- Section section = tk.createSection(parent, Section.TITLE_BAR);
- GridData gd = EclipseUiUtils.fillWidth();
- gd.verticalAlignment = PRE_TITLE_INDENT;
- section.setLayoutData(gd);
- section.setText(title);
- Composite body = tk.createComposite(section, SWT.WRAP);
- body.setLayoutData(EclipseUiUtils.fillAll());
- section.setClient(body);
- return body;
- }
-
- /** Creates label and multiline text. */
- protected Text createLMT(Composite body, String label, String value) {
- FormToolkit toolkit = getManagedForm().getToolkit();
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER | SWT.MULTI);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
- return text;
- }
-
- /** Creates label and password. */
- protected Text createLP(Composite body, String label, String value) {
- FormToolkit toolkit = getManagedForm().getToolkit();
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER | SWT.PASSWORD);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return text;
- }
-
- /** Creates label and text. */
- protected Text createLT(Composite body, String label, String value) {
- FormToolkit toolkit = getManagedForm().getToolkit();
- Label lbl = toolkit.createLabel(body, label);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- Text text = toolkit.createText(body, value, SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return text;
- }
-
- private class FormPartML implements ModifyListener {
- private static final long serialVersionUID = 6299808129505381333L;
- private AbstractFormPart formPart;
-
- public FormPartML(AbstractFormPart generalPart) {
- this.formPart = generalPart;
- }
-
- public void modifyText(ModifyEvent e) {
- formPart.markDirty();
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.editors;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.security.UserAdminService;
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.CheckboxCellEditor;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.forms.AbstractFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.userdetails.UserDetails;
-
-/**
- * Display/edit the roles of a user.
- */
-public class UserRolesPage extends FormPage implements ArgeoNames {
- final static String ID = "argeoUserEditor.rolesPage";
-
- private final static Log log = LogFactory.getLog(UserRolesPage.class);
- private final static Image ROLE_CHECKED = SecurityAdminPlugin
- .getImageDescriptor("icons/security.gif").createImage();
-
- private TableViewer rolesViewer;
- private UserAdminService userAdminService;
- private List<String> roles;
-
- public UserRolesPage(FormEditor editor, UserDetails userDetails,
- UserAdminService userAdminService) {
- super(editor, ID, "Roles");
- setUserDetails(userDetails);
- this.userAdminService = userAdminService;
- }
-
- public void setUserDetails(UserDetails userDetails) {
- this.roles = new ArrayList<String>();
- for (GrantedAuthority ga : userDetails.getAuthorities())
- roles.add(ga.getAuthority());
- if (rolesViewer != null)
- rolesViewer.refresh();
- }
-
- protected void createFormContent(final IManagedForm mf) {
- ScrolledForm form = mf.getForm();
- form.setText("Roles");
- FillLayout mainLayout = new FillLayout();
- // ColumnLayout mainLayout = new ColumnLayout();
- // mainLayout.minNumColumns = 1;
- // mainLayout.maxNumColumns = 4;
- // mainLayout.topMargin = 0;
- // mainLayout.bottomMargin = 5;
- // mainLayout.leftMargin = mainLayout.rightMargin =
- // mainLayout.horizontalSpacing = mainLayout.verticalSpacing = 10;
- form.getBody().setLayout(mainLayout);
- createRolesPart(form.getBody());
- }
-
- /** Creates the role section */
- protected void createRolesPart(Composite parent) {
- Table table = new Table(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
-
- AbstractFormPart part = new AbstractFormPart() {
- public void commit(boolean onSave) {
- // roles have already been modified in editing
- super.commit(onSave);
- if (log.isTraceEnabled())
- log.trace("Role part committed");
- }
- };
- getManagedForm().addPart(part);
-
- // GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
- // gridData.verticalSpan = 20;
- // table.setLayoutData(gridData);
- table.setLinesVisible(true);
- table.setHeaderVisible(false);
- rolesViewer = new TableViewer(table);
-
- // check column
- TableViewerColumn column = createTableViewerColumn(rolesViewer,
- "checked", 20);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = -1354458151271666525L;
-
- public String getText(Object element) {
- return null;
- }
-
- public Image getImage(Object element) {
- String role = element.toString();
- if (roles.contains(role)) {
- return ROLE_CHECKED;
- } else {
- return null;
- }
- }
- });
- column.setEditingSupport(new RoleEditingSupport(rolesViewer, part));
-
- // role column
- column = createTableViewerColumn(rolesViewer, "Role", 200);
- column.setLabelProvider(new ColumnLabelProvider() {
- private static final long serialVersionUID = 2968056181744306838L;
-
- public String getText(Object element) {
- return element.toString();
- }
-
- public Image getImage(Object element) {
- return null;
- }
- });
- rolesViewer.setContentProvider(new RolesContentProvider());
- rolesViewer.setInput(getEditorSite());
- }
-
- protected TableViewerColumn createTableViewerColumn(TableViewer viewer,
- String title, int bound) {
- final TableViewerColumn viewerColumn = new TableViewerColumn(viewer,
- SWT.NONE);
- final TableColumn column = viewerColumn.getColumn();
- column.setText(title);
- column.setWidth(bound);
- column.setResizable(true);
- column.setMoveable(true);
- return viewerColumn;
-
- }
-
- public List<String> getRoles() {
- return roles;
- }
-
- public void refresh() {
- rolesViewer.refresh();
- }
-
- private class RolesContentProvider implements IStructuredContentProvider {
- private static final long serialVersionUID = -1882254608698512781L;
-
- public Object[] getElements(Object inputElement) {
- return userAdminService.listEditableRoles().toArray();
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
-
- /** Select the columns by editing the checkbox in the first column */
- class RoleEditingSupport extends EditingSupport {
- private static final long serialVersionUID = 4041402007711754376L;
- private final TableViewer viewer;
- private final AbstractFormPart formPart;
-
- public RoleEditingSupport(TableViewer viewer, AbstractFormPart formPart) {
- super(viewer);
- this.viewer = viewer;
- this.formPart = formPart;
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
-
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return true;
- }
-
- @Override
- protected Object getValue(Object element) {
- String role = element.toString();
- return roles.contains(role);
-
- }
-
- @Override
- protected void setValue(Object element, Object value) {
- Boolean inRole = (Boolean) value;
- String role = element.toString();
- if (inRole && !roles.contains(role)) {
- roles.add(role);
- formPart.markDirty();
- } else if (!inRole && roles.contains(role)) {
- roles.remove(role);
- formPart.markDirty();
- }
- viewer.refresh();
- }
- }
-
-}
+++ /dev/null
-package org.argeo.security.ui.admin.internal;
-
-import org.osgi.service.useradmin.User;
-
-/** Simply declare a label provider that returns the common name of a user */
-public class CommonNameLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 5256703081044911941L;
-
- @Override
- public String getText(User user) {
- Object obj = user.getProperties().get(KEY_CN);
- if (obj != null)
- return (String) obj;
- else
- return "";
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.security.ui.admin.internal;
-
-import org.osgi.service.useradmin.User;
-
-/** Simply declare a label provider that returns the Primary Mail for a user */
-public class MailLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 8329764452141982707L;
-
- @Override
- public String getText(User user) {
- Object obj = user.getProperties().get(KEY_MAIL);
- if (obj != null)
- return (String) obj;
- else
- return "";
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.security.ui.admin.internal;
-
-import org.argeo.security.ui.admin.SecurityAdminImages;
-import org.eclipse.swt.graphics.Image;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.User;
-
-public class RoleIconLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 6550449442061090388L;
-
- @Override
- public String getText(User user) {
- return "";
- }
-
- @Override
- public Image getImage(Object element) {
- User user = (User) element;
- if (user.getType() == Role.GROUP)
- return SecurityAdminImages.ICON_GROUP;
- else
- return SecurityAdminImages.ICON_USER;
- }
-}
\ No newline at end of file
import javax.transaction.UserTransaction;
import org.argeo.ArgeoException;
+import org.argeo.security.ui.admin.internal.providers.UserTransactionProvider;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.services.ISourceProviderService;
+++ /dev/null
-package org.argeo.security.ui.admin.internal;
-
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.widgets.Display;
-import org.osgi.service.useradmin.User;
-
-/**
- * Utility class that add font modifications to a column label provider
- * depending on the given user properties
- */
-public abstract class UserAdminAbstractLP extends ColumnLabelProvider implements
- UserAdminConstants {
- private static final long serialVersionUID = 137336765024922368L;
-
- // private Font italic;
- private Font bold;
-
- @Override
- public Font getFont(Object element) {
- // Self as bold
- try {
- LdapName selfUserName = UiAdminUtils.getLdapName();
- String userName = UiAdminUtils.getProperty((User) element,
- UserAdminConstants.KEY_DN);
- LdapName userLdapName = new LdapName(userName);
- if (userLdapName.equals(selfUserName))
- return bold;
- } catch (InvalidNameException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- // Disabled as Italic
- // Node userProfile = (Node) elem;
- // if (!userProfile.getProperty(ARGEO_ENABLED).getBoolean())
- // return italic;
-
- return null;
- // return super.getFont(element);
- }
-
- @Override
- public String getText(Object element) {
- User user = (User) element;
- return getText(user);
- }
-
- public void setDisplay(Display display) {
- // italic = JFaceResources.getFontRegistry().defaultFontDescriptor()
- // .setStyle(SWT.ITALIC).createFont(display);
- bold = JFaceResources.getFontRegistry().defaultFontDescriptor()
- .setStyle(SWT.BOLD).createFont(display);
- }
-
- public abstract String getText(User user);
-}
+++ /dev/null
-package org.argeo.security.ui.admin.internal;
-
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.osgi.service.useradmin.User;
-
-public class UserDragListener implements DragSourceListener {
- private static final long serialVersionUID = -2074337775033781454L;
- private final Viewer viewer;
-
- public UserDragListener(Viewer viewer) {
- this.viewer = viewer;
- }
-
- public void dragStart(DragSourceEvent event) {
- // TODO implement finer checks
- IStructuredSelection selection = (IStructuredSelection) viewer
- .getSelection();
- if (selection.isEmpty() || selection.size() > 1)
- event.doit = false;
- else
- event.doit = true;
- }
-
- public void dragSetData(DragSourceEvent event) {
- // TODO Support multiple selection
- Object obj = ((IStructuredSelection) viewer.getSelection())
- .getFirstElement();
- if (obj != null) {
- User user = (User) obj;
- event.data = user.getName();
- }
- }
-
- public void dragFinished(DragSourceEvent event) {
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.security.ui.admin.internal;
-
-import org.osgi.service.useradmin.User;
-
-/** Simply declare a label provider that returns the username of a user */
-public class UserNameLP extends UserAdminAbstractLP {
- private static final long serialVersionUID = 6550449442061090388L;
-
- @Override
- public String getText(User user) {
- return user.getName();
- }
-}
+++ /dev/null
-package org.argeo.security.ui.admin.internal;
-
-import org.argeo.ArgeoException;
-import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
-import org.argeo.security.ui.admin.editors.UserEditor;
-import org.argeo.security.ui.admin.editors.UserEditorInput;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.osgi.service.useradmin.User;
-
-/**
- * Default double click listener for the various user tables, will open the
- * clicked item in the editor
- */
-public class UserTableDefaultDClickListener implements IDoubleClickListener {
- public void doubleClick(DoubleClickEvent evt) {
- if (evt.getSelection().isEmpty())
- return;
- Object obj = ((IStructuredSelection) evt.getSelection())
- .getFirstElement();
- User user = (User) obj;
- // IWorkbench iw =
- IWorkbenchWindow iww = WorkbenchUiPlugin.getDefault().getWorkbench()
- .getActiveWorkbenchWindow();
- IWorkbenchPage iwp = iww.getActivePage();
- UserEditorInput uei = new UserEditorInput(user.getName());
-
- try {
- // IEditorPart editor =
- iwp.openEditor(uei, UserEditor.ID);
- } catch (PartInitException pie) {
- throw new ArgeoException("Unable to open UserEditor for " + user,
- pie);
- }
- }
-}
\ No newline at end of file
import org.argeo.ArgeoException;
import org.argeo.eclipse.ui.EclipseUiUtils;
import org.argeo.eclipse.ui.utils.ViewerUtils;
+import org.argeo.security.ui.admin.internal.providers.UserAdminAbstractLP;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnLabelProvider;
+++ /dev/null
-package org.argeo.security.ui.admin.internal;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.transaction.Status;
-import javax.transaction.UserTransaction;
-
-import org.argeo.ArgeoException;
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.eclipse.ui.AbstractSourceProvider;
-import org.eclipse.ui.ISources;
-
-/** Notifies the UI on UserTransaction state change */
-public class UserTransactionProvider extends AbstractSourceProvider {
- public final static String TRANSACTION_STATE = SecurityAdminPlugin.PLUGIN_ID
- + ".userTransactionState";
- public final static String STATUS_ACTIVE = "status.active";
- public final static String STATUS_NO_TRANSACTION = "status.noTransaction";
-
- /* DEPENDENCY INJECTION */
- private UserTransaction userTransaction;
-
- @Override
- public String[] getProvidedSourceNames() {
- return new String[] { TRANSACTION_STATE };
- }
-
- @Override
- public Map<String, String> getCurrentState() {
- Map<String, String> currentState = new HashMap<String, String>(1);
- currentState.put(TRANSACTION_STATE, getInternalCurrentState());
- return currentState;
- }
-
- @Override
- public void dispose() {
- }
-
- private String getInternalCurrentState() {
- try {
- String transactionState;
- if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION)
- transactionState = STATUS_NO_TRANSACTION;
- else
- // if (userTransaction.getStatus() == Status.STATUS_ACTIVE)
- transactionState = STATUS_ACTIVE;
- return transactionState;
- } catch (Exception e) {
- throw new ArgeoException("Unable to begin transaction", e);
- }
- }
-
- /** Publish the ability to notify a state change */
- public void fireTransactionStateChange() {
- fireSourceChanged(ISources.WORKBENCH, TRANSACTION_STATE,
- getInternalCurrentState());
- }
-
- /* DEPENDENCY INJECTION */
- public void setUserTransaction(UserTransaction userTransaction) {
- this.userTransaction = userTransaction;
- }
-}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.commands;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.argeo.security.ui.admin.internal.UiAdminUtils;
+import org.argeo.security.ui.admin.internal.UserAdminWrapper;
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.osgi.service.useradmin.Group;
+import org.osgi.service.useradmin.UserAdmin;
+import org.osgi.service.useradmin.UserAdminEvent;
+
+/** Deletes the selected groups */
+public class DeleteGroups extends AbstractHandler {
+ public final static String ID = SecurityAdminPlugin.PLUGIN_ID
+ + ".deleteGroups";
+
+ /* DEPENDENCY INJECTION */
+ private UserAdminWrapper userAdminWrapper;
+
+ @SuppressWarnings("unchecked")
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection selection = HandlerUtil.getCurrentSelection(event);
+ if (selection.isEmpty())
+ return null;
+
+ List<Group> groups = new ArrayList<Group>();
+ Iterator<Group> it = ((IStructuredSelection) selection).iterator();
+ StringBuilder builder = new StringBuilder();
+ while (it.hasNext()) {
+ Group currGroup = it.next();
+ String groupName = UiAdminUtils.getUsername(currGroup);
+ // TODO add checks
+ builder.append(groupName).append("; ");
+ groups.add(currGroup);
+ }
+
+ if (!MessageDialog.openQuestion(HandlerUtil.getActiveShell(event),
+ "Delete Groups",
+ "Are you sure that you " + "want to delete these groups?\n"
+ + builder.substring(0, builder.length() - 2)))
+ return null;
+
+ userAdminWrapper.beginTransactionIfNeeded();
+ UserAdmin userAdmin = userAdminWrapper.getUserAdmin();
+ for (Group group : groups) {
+ userAdmin.removeRole(group.getName());
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_REMOVED, group));
+ }
+ return null;
+ }
+
+ /* DEPENDENCY INJECTION */
+ public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
+ this.userAdminWrapper = userAdminWrapper;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.commands;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.argeo.security.ui.admin.internal.UiAdminUtils;
+import org.argeo.security.ui.admin.internal.UserAdminWrapper;
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.osgi.service.useradmin.User;
+import org.osgi.service.useradmin.UserAdmin;
+import org.osgi.service.useradmin.UserAdminEvent;
+
+/** Deletes the selected users */
+public class DeleteUsers extends AbstractHandler {
+ public final static String ID = SecurityAdminPlugin.PLUGIN_ID
+ + ".deleteUsers";
+
+ /* DEPENDENCY INJECTION */
+ private UserAdminWrapper userAdminWrapper;
+
+ @SuppressWarnings("unchecked")
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection selection = HandlerUtil.getCurrentSelection(event);
+ if (selection.isEmpty())
+ return null;
+
+ Iterator<User> it = ((IStructuredSelection) selection).iterator();
+ List<User> users = new ArrayList<User>();
+ StringBuilder builder = new StringBuilder();
+
+ while (it.hasNext()) {
+ User currUser = it.next();
+ String userName = UiAdminUtils.getUsername(currUser);
+ if (UiAdminUtils.isCurrentUser(currUser)) {
+ MessageDialog.openError(HandlerUtil.getActiveShell(event),
+ "Deletion forbidden",
+ "You cannot delete your own user this way.");
+ return null;
+ }
+ builder.append(userName).append("; ");
+ users.add(currUser);
+ }
+
+ if (!MessageDialog.openQuestion(
+ HandlerUtil.getActiveShell(event),
+ "Delete Users",
+ "Are you sure that you want to delete these users?\n"
+ + builder.substring(0, builder.length() - 2)))
+ return null;
+
+ userAdminWrapper.beginTransactionIfNeeded();
+ UserAdmin userAdmin = userAdminWrapper.getUserAdmin();
+ for (User user : users) {
+ userAdmin.removeRole(user.getName());
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_REMOVED, user));
+ }
+ return null;
+ }
+
+ /* DEPENDENCY INJECTION */
+ public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
+ this.userAdminWrapper = userAdminWrapper;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.commands;
+
+import org.argeo.security.ui.admin.internal.parts.GroupsView;
+import org.argeo.security.ui.admin.internal.parts.UsersView;
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+/** Retrieve the active view or editor and call forceRefresh method if defined */
+public class ForceRefresh extends AbstractHandler {
+
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IWorkbenchWindow iww = HandlerUtil.getActiveWorkbenchWindow(event);
+ if (iww == null)
+ return null;
+ IWorkbenchPage activePage = iww.getActivePage();
+ IWorkbenchPart part = activePage.getActivePart();
+ if (part instanceof UsersView)
+ ((UsersView) part).refresh();
+ else if (part instanceof GroupsView)
+ ((GroupsView) part).refresh();
+ return null;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.commands;
+
+import java.util.Dictionary;
+
+import org.argeo.eclipse.ui.EclipseUiUtils;
+import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.argeo.security.ui.admin.internal.UiAdminUtils;
+import org.argeo.security.ui.admin.internal.UserAdminConstants;
+import org.argeo.security.ui.admin.internal.UserAdminWrapper;
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.osgi.service.useradmin.Group;
+import org.osgi.service.useradmin.Role;
+import org.osgi.service.useradmin.UserAdmin;
+import org.osgi.service.useradmin.UserAdminEvent;
+
+/** Create a new group. */
+public class NewGroup extends AbstractHandler {
+ public final static String ID = SecurityAdminPlugin.PLUGIN_ID + ".newGroup";
+
+ /* DEPENDENCY INJECTION */
+ private UserAdminWrapper userAdminWrapper;
+ private UserAdmin userAdmin;
+
+ // TODO implement a dynamic choice of the base dn
+ private String getDn(String cn) {
+ return "cn=" + cn + ",dc=example,dc=com";
+ }
+
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ NewGroupWizard newGroupWizard = new NewGroupWizard();
+ WizardDialog dialog = new WizardDialog(
+ HandlerUtil.getActiveShell(event), newGroupWizard);
+ dialog.setTitle("Create a new group");
+ dialog.open();
+ return null;
+ }
+
+ private class NewGroupWizard extends Wizard {
+
+ // pages
+ private MainGroupInfoWizardPage mainGroupInfo;
+
+ // End user fields
+ private Text dNameTxt, commonNameTxt, descriptionTxt;
+
+ public NewGroupWizard() {
+ }
+
+ @Override
+ public void addPages() {
+ mainGroupInfo = new MainGroupInfoWizardPage();
+ addPage(mainGroupInfo);
+
+ setWindowTitle("Create a new group");
+ // mainGroupInfo.setMessage(message, WizardPage.WARNING);
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Override
+ public boolean performFinish() {
+ if (!canFinish())
+ return false;
+ String commonName = commonNameTxt.getText();
+ try {
+ userAdminWrapper.beginTransactionIfNeeded();
+ Group group = (Group) userAdmin.createRole(getDn(commonName),
+ Role.GROUP);
+ Dictionary props = group.getProperties();
+ String descStr = descriptionTxt.getText();
+ if (UiAdminUtils.notNull(descStr))
+ props.put(UserAdminConstants.KEY_DESC, descStr);
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_CREATED, group));
+ return true;
+ } catch (Exception e) {
+ ErrorFeedback.show("Cannot create new group " + commonName, e);
+ return false;
+ }
+ }
+
+ private class MainGroupInfoWizardPage extends WizardPage implements
+ ModifyListener, ArgeoNames {
+ private static final long serialVersionUID = -3150193365151601807L;
+
+ public MainGroupInfoWizardPage() {
+ super("Main");
+ setTitle("General information");
+ setMessage("Please provide a common name and a free description");
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite bodyCmp = new Composite(parent, SWT.NONE);
+ bodyCmp.setLayout(new GridLayout(2, false));
+ dNameTxt = EclipseUiUtils.createGridLT(bodyCmp,
+ "Distinguished name", this);
+ dNameTxt.setEnabled(false);
+ commonNameTxt = EclipseUiUtils.createGridLT(bodyCmp,
+ "Common name", this);
+ commonNameTxt.addModifyListener(new ModifyListener() {
+ private static final long serialVersionUID = -1435351236582736843L;
+
+ @Override
+ public void modifyText(ModifyEvent event) {
+ String name = commonNameTxt.getText();
+ if (name.trim().equals("")) {
+ dNameTxt.setText("");
+ } else {
+ dNameTxt.setText(getDn(name));
+ }
+ }
+ });
+
+ Label descLbl = new Label(bodyCmp, SWT.LEAD);
+ descLbl.setText("Description");
+ descLbl.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false,
+ false));
+ descriptionTxt = new Text(bodyCmp, SWT.LEAD | SWT.MULTI
+ | SWT.WRAP | SWT.BORDER);
+ descriptionTxt.setLayoutData(EclipseUiUtils.fillAll());
+ descriptionTxt.addModifyListener(this);
+
+ setControl(bodyCmp);
+
+ // Initialize buttons
+ setPageComplete(false);
+ getContainer().updateButtons();
+ }
+
+ @Override
+ public void modifyText(ModifyEvent event) {
+ String message = checkComplete();
+ if (message != null) {
+ setMessage(message, WizardPage.ERROR);
+ setPageComplete(false);
+ } else {
+ setMessage("Complete", WizardPage.INFORMATION);
+ setPageComplete(true);
+ }
+ getContainer().updateButtons();
+ }
+
+ /** @return error message or null if complete */
+ protected String checkComplete() {
+ String name = commonNameTxt.getText();
+
+ if (name.trim().equals(""))
+ return "Common name must not be empty";
+ Role role = userAdmin.getRole(getDn(name));
+ if (role != null)
+ return "Group " + name + " already exists";
+ return null;
+ }
+
+ @Override
+ public void setVisible(boolean visible) {
+ super.setVisible(visible);
+ if (visible)
+ commonNameTxt.setFocus();
+ }
+ }
+ }
+
+ /* DEPENDENCY INJECTION */
+ public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
+ this.userAdminWrapper = userAdminWrapper;
+ this.userAdmin = userAdminWrapper.getUserAdmin();
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.commands;
+
+import java.util.Dictionary;
+
+import org.argeo.eclipse.ui.EclipseUiUtils;
+import org.argeo.eclipse.ui.dialogs.ErrorFeedback;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.security.UserAdminService;
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.argeo.security.ui.admin.internal.UiAdminUtils;
+import org.argeo.security.ui.admin.internal.UserAdminConstants;
+import org.argeo.security.ui.admin.internal.UserAdminWrapper;
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.osgi.service.useradmin.Role;
+import org.osgi.service.useradmin.User;
+import org.osgi.service.useradmin.UserAdminEvent;
+
+/** Open a wizard that enables creation of a new user. */
+public class NewUser extends AbstractHandler {
+ // private final static Log log = LogFactory.getLog(NewUser.class);
+ public final static String ID = SecurityAdminPlugin.PLUGIN_ID + ".newUser";
+
+ /* DEPENDENCY INJECTION */
+ private UserAdminWrapper userAdminWrapper;
+
+ // TODO implement a dynamic choice of the base dn
+ private String getDn(String uid) {
+ return "uid=" + uid + ",ou=users,dc=example,dc=com";
+ }
+
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ NewUserWizard newUserWizard = new NewUserWizard();
+ WizardDialog dialog = new WizardDialog(
+ HandlerUtil.getActiveShell(event), newUserWizard);
+
+ dialog.open();
+
+ // // Force refresh until the listener are implemented
+ // if (Window.OK == dialog.open())
+ // forceRefresh(event);
+ return null;
+ }
+
+ // private void forceRefresh(ExecutionEvent event) {
+ // IWorkbenchWindow iww = HandlerUtil.getActiveWorkbenchWindow(event);
+ // if (iww == null)
+ // return;
+ // IWorkbenchPage activePage = iww.getActivePage();
+ // IWorkbenchPart part = activePage.getActivePart();
+ // if (part instanceof UsersView)
+ // ((UsersView) part).refresh();
+ // }
+
+ private class NewUserWizard extends Wizard {
+
+ // pages
+ private MainUserInfoWizardPage mainUserInfo;
+
+ // End user fields
+ private Text dNameTxt, usernameTxt, firstNameTxt, lastNameTxt,
+ primaryMailTxt, pwd1Txt, pwd2Txt;
+
+ public NewUserWizard() {
+ }
+
+ @Override
+ public void addPages() {
+ mainUserInfo = new MainUserInfoWizardPage();
+ addPage(mainUserInfo);
+ String message = "Dummy wizard to ease user creation tests:\n Mail and last name are automatically "
+ + "generated form the uid. Password are defauted to 'demo'.";
+ mainUserInfo.setMessage(message, WizardPage.WARNING);
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Override
+ public boolean performFinish() {
+ if (!canFinish())
+ return false;
+ String username = mainUserInfo.getUsername();
+ try {
+ userAdminWrapper.beginTransactionIfNeeded();
+ char[] password = mainUserInfo.getPassword();
+ User user = (User) userAdminWrapper.getUserAdmin().createRole(
+ getDn(username), Role.USER);
+
+ Dictionary props = user.getProperties();
+
+ String lastNameStr = lastNameTxt.getText();
+ if (UiAdminUtils.notNull(lastNameStr))
+ props.put(UserAdminConstants.KEY_LASTNAME, lastNameStr);
+
+ String firstNameStr = firstNameTxt.getText();
+ if (UiAdminUtils.notNull(firstNameStr))
+ props.put(UserAdminConstants.KEY_FIRSTNAME, firstNameStr);
+
+ String cn = UiAdminUtils
+ .getDefaultCn(firstNameStr, lastNameStr);
+ if (UiAdminUtils.notNull(cn))
+ props.put(UserAdminConstants.KEY_CN, cn);
+
+ String mailStr = primaryMailTxt.getText();
+ if (UiAdminUtils.notNull(mailStr))
+ props.put(UserAdminConstants.KEY_MAIL, mailStr);
+
+ user.getCredentials().put(null, password);
+
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_CREATED, user));
+ return true;
+ } catch (Exception e) {
+ ErrorFeedback.show("Cannot create new user " + username, e);
+ return false;
+ }
+ }
+
+ private class MainUserInfoWizardPage extends WizardPage implements
+ ModifyListener, ArgeoNames {
+ private static final long serialVersionUID = -3150193365151601807L;
+
+ public MainUserInfoWizardPage() {
+ super("Main");
+ setTitle("Required Information");
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(2, false));
+ dNameTxt = EclipseUiUtils.createGridLT(composite,
+ "Distinguished name", this);
+ dNameTxt.setEnabled(false);
+ usernameTxt = EclipseUiUtils.createGridLT(composite,
+ "Local ID", this);
+ usernameTxt.addModifyListener(new ModifyListener() {
+ private static final long serialVersionUID = -1435351236582736843L;
+
+ @Override
+ public void modifyText(ModifyEvent event) {
+ String name = usernameTxt.getText();
+ if (name.trim().equals("")) {
+ dNameTxt.setText("");
+ lastNameTxt.setText("");
+ primaryMailTxt.setText("");
+ pwd1Txt.setText("");
+ pwd2Txt.setText("");
+ } else {
+ dNameTxt.setText(getDn(name));
+ lastNameTxt.setText(name.toUpperCase());
+ primaryMailTxt.setText(name + "@example.com");
+ pwd1Txt.setText("demo");
+ pwd2Txt.setText("demo");
+ }
+ }
+ });
+
+ primaryMailTxt = EclipseUiUtils.createGridLT(composite,
+ "Email", this);
+ firstNameTxt = EclipseUiUtils.createGridLT(composite,
+ "First name", this);
+ lastNameTxt = EclipseUiUtils.createGridLT(composite,
+ "Last name", this);
+ pwd1Txt = EclipseUiUtils.createGridLP(composite, "Password",
+ this);
+ pwd2Txt = EclipseUiUtils.createGridLP(composite,
+ "Repeat password", this);
+ setControl(composite);
+
+ // Initialize buttons
+ setPageComplete(false);
+ getContainer().updateButtons();
+ }
+
+ @Override
+ public void modifyText(ModifyEvent event) {
+ String message = checkComplete();
+ if (message != null) {
+ setMessage(message, WizardPage.ERROR);
+ setPageComplete(false);
+ } else {
+ setMessage("Complete", WizardPage.INFORMATION);
+ setPageComplete(true);
+ }
+ getContainer().updateButtons();
+ }
+
+ /** @return error message or null if complete */
+ protected String checkComplete() {
+ String name = usernameTxt.getText();
+
+ if (name.trim().equals(""))
+ return "User name must not be empty";
+ Role role = userAdminWrapper.getUserAdmin()
+ .getRole(getDn(name));
+ if (role != null)
+ return "User " + name + " already exists";
+ if (!primaryMailTxt.getText().matches(
+ UserAdminService.EMAIL_PATTERN))
+ return "Not a valid email address";
+ if (lastNameTxt.getText().trim().equals(""))
+ return "Specify a last name";
+ if (pwd1Txt.getText().trim().equals(""))
+ return "Specify a password";
+ if (pwd2Txt.getText().trim().equals(""))
+ return "Repeat the password";
+ if (!pwd2Txt.getText().equals(pwd1Txt.getText()))
+ return "Passwords are different";
+ return null;
+ }
+
+ @Override
+ public void setVisible(boolean visible) {
+ super.setVisible(visible);
+ if (visible)
+ usernameTxt.setFocus();
+ }
+
+ public String getUsername() {
+ return usernameTxt.getText();
+ }
+
+ public char[] getPassword() {
+ return pwd1Txt.getTextChars();
+ }
+
+ }
+ }
+
+ /* DEPENDENCY INJECTION */
+ public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
+ this.userAdminWrapper = userAdminWrapper;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.commands;
+
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+/** Save the currently edited Argeo user. */
+public class SaveArgeoUser extends AbstractHandler {
+ public final static String ID = SecurityAdminPlugin.PLUGIN_ID
+ + ".saveArgeoUser";
+
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ try {
+ IWorkbenchPart iwp = HandlerUtil.getActiveWorkbenchWindow(event)
+ .getActivePage().getActivePart();
+
+ if (!(iwp instanceof IEditorPart))
+ return null;
+ IEditorPart editor = (IEditorPart) iwp;
+ editor.doSave(null);
+ } catch (Exception e) {
+ MessageDialog.openError(Display.getDefault().getActiveShell(),
+ "Error", "Cannot save user: " + e.getMessage());
+ }
+ return null;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.commands;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+
+/** Launch a wizard to update various properties about users in JCR. */
+public class UserBatchUpdate extends AbstractHandler {
+ // private Repository repository;
+ // private UserAdminService userAdminService;
+
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ // Session session = null;
+ // try {
+ // session = repository.login();
+ // UserBatchUpdateWizard userBatchUpdateWizard = new
+ // UserBatchUpdateWizard(
+ // session, userAdminService);
+ // WizardDialog dialog = new WizardDialog(
+ // HandlerUtil.getActiveShell(event), userBatchUpdateWizard);
+ // dialog.open();
+ // } catch (Exception e) {
+ // throw new ExecutionException("Cannot open wizard", e);
+ // } finally {
+ // JcrUtils.logoutQuietly(session);
+ // }
+ return null;
+ }
+
+// public void setRepository(Repository repository) {
+// this.repository = repository;
+// }
+ //
+ // public void setUserAdminService(UserAdminService userAdminService) {
+ // this.userAdminService = userAdminService;
+ // }
+
+ // public void setJcrSecurityModel(JcrSecurityModel jcrSecurityModel) {
+ // this.jcrSecurityModel = jcrSecurityModel;
+ // }
+
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.commands;
+
+import javax.transaction.Status;
+import javax.transaction.UserTransaction;
+
+import org.argeo.ArgeoException;
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.argeo.security.ui.admin.internal.UiAdminUtils;
+import org.argeo.security.ui.admin.internal.UserAdminWrapper;
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.osgi.service.useradmin.UserAdminEvent;
+
+/** Manage the transaction that is bound to the current perspective */
+public class UserTransactionHandler extends AbstractHandler {
+ public final static String ID = SecurityAdminPlugin.PLUGIN_ID
+ + ".userTransactionHandler";
+
+ public final static String PARAM_COMMAND_ID = "param.commandId";
+
+ public final static String TRANSACTION_BEGIN = "transaction.begin";
+ public final static String TRANSACTION_COMMIT = "transaction.commit";
+ public final static String TRANSACTION_ROLLBACK = "transaction.rollback";
+
+ /* DEPENDENCY INJECTION */
+ private UserAdminWrapper userAdminWrapper;
+
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ String commandId = event.getParameter(PARAM_COMMAND_ID);
+ UserTransaction userTransaction = userAdminWrapper.getUserTransaction();
+ try {
+ if (TRANSACTION_BEGIN.equals(commandId)) {
+ if (userTransaction.getStatus() != Status.STATUS_NO_TRANSACTION)
+ throw new ArgeoException("A transaction already exists");
+ else
+ userTransaction.begin();
+ } else if (TRANSACTION_COMMIT.equals(commandId)) {
+ if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION)
+ throw new ArgeoException("No transaction.");
+ else
+ userTransaction.commit();
+ } else if (TRANSACTION_ROLLBACK.equals(commandId)) {
+ if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION)
+ throw new ArgeoException("No transaction to rollback.");
+ else {
+ userTransaction.rollback();
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_CHANGED, null));
+ }
+ }
+ UiAdminUtils.notifyTransactionStateChange(userTransaction);
+ } catch (ArgeoException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new ArgeoException("Unable to call " + commandId + " on "
+ + userTransaction, e);
+ }
+ return null;
+ }
+
+ /* DEPENDENCY INJECTION */
+ public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
+ this.userAdminWrapper = userAdminWrapper;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.parts;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IPersistableElement;
+
+/** Editor input for an Argeo user. */
+public class ArgeoUserEditorInput implements IEditorInput {
+ private final String username;
+
+ public ArgeoUserEditorInput(String username) {
+ this.username = username;
+ }
+
+ public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
+ return null;
+ }
+
+ public boolean exists() {
+ return username != null;
+ }
+
+ public ImageDescriptor getImageDescriptor() {
+ return null;
+ }
+
+ public String getName() {
+ return username != null ? username : "<new user>";
+ }
+
+ public IPersistableElement getPersistable() {
+ return null;
+ }
+
+ public String getToolTipText() {
+ return username != null ? username : "<new user>";
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof ArgeoUserEditorInput))
+ return false;
+ if (((ArgeoUserEditorInput) obj).getUsername() == null)
+ return false;
+ return ((ArgeoUserEditorInput) obj).getUsername().equals(username);
+ }
+
+ public String getUsername() {
+ return username;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.parts;
+
+import java.util.Arrays;
+
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.RepositoryException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.jcr.ArgeoNames;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.forms.AbstractFormPart;
+import org.eclipse.ui.forms.IManagedForm;
+import org.eclipse.ui.forms.SectionPart;
+import org.eclipse.ui.forms.editor.FormEditor;
+import org.eclipse.ui.forms.editor.FormPage;
+import org.eclipse.ui.forms.widgets.FormToolkit;
+import org.eclipse.ui.forms.widgets.ScrolledForm;
+import org.eclipse.ui.forms.widgets.Section;
+
+/** Display/edit the properties common to all Argeo users */
+public class DefaultUserMainPage extends FormPage implements ArgeoNames {
+ final static String ID = "argeoUserEditor.mainPage";
+
+ private final static Log log = LogFactory.getLog(DefaultUserMainPage.class);
+ private Node userProfile;
+
+ private char[] newPassword;
+
+ public DefaultUserMainPage(FormEditor editor, Node userProfile) {
+ super(editor, ID, "Main");
+ this.userProfile = userProfile;
+ }
+
+ protected void createFormContent(final IManagedForm mf) {
+ try {
+ ScrolledForm form = mf.getForm();
+ refreshFormTitle(form);
+ GridLayout mainLayout = new GridLayout(1, true);
+ form.getBody().setLayout(mainLayout);
+
+ createGeneralPart(form.getBody());
+ createPassworPart(form.getBody());
+ } catch (RepositoryException e) {
+ throw new ArgeoException("Cannot create form content", e);
+ }
+ }
+
+ /** Creates the general section */
+ protected void createGeneralPart(Composite parent)
+ throws RepositoryException {
+ FormToolkit tk = getManagedForm().getToolkit();
+ Section section = tk.createSection(parent, Section.TITLE_BAR);
+ section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ section.setText("General");
+ Composite body = tk.createComposite(section, SWT.WRAP);
+ section.setClient(body);
+ GridLayout layout = new GridLayout(2, false);
+ body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ body.setLayout(layout);
+
+ final Text commonName = createLT(body, "Displayed Name",
+ getProperty(Property.JCR_TITLE));
+ final Text firstName = createLT(body, "First name",
+ getProperty(ARGEO_FIRST_NAME));
+ final Text lastName = createLT(body, "Last name",
+ getProperty(ARGEO_LAST_NAME));
+ final Text email = createLT(body, "Email",
+ getProperty(ARGEO_PRIMARY_EMAIL));
+ final Text description = createLMT(body, "Description",
+ getProperty(Property.JCR_DESCRIPTION));
+
+ // create form part (controller)
+ AbstractFormPart part = new SectionPart(section) {
+ public void commit(boolean onSave) {
+ try {
+ userProfile.getSession().getWorkspace().getVersionManager()
+ .checkout(userProfile.getPath());
+ userProfile.setProperty(Property.JCR_TITLE,
+ commonName.getText());
+ userProfile.setProperty(ARGEO_FIRST_NAME,
+ firstName.getText());
+ userProfile
+ .setProperty(ARGEO_LAST_NAME, lastName.getText());
+ userProfile.setProperty(ARGEO_PRIMARY_EMAIL,
+ email.getText());
+ userProfile.setProperty(Property.JCR_DESCRIPTION,
+ description.getText());
+ userProfile.getSession().save();
+ userProfile.getSession().getWorkspace().getVersionManager()
+ .checkin(userProfile.getPath());
+ super.commit(onSave);
+ refreshFormTitle(getManagedForm().getForm());
+ if (log.isTraceEnabled())
+ log.trace("General part committed");
+ } catch (RepositoryException e) {
+ throw new ArgeoException("Cannot commit", e);
+ }
+ }
+ };
+ // if (username != null)
+ // username.addModifyListener(new FormPartML(part));
+ commonName.addModifyListener(new FormPartML(part));
+ firstName.addModifyListener(new FormPartML(part));
+ lastName.addModifyListener(new FormPartML(part));
+ email.addModifyListener(new FormPartML(part));
+ description.addModifyListener(new FormPartML(part));
+ getManagedForm().addPart(part);
+ }
+
+ private void refreshFormTitle(ScrolledForm form) throws RepositoryException {
+ form.setText(getProperty(Property.JCR_TITLE)
+ + (userProfile.getProperty(ARGEO_ENABLED).getBoolean() ? ""
+ : " [DISABLED]"));
+ }
+
+ /** @return the property, or the empty string if not set */
+ protected String getProperty(String name) throws RepositoryException {
+ return userProfile.hasProperty(name) ? userProfile.getProperty(name)
+ .getString() : "";
+ }
+
+ /** Creates the password section */
+ protected void createPassworPart(Composite parent) {
+ FormToolkit tk = getManagedForm().getToolkit();
+ Section section = tk.createSection(parent, Section.TITLE_BAR);
+ section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ section.setText("Password");
+
+ Composite body = tk.createComposite(section, SWT.WRAP);
+ section.setClient(body);
+ GridLayout layout = new GridLayout(2, false);
+ body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ body.setLayout(layout);
+
+ // add widgets (view)
+ final Text password1 = createLP(body, "New password", "");
+ final Text password2 = createLP(body, "Repeat password", "");
+ // create form part (controller)
+ AbstractFormPart part = new SectionPart(section) {
+
+ public void commit(boolean onSave) {
+ if (!password1.getText().equals("")
+ || !password2.getText().equals("")) {
+ if (password1.getText().equals(password2.getText())) {
+ newPassword = password1.getText().toCharArray();
+ password1.setText("");
+ password2.setText("");
+ super.commit(onSave);
+ } else {
+ password1.setText("");
+ password2.setText("");
+ throw new ArgeoException("Passwords are not equals");
+ }
+ }
+ }
+
+ };
+ password1.addModifyListener(new FormPartML(part));
+ password2.addModifyListener(new FormPartML(part));
+ getManagedForm().addPart(part);
+ }
+
+ /** Creates label and text. */
+ protected Text createLT(Composite body, String label, String value) {
+ FormToolkit toolkit = getManagedForm().getToolkit();
+ Label lbl = toolkit.createLabel(body, label);
+ lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ Text text = toolkit.createText(body, value, SWT.BORDER);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ return text;
+ }
+
+ /** Creates label and multiline text. */
+ protected Text createLMT(Composite body, String label, String value) {
+ FormToolkit toolkit = getManagedForm().getToolkit();
+ Label lbl = toolkit.createLabel(body, label);
+ lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ Text text = toolkit.createText(body, value, SWT.BORDER | SWT.MULTI);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
+ return text;
+ }
+
+ /** Creates label and password. */
+ protected Text createLP(Composite body, String label, String value) {
+ FormToolkit toolkit = getManagedForm().getToolkit();
+ Label lbl = toolkit.createLabel(body, label);
+ lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ Text text = toolkit.createText(body, value, SWT.BORDER | SWT.PASSWORD);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ return text;
+ }
+
+ private class FormPartML implements ModifyListener {
+ private static final long serialVersionUID = 6299808129505381333L;
+ private AbstractFormPart formPart;
+
+ public FormPartML(AbstractFormPart generalPart) {
+ this.formPart = generalPart;
+ }
+
+ public void modifyText(ModifyEvent e) {
+ formPart.markDirty();
+ }
+
+ }
+
+ public String getNewPassword() {
+ if (newPassword != null)
+ return new String(newPassword);
+ else
+ return null;
+ }
+
+ public void resetNewPassword() {
+ if (newPassword != null)
+ Arrays.fill(newPassword, 'x');
+ newPassword = null;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.parts;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.jcr.RepositoryException;
+
+import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiUtils;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.security.ui.admin.internal.ColumnDefinition;
+import org.argeo.security.ui.admin.internal.UserAdminConstants;
+import org.argeo.security.ui.admin.internal.UserAdminWrapper;
+import org.argeo.security.ui.admin.internal.UserTableViewer;
+import org.argeo.security.ui.admin.internal.providers.CommonNameLP;
+import org.argeo.security.ui.admin.internal.providers.MailLP;
+import org.argeo.security.ui.admin.internal.providers.RoleIconLP;
+import org.argeo.security.ui.admin.internal.providers.UserNameLP;
+import org.argeo.security.ui.admin.internal.providers.UserTableDefaultDClickListener;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerDropAdapter;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.dnd.TransferData;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.forms.AbstractFormPart;
+import org.eclipse.ui.forms.IManagedForm;
+import org.eclipse.ui.forms.SectionPart;
+import org.eclipse.ui.forms.editor.FormEditor;
+import org.eclipse.ui.forms.editor.FormPage;
+import org.eclipse.ui.forms.widgets.FormToolkit;
+import org.eclipse.ui.forms.widgets.ScrolledForm;
+import org.eclipse.ui.forms.widgets.Section;
+import org.osgi.service.useradmin.Group;
+import org.osgi.service.useradmin.Role;
+import org.osgi.service.useradmin.User;
+import org.osgi.service.useradmin.UserAdmin;
+import org.osgi.service.useradmin.UserAdminEvent;
+
+/** Display/edit main properties of a given group */
+public class GroupMainPage extends FormPage implements ArgeoNames {
+ final static String ID = "GroupEditor.mainPage";
+
+ private final UserEditor editor;
+ private UserAdminWrapper userAdminWrapper;
+
+ // Local configuration
+ private final int PRE_TITLE_INDENT = 10;
+
+ public GroupMainPage(FormEditor editor, UserAdminWrapper userAdminWrapper) {
+ super(editor, ID, "Main");
+ this.editor = (UserEditor) editor;
+ this.userAdminWrapper = userAdminWrapper;
+ }
+
+ protected void createFormContent(final IManagedForm mf) {
+ try {
+ ScrolledForm form = mf.getForm();
+ refreshFormTitle();
+
+ // Body
+ Composite body = form.getBody();
+ GridLayout mainLayout = new GridLayout();
+ body.setLayout(mainLayout);
+ appendOverviewPart(body);
+ appendMembersPart(body);
+ } catch (RepositoryException e) {
+ throw new ArgeoException("Cannot create form content", e);
+ }
+ }
+
+ /** Creates the general section */
+ protected void appendOverviewPart(Composite parent) {
+ FormToolkit tk = getManagedForm().getToolkit();
+ Composite body = addSection(tk, parent, "Main information");
+ GridLayout layout = new GridLayout(2, false);
+ body.setLayout(layout);
+
+ Text distinguishedName = createLT(body, "Group Name",
+ editor.getProperty(UserAdminConstants.KEY_UID));
+ distinguishedName.setEnabled(false);
+
+ final Text commonName = createLT(body, "Common Name",
+ editor.getProperty(UserAdminConstants.KEY_CN));
+ commonName.setEnabled(false);
+
+ // create form part (controller)
+ AbstractFormPart part = new SectionPart((Section) body.getParent()) {
+ public void commit(boolean onSave) {
+ super.commit(onSave);
+ }
+ };
+ getManagedForm().addPart(part);
+ }
+
+ /** Filtered table with members. Has drag & drop ability */
+ protected void appendMembersPart(Composite parent)
+ throws RepositoryException {
+
+ FormToolkit tk = getManagedForm().getToolkit();
+ Section section = tk.createSection(parent, Section.TITLE_BAR);
+ section.setLayoutData(EclipseUiUtils.fillAll());
+ section.setText("Members of group "
+ + editor.getProperty(UserAdminConstants.KEY_CN));
+
+ // Composite body = tk.createComposite(section, SWT.NONE);
+ Composite body = new Composite(section, SWT.NO_FOCUS);
+ section.setClient(body);
+ body.setLayoutData(EclipseUiUtils.fillAll());
+
+ createMemberPart(body);
+
+ // create form part (controller)
+ AbstractFormPart part = new SectionPart(section) {
+ public void commit(boolean onSave) {
+ super.commit(onSave);
+ }
+ };
+
+ getManagedForm().addPart(part);
+ }
+
+ // UI Objects
+ private UserTableViewer userTableViewerCmp;
+ private TableViewer userViewer;
+ private List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
+
+ public void createMemberPart(Composite parent) {
+ parent.setLayout(EclipseUiUtils.noSpaceGridLayout());
+ // Define the displayed columns
+ columnDefs.add(new ColumnDefinition(new RoleIconLP(), "", 0, 24));
+ columnDefs.add(new ColumnDefinition(new UserNameLP(),
+ "Distinguished Name", 240));
+ columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Common Name",
+ 150));
+ columnDefs.add(new ColumnDefinition(new MailLP(), "Primary Mail", 150));
+
+ // Create and configure the table
+ userTableViewerCmp = new MyUserTableViewer(parent, SWT.MULTI
+ | SWT.H_SCROLL | SWT.V_SCROLL, userAdminWrapper.getUserAdmin());
+
+ userTableViewerCmp.setColumnDefinitions(columnDefs);
+ userTableViewerCmp.populate(true, false);
+ // userTableViewerCmp.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
+ // false, false));
+ userTableViewerCmp.setLayoutData(EclipseUiUtils.fillAll());
+
+ // Links
+ userViewer = userTableViewerCmp.getTableViewer();
+ userViewer.addDoubleClickListener(new UserTableDefaultDClickListener());
+ // Really?
+ userTableViewerCmp.refresh();
+
+ // Drag and drop
+ int operations = DND.DROP_COPY | DND.DROP_MOVE;
+ Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
+ userViewer.addDropSupport(operations, tt,
+ new GroupDropListener(userViewer, userAdminWrapper,
+ (Group) editor.getDisplayedUser()));
+ }
+
+ private class MyUserTableViewer extends UserTableViewer {
+ private static final long serialVersionUID = 8467999509931900367L;
+
+ public MyUserTableViewer(Composite parent, int style,
+ UserAdmin userAdmin) {
+ super(parent, style, userAdmin, true);
+ }
+
+ @Override
+ protected List<User> listFilteredElements(String filter) {
+ Group group = (Group) editor.getDisplayedUser();
+ Role[] roles = group.getMembers();
+ List<User> users = new ArrayList<User>();
+ for (Role role : roles)
+ // if (role.getType() == Role.GROUP)
+ users.add((User) role);
+ return users;
+ }
+ }
+
+ private void refreshFormTitle() throws RepositoryException {
+ getManagedForm().getForm().setText(
+ editor.getProperty(UserAdminConstants.KEY_CN));
+ }
+
+ /**
+ * Defines this table as being a potential target to add group membership
+ * (roles) to this user
+ */
+ private class GroupDropListener extends ViewerDropAdapter {
+ private static final long serialVersionUID = 2893468717831451621L;
+
+ private final UserAdminWrapper userAdminWrapper;
+ private final Group myGroup;
+
+ public GroupDropListener(Viewer viewer,
+ UserAdminWrapper userAdminWrapper, Group group) {
+ super(viewer);
+ this.userAdminWrapper = userAdminWrapper;
+ this.myGroup = group;
+ }
+
+ @Override
+ public boolean validateDrop(Object target, int operation,
+ TransferData transferType) {
+ // Target is always OK in a list only view
+ // TODO check if not a string
+ boolean validDrop = true;
+ return validDrop;
+ }
+
+ @Override
+ public void drop(DropTargetEvent event) {
+ // TODO Is there an opportunity to perform ceck before?
+
+ String newUserName = (String) event.data;
+ UserAdmin myUserAdmin = userAdminWrapper.getUserAdmin();
+ Role role = myUserAdmin.getRole(newUserName);
+ if (role.getType() == Role.USER) {
+ // TODO check if the user is already member of this group
+ userAdminWrapper.beginTransactionIfNeeded();
+ User user = (User) role;
+ myGroup.addMember(user);
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_CHANGED, myGroup));
+ } else if (role.getType() == Role.GROUP) {
+ Group newGroup = (Group) role;
+
+ Shell shell = getViewer().getControl().getShell();
+ // Sanity checks
+ if (myGroup == newGroup) { // Equality
+ MessageDialog.openError(shell, "Forbidden addition ",
+ "A group cannot be a member of itself.");
+ return;
+ }
+
+ // Cycle
+ String myName = myGroup.getName();
+ List<User> myMemberships = editor.getFlatGroups(myGroup);
+ if (myMemberships.contains(newGroup)) {
+ MessageDialog.openError(shell, "Forbidden addition: cycle",
+ "Cannot add " + newUserName + " to group " + myName
+ + ". This would create a cycle");
+ return;
+ }
+
+ // Already member
+ List<User> newGroupMemberships = editor.getFlatGroups(newGroup);
+ if (newGroupMemberships.contains(myGroup)) {
+ MessageDialog.openError(shell, "Forbidden addition",
+ "Cannot add " + newUserName + " to group " + myName
+ + ", this membership already exists");
+ return;
+ }
+
+ userAdminWrapper.beginTransactionIfNeeded();
+ // TODO implement the dirty state
+ myGroup.addMember(newGroup);
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_CHANGED, myGroup));
+ }
+ super.drop(event);
+ }
+
+ @Override
+ public boolean performDrop(Object data) {
+ userTableViewerCmp.refresh();
+ return true;
+ }
+ }
+
+ // LOCAL HELPERS
+ private Composite addSection(FormToolkit tk, Composite parent, String title) {
+ Section section = tk.createSection(parent, Section.TITLE_BAR);
+ GridData gd = EclipseUiUtils.fillWidth();
+ gd.verticalAlignment = PRE_TITLE_INDENT;
+ section.setLayoutData(gd);
+ section.setText(title);
+ Composite body = tk.createComposite(section, SWT.WRAP);
+ body.setLayoutData(EclipseUiUtils.fillAll());
+ section.setClient(body);
+ return body;
+ }
+
+ /** Creates label and text. */
+ protected Text createLT(Composite body, String label, String value) {
+ FormToolkit toolkit = getManagedForm().getToolkit();
+ Label lbl = toolkit.createLabel(body, label);
+ lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ Text text = toolkit.createText(body, value, SWT.BORDER);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ return text;
+ }
+}
\ No newline at end of file
import org.argeo.jcr.ArgeoNames;
import org.argeo.security.ui.admin.SecurityAdminPlugin;
import org.argeo.security.ui.admin.internal.ColumnDefinition;
-import org.argeo.security.ui.admin.internal.CommonNameLP;
import org.argeo.security.ui.admin.internal.UiAdminUtils;
import org.argeo.security.ui.admin.internal.UserAdminConstants;
import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.argeo.security.ui.admin.internal.UserDragListener;
-import org.argeo.security.ui.admin.internal.UserNameLP;
-import org.argeo.security.ui.admin.internal.UserTableDefaultDClickListener;
import org.argeo.security.ui.admin.internal.UserTableViewer;
+import org.argeo.security.ui.admin.internal.providers.CommonNameLP;
+import org.argeo.security.ui.admin.internal.providers.UserDragListener;
+import org.argeo.security.ui.admin.internal.providers.UserNameLP;
+import org.argeo.security.ui.admin.internal.providers.UserTableDefaultDClickListener;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.parts;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.version.VersionManager;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.ArgeoException;
+import org.argeo.ArgeoMonitor;
+import org.argeo.eclipse.ui.EclipseArgeoMonitor;
+import org.argeo.eclipse.ui.parts.UsersTable;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.jcr.JcrUtils;
+import org.argeo.security.UserAdminService;
+import org.argeo.security.jcr.JcrUserDetails;
+import org.argeo.security.ui.PrivilegedJob;
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.dialogs.IPageChangeProvider;
+import org.eclipse.jface.dialogs.IPageChangedListener;
+import org.eclipse.jface.dialogs.PageChangedEvent;
+import org.eclipse.jface.wizard.IWizardContainer;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+/** Wizard to update users */
+public class UserBatchUpdateWizard extends Wizard {
+ private final static Log log = LogFactory
+ .getLog(UserBatchUpdateWizard.class);
+ private Session session;
+ private UserAdminService userAdminService;
+
+ // pages
+ private ChooseCommandWizardPage chooseCommandPage;
+ private ChooseUsersWizardPage userListPage;
+ private ValidateAndLaunchWizardPage validatePage;
+
+ // /////////////////////////////////////////////////
+ // / Definition of the various implemented commands
+ private final static String CMD_UPDATE_PASSWORD = "resetPassword";
+ private final static String CMD_GROUP_MEMBERSHIP = "groupMembership";
+
+ private final Map<String, String> commands = new HashMap<String, String>() {
+ private static final long serialVersionUID = 1L;
+ {
+ put("Enable user(s)", ArgeoNames.ARGEO_ENABLED);
+ put("Expire credentials", ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED);
+ put("Expire account(s)", ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED);
+ put("Lock account(s)", ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED);
+ put("Reset password(s)", CMD_UPDATE_PASSWORD);
+ // TODO implement role / group management
+ // put("Add/Remove from group", CMD_GROUP_MEMBERSHIP);
+ }
+ };
+
+ public UserBatchUpdateWizard(Session session,
+ UserAdminService userAdminService) {
+ this.session = session;
+ this.userAdminService = userAdminService;
+ }
+
+ @Override
+ public void addPages() {
+ chooseCommandPage = new ChooseCommandWizardPage();
+ addPage(chooseCommandPage);
+ userListPage = new ChooseUsersWizardPage(session);
+ addPage(userListPage);
+ validatePage = new ValidateAndLaunchWizardPage(session);
+ addPage(validatePage);
+ }
+
+ @Override
+ public boolean performFinish() {
+ if (!canFinish())
+ return false;
+
+ UpdateJob job = null;
+ if (ArgeoNames.ARGEO_ENABLED.equals(chooseCommandPage.getCommand())) {
+ job = new UpdateBoolean(session, userListPage.getSelectedUsers(),
+ ArgeoNames.ARGEO_ENABLED,
+ chooseCommandPage.getBoleanValue());
+ } else if (ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED
+ .equals(chooseCommandPage.getCommand())) {
+ job = new UpdateBoolean(session, userListPage.getSelectedUsers(),
+ ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED,
+ chooseCommandPage.getBoleanValue());
+ } else if (ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED
+ .equals(chooseCommandPage.getCommand())) {
+ job = new UpdateBoolean(session, userListPage.getSelectedUsers(),
+ ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED,
+ chooseCommandPage.getBoleanValue());
+ } else if (ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED.equals(chooseCommandPage
+ .getCommand())) {
+ job = new UpdateBoolean(session, userListPage.getSelectedUsers(),
+ ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED,
+ chooseCommandPage.getBoleanValue());
+ } else if (CMD_UPDATE_PASSWORD.equals(chooseCommandPage.getCommand())) {
+ String newValue = chooseCommandPage.getPwdValue();
+ if (newValue == null)
+ throw new ArgeoException(
+ "Password cannot be null or an empty string");
+ job = new ResetPassword(session, userAdminService,
+ userListPage.getSelectedUsers(), newValue);
+ }
+
+ if (job != null)
+ job.schedule();
+ return true;
+ }
+
+ public void setSession(Session session) {
+ this.session = session;
+ }
+
+ public boolean canFinish() {
+ if (this.getContainer().getCurrentPage() == validatePage)
+ return true;
+ return false;
+ }
+
+ // /////////////////////////
+ // REEL UPDATE JOB
+ private class UpdateBoolean extends UpdateJob {
+ private String propertyName;
+ private boolean value;
+
+ public UpdateBoolean(Session session, List<Node> nodesToUpdate,
+ String propertyName, boolean value) {
+ super(session, nodesToUpdate);
+ this.propertyName = propertyName;
+ this.value = value;
+ }
+
+ protected void doUpdate(Node node) {
+ try {
+ node.setProperty(propertyName, value);
+ } catch (RepositoryException re) {
+ throw new ArgeoException(
+ "Unable to update boolean value for node " + node, re);
+ }
+ }
+ }
+
+ private class ResetPassword extends UpdateJob {
+ private String newValue;
+ private UserAdminService userAdminService;
+
+ public ResetPassword(Session session,
+ UserAdminService userAdminService, List<Node> nodesToUpdate,
+ String newValue) {
+ super(session, nodesToUpdate);
+ this.newValue = newValue;
+ this.userAdminService = userAdminService;
+ }
+
+ protected void doUpdate(Node node) {
+ try {
+ String userId = node.getProperty(ArgeoNames.ARGEO_USER_ID)
+ .getString();
+ if (userAdminService.userExists(userId)) {
+ JcrUserDetails userDetails = (JcrUserDetails) userAdminService
+ .loadUserByUsername(userId);
+ userAdminService.updateUser(userDetails
+ .cloneWithNewPassword(newValue));
+ }
+ } catch (RepositoryException re) {
+ throw new ArgeoException(
+ "Unable to update boolean value for node " + node, re);
+ }
+ }
+ }
+
+ @SuppressWarnings("unused")
+ private class AddToGroup extends UpdateJob {
+ private String groupID;
+ private Session session;
+
+ public AddToGroup(Session session, List<Node> nodesToUpdate,
+ String groupID) {
+ super(session, nodesToUpdate);
+ this.session = session;
+ this.groupID = groupID;
+ }
+
+ protected void doUpdate(Node node) {
+ log.info("Add/Remove to group actions are not yet implemented");
+ // TODO implement this
+ // try {
+ // throw new ArgeoException("Not yet implemented");
+ // } catch (RepositoryException re) {
+ // throw new ArgeoException(
+ // "Unable to update boolean value for node " + node, re);
+ // }
+ }
+ }
+
+ /**
+ * Base privileged job that will be run asynchronously to perform the batch
+ * update
+ */
+ private abstract class UpdateJob extends PrivilegedJob {
+
+ private final Session currSession;
+ private final List<Node> nodesToUpdate;
+
+ protected abstract void doUpdate(Node node);
+
+ public UpdateJob(Session session, List<Node> nodesToUpdate) {
+ super("Perform update");
+ try {
+ this.currSession = session.getRepository().login();
+ // "move" nodes to update in the new session
+ // the "old" session will be closed by the calling command
+ // before the job has effectively ran
+ // TODO there must be a cleaner way to do.
+ List<Node> nodes = new ArrayList<Node>();
+ for (Node node : nodesToUpdate) {
+ nodes.add(currSession.getNode(node.getPath()));
+ }
+ this.nodesToUpdate = nodes;
+ } catch (RepositoryException e) {
+ throw new ArgeoException("Error while dupplicating "
+ + "session for job", e);
+ }
+ }
+
+ @Override
+ protected IStatus doRun(IProgressMonitor progressMonitor) {
+ try {
+ ArgeoMonitor monitor = new EclipseArgeoMonitor(progressMonitor);
+ VersionManager vm = currSession.getWorkspace()
+ .getVersionManager();
+ int total = nodesToUpdate.size();
+ monitor.beginTask("Performing change", total);
+ for (Node node : nodesToUpdate) {
+ String path = node.getPath();
+ vm.checkout(path);
+ doUpdate(node);
+ currSession.save();
+ vm.checkin(path);
+ monitor.worked(1);
+ }
+ } catch (Exception e) {
+ log.error("Cannot perform batch update on users", e);
+ // e.printStackTrace();
+
+ // Dig exception to find the root cause that will enable the
+ // user to understand the problem
+ Throwable cause = e;
+ Throwable originalCause = e;
+ while (cause != null) {
+ if (log.isTraceEnabled())
+ log.trace("Parent Cause message : "
+ + cause.getMessage());
+ originalCause = cause;
+ cause = cause.getCause();
+ }
+ return new Status(IStatus.ERROR, SecurityAdminPlugin.PLUGIN_ID,
+ "Cannot perform updates.", originalCause);
+ } finally {
+ JcrUtils.logoutQuietly(currSession);
+ }
+ return Status.OK_STATUS;
+ }
+ }
+
+ // //////////////////////
+ // Pages definition
+ /** Displays a combo box that enables user to choose which action to perform */
+ private class ChooseCommandWizardPage extends WizardPage {
+ private static final long serialVersionUID = 1L;
+
+ private Combo chooseCommandCmb;
+ private Button trueChk;
+ private Text valueTxt;
+ private Text pwdTxt;
+ private Text pwd2Txt;
+
+ public ChooseCommandWizardPage() {
+ super("Choose a command to run.");
+ setTitle("Choose a command to run.");
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ GridLayout gl = new GridLayout();
+ Composite container = new Composite(parent, SWT.NO_FOCUS);
+ container.setLayout(gl);
+
+ chooseCommandCmb = new Combo(container, SWT.NO_FOCUS);
+ String[] values = commands.keySet().toArray(
+ new String[commands.size()]);
+ chooseCommandCmb.setItems(values);
+ chooseCommandCmb.setLayoutData(new GridData(SWT.FILL, SWT.TOP,
+ true, false));
+
+ final Composite bottomPart = new Composite(container, SWT.NO_FOCUS);
+ gl = new GridLayout();
+ gl.horizontalSpacing = gl.marginWidth = gl.verticalSpacing = 0;
+ bottomPart.setLayout(gl);
+ bottomPart.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true));
+
+ chooseCommandCmb.addSelectionListener(new SelectionListener() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if (getCommand().equals(CMD_UPDATE_PASSWORD))
+ populatePasswordCmp(bottomPart);
+ else if (getCommand().equals(CMD_GROUP_MEMBERSHIP))
+ populateGroupCmp(bottomPart);
+ else
+ populateBooleanFlagCmp(bottomPart);
+ bottomPart.pack(true);
+ bottomPart.layout();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ setControl(container);
+ }
+
+ private void cleanParent(Composite parent) {
+ if (parent.getChildren().length > 0) {
+ for (Control control : parent.getChildren())
+ control.dispose();
+ }
+ }
+
+ private void populateBooleanFlagCmp(Composite parent) {
+ cleanParent(parent);
+ trueChk = new Button(parent, SWT.CHECK);
+ trueChk.setText("Do it. (It will to the contrary if unchecked)");
+ trueChk.setSelection(true);
+ trueChk.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
+ }
+
+ private void populatePasswordCmp(Composite parent) {
+ cleanParent(parent);
+ Composite body = new Composite(parent, SWT.NO_FOCUS);
+ body.setLayout(new GridLayout(2, false));
+ body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ pwdTxt = createLP(body, "New password", "");
+ pwd2Txt = createLP(body, "Repeat password", "");
+ }
+
+ /** Creates label and password. */
+ protected Text createLP(Composite body, String label, String value) {
+ Label lbl = new Label(body, SWT.NONE);
+ lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ lbl.setText(label);
+ Text text = new Text(body, SWT.BORDER | SWT.PASSWORD);
+ text.setText(value);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ return text;
+ }
+
+ private void populateGroupCmp(Composite parent) {
+ if (parent.getChildren().length > 0) {
+ for (Control control : parent.getChildren())
+ control.dispose();
+ }
+ trueChk = new Button(parent, SWT.CHECK);
+ trueChk.setText("Add to group. (It will remove user(s) from the "
+ + "corresponding group if unchecked)");
+ trueChk.setSelection(true);
+ trueChk.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
+ }
+
+ protected String getCommand() {
+ return commands.get(chooseCommandCmb.getItem(chooseCommandCmb
+ .getSelectionIndex()));
+ }
+
+ protected String getCommandLbl() {
+ return chooseCommandCmb.getItem(chooseCommandCmb
+ .getSelectionIndex());
+ }
+
+ protected boolean getBoleanValue() {
+ // FIXME this is not consistent and will lead to errors.
+ if (ArgeoNames.ARGEO_ENABLED.equals(getCommand()))
+ return trueChk.getSelection();
+ else
+ return !trueChk.getSelection();
+ }
+
+ @SuppressWarnings("unused")
+ protected String getStringValue() {
+ String value = null;
+ if (valueTxt != null) {
+ value = valueTxt.getText();
+ if ("".equals(value.trim()))
+ value = null;
+ }
+ return value;
+ }
+
+ protected String getPwdValue() {
+ String newPwd = null;
+ if (pwdTxt == null || pwd2Txt == null)
+ return null;
+ if (!pwdTxt.getText().equals("") || !pwd2Txt.getText().equals("")) {
+ if (pwdTxt.getText().equals(pwd2Txt.getText())) {
+ newPwd = pwdTxt.getText();
+ pwdTxt.setText("");
+ pwd2Txt.setText("");
+ } else {
+ pwdTxt.setText("");
+ pwd2Txt.setText("");
+ throw new ArgeoException("Passwords are not equals");
+ }
+ }
+ return newPwd;
+ }
+ }
+
+ /**
+ * Displays a list of users with a check box to be able to choose some of
+ * them
+ */
+ private class ChooseUsersWizardPage extends WizardPage implements
+ IPageChangedListener {
+ private static final long serialVersionUID = 1L;
+ private UsersTable userTableCmp;
+ private Composite container;
+ private Session session;
+
+ public ChooseUsersWizardPage(Session session) {
+ super("Choose Users");
+ this.session = session;
+ setTitle("Select users who will be impacted");
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ container = new Composite(parent, SWT.NONE);
+ container.setLayout(new FillLayout());
+ userTableCmp = new MyUserTableCmp(container, SWT.NO_FOCUS, session);
+ userTableCmp.populate(true, true);
+ setControl(container);
+
+ // Add listener to update message when shown
+ final IWizardContainer container = this.getContainer();
+ if (container instanceof IPageChangeProvider) {
+ ((IPageChangeProvider) container).addPageChangedListener(this);
+ }
+
+ }
+
+ @Override
+ public void pageChanged(PageChangedEvent event) {
+ if (event.getSelectedPage() == this) {
+ String msg = "Chosen batch action: "
+ + chooseCommandPage.getCommandLbl();
+ ((WizardPage) event.getSelectedPage()).setMessage(msg);
+ }
+ }
+
+ protected List<Node> getSelectedUsers() {
+ return userTableCmp.getSelectedUsers();
+ }
+
+ private class MyUserTableCmp extends UsersTable {
+
+ private static final long serialVersionUID = 1L;
+
+ public MyUserTableCmp(Composite parent, int style, Session session) {
+ super(parent, style, session);
+ }
+
+ @Override
+ protected void refreshFilteredList() {
+ List<Node> nodes = new ArrayList<Node>();
+ try {
+ NodeIterator ni = listFilteredElements(session,
+ getFilterString());
+
+ users: while (ni.hasNext()) {
+ Node currNode = ni.nextNode();
+ String username = currNode.hasProperty(ARGEO_USER_ID) ? currNode
+ .getProperty(ARGEO_USER_ID).getString() : "";
+ if (username.equals(session.getUserID()))
+ continue users;
+ else
+ nodes.add(currNode);
+ }
+ getTableViewer().setInput(nodes.toArray());
+ } catch (RepositoryException e) {
+ throw new ArgeoException("Unable to list users", e);
+ }
+ }
+ }
+ }
+
+ /**
+ * Recapitulation of input data before running real update
+ */
+ private class ValidateAndLaunchWizardPage extends WizardPage implements
+ IPageChangedListener {
+ private static final long serialVersionUID = 1L;
+ private UsersTable userTableCmp;
+ private Session session;
+
+ public ValidateAndLaunchWizardPage(Session session) {
+ super("Validate and launch");
+ this.session = session;
+ setTitle("Validate and launch");
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite mainCmp = new Composite(parent, SWT.NO_FOCUS);
+ mainCmp.setLayout(new FillLayout());
+
+ // Add listener to update user list when shown
+ final IWizardContainer container = this.getContainer();
+ if (container instanceof IPageChangeProvider) {
+ ((IPageChangeProvider) container).addPageChangedListener(this);
+ }
+
+ userTableCmp = new UsersTable(mainCmp, SWT.NO_FOCUS, session);
+ userTableCmp.populate(false, false);
+ setControl(mainCmp);
+ }
+
+ @Override
+ public void pageChanged(PageChangedEvent event) {
+ if (event.getSelectedPage() == this) {
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ Object[] values = ((ArrayList) userListPage.getSelectedUsers())
+ .toArray(new Object[userListPage.getSelectedUsers()
+ .size()]);
+ userTableCmp.getTableViewer().setInput(values);
+ String msg = "Following batch action: ["
+ + chooseCommandPage.getCommandLbl()
+ + "] will be perfomed on the users listed below.\n"
+ + "Are you sure you want to proceed?";
+ ((WizardPage) event.getSelectedPage()).setMessage(msg);
+ }
+ }
+
+ // private class MyUserTableCmp extends UserTableComposite {
+ // public MyUserTableCmp(Composite parent, int style, Session session) {
+ // super(parent, style, session);
+ // }
+ //
+ // @Override
+ // protected void refreshFilteredList() {
+ // @SuppressWarnings({ "unchecked", "rawtypes" })
+ //
+ // setFilteredList(values);
+ // }
+ //
+ // @Override
+ // public void setVisible(boolean visible) {
+ // super.setVisible(visible);
+ // if (visible)
+ // refreshFilteredList();
+ // }
+ // }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.parts;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.argeo.ArgeoException;
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.argeo.security.ui.admin.internal.UserAdminConstants;
+import org.argeo.security.ui.admin.internal.UserAdminWrapper;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.forms.editor.FormEditor;
+import org.osgi.service.useradmin.Authorization;
+import org.osgi.service.useradmin.Role;
+import org.osgi.service.useradmin.User;
+import org.osgi.service.useradmin.UserAdmin;
+import org.osgi.service.useradmin.UserAdminEvent;
+
+/** Editor for a user, might be a user or a group. */
+public class UserEditor extends FormEditor implements UserAdminConstants {
+ private static final long serialVersionUID = 8357851520380820241L;
+
+ public final static String ID = SecurityAdminPlugin.PLUGIN_ID
+ + ".userEditor";
+
+ /* DEPENDENCY INJECTION */
+ private UserAdminWrapper userAdminWrapper;
+ private UserAdmin userAdmin;
+
+ // Context
+ private User user;
+ private String username;
+
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ super.init(site, input);
+ username = ((UserEditorInput) getEditorInput()).getUsername();
+ user = (User) userAdmin.getRole(username);
+
+ String commonName = getProperty(KEY_CN);
+
+ setPartName(commonName != null ? commonName : "username");
+
+ // TODO: following has been disabled because it causes NPE after a
+ // login/logout on RAP
+ // Image titleIcon = user.getType() == Role.GROUP ?
+ // SecurityAdminImages.ICON_GROUP
+ // : SecurityAdminImages.ICON_USER;
+ // setTitleImage(titleIcon);
+ }
+
+ /**
+ * returns the list of all authorisation for the given user or of the
+ * current displayed user if parameter is null
+ */
+ protected List<User> getFlatGroups(User aUser) {
+ Authorization currAuth;
+ if (aUser == null)
+ currAuth = userAdmin.getAuthorization(this.user);
+ else
+ currAuth = userAdmin.getAuthorization(aUser);
+
+ String[] roles = currAuth.getRoles();
+
+ List<User> groups = new ArrayList<User>();
+ for (String roleStr : roles) {
+ User currRole = (User) userAdmin.getRole(roleStr);
+ if (!groups.contains(currRole))
+ groups.add(currRole);
+ }
+ return groups;
+ }
+
+ /** Exposes the user (or group) that is displayed by the current editor */
+ protected User getDisplayedUser() {
+ return user;
+ }
+
+ void updateEditorTitle(String title) {
+ setPartName(title);
+ }
+
+ protected void addPages() {
+ try {
+ if (user.getType() == Role.GROUP)
+ addPage(new GroupMainPage(this, userAdminWrapper));
+ else
+ addPage(new UserMainPage(this, userAdminWrapper));
+ } catch (Exception e) {
+ throw new ArgeoException("Cannot add pages", e);
+ }
+ }
+
+ protected String getProperty(String key) {
+ Object obj = user.getProperties().get(key);
+ if (obj != null)
+ return (String) obj;
+ else
+ return "";
+ }
+
+ /**
+ * Updates the property in the working copy. The transaction must be
+ * explicitly committed to persist the update.
+ */
+ @SuppressWarnings("unchecked")
+ protected void setProperty(String key, String value) {
+ user.getProperties().put(key, value);
+ }
+
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ userAdminWrapper.beginTransactionIfNeeded();
+ commitPages(true);
+ firePropertyChange(PROP_DIRTY);
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_REMOVED, user));
+ }
+
+ @Override
+ public void doSaveAs() {
+ }
+
+ @Override
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
+
+ public void refresh() {
+
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ }
+
+ /* DEPENDENCY INJECTION */
+ public void setUserAdminWrapper(UserAdminWrapper userAdminWrapper) {
+ this.userAdminWrapper = userAdminWrapper;
+ this.userAdmin = userAdminWrapper.getUserAdmin();
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.parts;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IPersistableElement;
+
+/**
+ * Editor input for an user defined by unique name (usually a distinguished
+ * name).
+ */
+public class UserEditorInput implements IEditorInput {
+ private final String username;
+
+ public UserEditorInput(String username) {
+ this.username = username;
+ }
+
+ public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
+ return null;
+ }
+
+ public boolean exists() {
+ return username != null;
+ }
+
+ public ImageDescriptor getImageDescriptor() {
+ return null;
+ }
+
+ public String getName() {
+ return username != null ? username : "<new user>";
+ }
+
+ public IPersistableElement getPersistable() {
+ return null;
+ }
+
+ public String getToolTipText() {
+ return username != null ? username : "<new user>";
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof UserEditorInput))
+ return false;
+ if (((UserEditorInput) obj).getUsername() == null)
+ return false;
+ return ((UserEditorInput) obj).getUsername().equals(username);
+ }
+
+ public String getUsername() {
+ return username;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.parts;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.EclipseUiUtils;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.security.ui.admin.internal.ColumnDefinition;
+import org.argeo.security.ui.admin.internal.UserAdminConstants;
+import org.argeo.security.ui.admin.internal.UserAdminWrapper;
+import org.argeo.security.ui.admin.internal.UserTableViewer;
+import org.argeo.security.ui.admin.internal.providers.CommonNameLP;
+import org.argeo.security.ui.admin.internal.providers.RoleIconLP;
+import org.argeo.security.ui.admin.internal.providers.UserNameLP;
+import org.argeo.security.ui.admin.internal.providers.UserTableDefaultDClickListener;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerDropAdapter;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.dnd.TransferData;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.forms.AbstractFormPart;
+import org.eclipse.ui.forms.IManagedForm;
+import org.eclipse.ui.forms.SectionPart;
+import org.eclipse.ui.forms.editor.FormEditor;
+import org.eclipse.ui.forms.editor.FormPage;
+import org.eclipse.ui.forms.widgets.FormToolkit;
+import org.eclipse.ui.forms.widgets.ScrolledForm;
+import org.eclipse.ui.forms.widgets.Section;
+import org.osgi.service.useradmin.Group;
+import org.osgi.service.useradmin.Role;
+import org.osgi.service.useradmin.User;
+import org.osgi.service.useradmin.UserAdmin;
+import org.osgi.service.useradmin.UserAdminEvent;
+
+/** Display/edit the properties common to all users */
+public class UserMainPage extends FormPage implements ArgeoNames {
+ final static String ID = "argeoUserEditor.mainPage";
+
+ // private final static Log log = LogFactory.getLog(UserMainPage.class);
+
+ private final UserEditor editor;
+ private UserAdminWrapper userAdminWrapper;
+
+ private char[] newPassword;
+
+ // Local configuration
+ private final int PRE_TITLE_INDENT = 10;
+
+ public UserMainPage(FormEditor editor, UserAdminWrapper userAdminWrapper) {
+ super(editor, ID, "Main");
+ this.editor = (UserEditor) editor;
+ this.userAdminWrapper = userAdminWrapper;
+ }
+
+ public String getNewPassword() {
+ if (newPassword != null)
+ return new String(newPassword);
+ else
+ return null;
+ }
+
+ public void resetNewPassword() {
+ if (newPassword != null)
+ Arrays.fill(newPassword, 'x');
+ newPassword = null;
+ }
+
+ protected void createFormContent(final IManagedForm mf) {
+ ScrolledForm form = mf.getForm();
+ // Form page main title
+ form.setText(editor.getProperty(UserAdminConstants.KEY_CN));
+
+ // Body
+ Composite body = form.getBody();
+ GridLayout mainLayout = new GridLayout(1, true);
+ body.setLayout(mainLayout);
+ appendOverviewPart(body);
+ appendPasswordPart(body);
+ appendMemberOfPart(body);
+ }
+
+ /** Creates the general section */
+ protected void appendOverviewPart(Composite parent) {
+ FormToolkit tk = getManagedForm().getToolkit();
+ Composite body = addSection(tk, parent, "Main information");
+ body.setLayout(new GridLayout(2, false));
+
+ Text distinguishedName = createLT(body, "User Name",
+ editor.getProperty(UserAdminConstants.KEY_UID));
+ distinguishedName.setEnabled(false);
+
+ final Text commonName = createLT(body, "Common Name",
+ editor.getProperty(UserAdminConstants.KEY_CN));
+ commonName.setEnabled(false);
+
+ final Text firstName = createLT(body, "First name",
+ editor.getProperty(UserAdminConstants.KEY_FIRSTNAME));
+
+ final Text lastName = createLT(body, "Last name",
+ editor.getProperty(UserAdminConstants.KEY_LASTNAME));
+
+ final Text email = createLT(body, "Email",
+ editor.getProperty(UserAdminConstants.KEY_MAIL));
+
+ // create form part (controller)
+ AbstractFormPart part = new SectionPart((Section) body.getParent()) {
+ public void commit(boolean onSave) {
+ // TODO check changed ?
+ // TODO Sanity checks
+
+ editor.setProperty(UserAdminConstants.KEY_FIRSTNAME,
+ firstName.getText());
+ editor.setProperty(UserAdminConstants.KEY_LASTNAME,
+ lastName.getText());
+ editor.setProperty(UserAdminConstants.KEY_CN,
+ commonName.getText());
+ // TODO check mail validity
+ editor.setProperty(UserAdminConstants.KEY_MAIL, email.getText());
+
+ // Enable common name ?
+ // editor.setProperty(UserAdminConstants.KEY_CN,
+ // email.getText());
+ super.commit(onSave);
+ }
+ };
+
+ ModifyListener cnML = new ModifyListener() {
+ private static final long serialVersionUID = 4298649222869835486L;
+
+ @Override
+ public void modifyText(ModifyEvent event) {
+ String first = firstName.getText();
+ String last = lastName.getText();
+ String cn = first.trim() + " " + last.trim() + " ";
+ cn = cn.trim();
+ commonName.setText(cn);
+ getManagedForm().getForm().setText(cn);
+ editor.updateEditorTitle(cn);
+ }
+ };
+ firstName.addModifyListener(cnML);
+ lastName.addModifyListener(cnML);
+ firstName.addModifyListener(new FormPartML(part));
+ lastName.addModifyListener(new FormPartML(part));
+ email.addModifyListener(new FormPartML(part));
+ getManagedForm().addPart(part);
+ }
+
+ /** Creates the password section */
+ protected void appendPasswordPart(Composite parent) {
+ FormToolkit tk = getManagedForm().getToolkit();
+ Composite body = addSection(tk, parent, "Password");
+
+ // Section section = tk.createSection(parent, Section.TITLE_BAR);
+ // section.setLayoutData(EclipseUiUtils.fillWidth());
+ // section.setText("Password");
+ // Composite body = tk.createComposite(section, SWT.NO_FOCUS);
+ // section.setClient(body);
+ // body.setLayoutData(EclipseUiUtils.fillWidth());
+
+ body.setLayout(new GridLayout(2, false));
+ // add widgets (view)
+ final Text password1 = createLP(body, "New password", "");
+ final Text password2 = createLP(body, "Repeat password", "");
+ // create form part (controller)
+ AbstractFormPart part = new SectionPart((Section) body.getParent()) {
+
+ public void commit(boolean onSave) {
+ if (!password1.getText().equals("")
+ || !password2.getText().equals("")) {
+ if (password1.getText().equals(password2.getText())) {
+ newPassword = password1.getText().toCharArray();
+ // TODO real set password
+ password1.setText("");
+ password2.setText("");
+ super.commit(onSave);
+ } else {
+ password1.setText("");
+ password2.setText("");
+ throw new ArgeoException("Passwords are not equals");
+ }
+ }
+ }
+
+ };
+ password1.addModifyListener(new FormPartML(part));
+ password2.addModifyListener(new FormPartML(part));
+ getManagedForm().addPart(part);
+ }
+
+ private UserTableViewer userTableViewerCmp;
+ private TableViewer userViewer;
+
+ private void appendMemberOfPart(Composite parent) {
+ FormToolkit tk = getManagedForm().getToolkit();
+ Composite body = addSection(tk, parent, "Roles");
+ body.setLayout(EclipseUiUtils.noSpaceGridLayout());
+
+ // Define the displayed columns
+ List<ColumnDefinition> columnDefs = new ArrayList<ColumnDefinition>();
+ columnDefs.add(new ColumnDefinition(new RoleIconLP(), "", 0, 24));
+ columnDefs.add(new ColumnDefinition(new UserNameLP(),
+ "Distinguished Name", 300));
+ columnDefs.add(new ColumnDefinition(new CommonNameLP(), "Common Name",
+ 150));
+
+ // Create and configure the table
+ userTableViewerCmp = new MyUserTableViewer(body, SWT.MULTI
+ | SWT.H_SCROLL | SWT.V_SCROLL, userAdminWrapper.getUserAdmin());
+
+ userTableViewerCmp.setColumnDefinitions(columnDefs);
+ userTableViewerCmp.populate(true, false);
+ GridData gd = EclipseUiUtils.fillAll();
+ gd.heightHint = 300;
+ userTableViewerCmp.setLayoutData(gd);
+
+ // Links
+ userViewer = userTableViewerCmp.getTableViewer();
+ userViewer.addDoubleClickListener(new UserTableDefaultDClickListener());
+ // Really?
+ userTableViewerCmp.refresh();
+
+ // Drag and drop
+ int operations = DND.DROP_COPY | DND.DROP_MOVE;
+ Transfer[] tt = new Transfer[] { TextTransfer.getInstance() };
+ userViewer.addDropSupport(operations, tt, new GroupDropListener(
+ userViewer, userAdminWrapper.getUserAdmin(), editor.getDisplayedUser()));
+
+ }
+
+ private class MyUserTableViewer extends UserTableViewer {
+ private static final long serialVersionUID = 8467999509931900367L;
+
+ public MyUserTableViewer(Composite parent, int style,
+ UserAdmin userAdmin) {
+ super(parent, style, userAdmin, true);
+ }
+
+ @Override
+ protected List<User> listFilteredElements(String filter) {
+ return (List<User>) editor.getFlatGroups(null);
+ }
+ }
+
+ /**
+ * Defines this table as being a potential target to add group membership
+ * (roles) to this user
+ */
+ private class GroupDropListener extends ViewerDropAdapter {
+ private static final long serialVersionUID = 2893468717831451621L;
+
+ private final UserAdmin myUserAdmin;
+ private final User myUser;
+
+ public GroupDropListener(Viewer viewer, UserAdmin userAdmin, User user) {
+ super(viewer);
+ this.myUserAdmin = userAdmin;
+ this.myUser = user;
+ }
+
+ @Override
+ public boolean validateDrop(Object target, int operation,
+ TransferData transferType) {
+ // Target is always OK in a list only view
+ // TODO check if not a string
+ boolean validDrop = true;
+ return validDrop;
+ }
+
+ @Override
+ public void drop(DropTargetEvent event) {
+ String name = (String) event.data;
+ Role role = myUserAdmin.getRole(name);
+ // TODO this check should be done before.
+ if (role.getType() == Role.GROUP) {
+ // TODO check if the user is already member of this group
+ userAdminWrapper.beginTransactionIfNeeded();
+ Group group = (Group) role;
+ group.addMember(myUser);
+ userAdminWrapper.notifyListeners(new UserAdminEvent(null,
+ UserAdminEvent.ROLE_CHANGED, group));
+ }
+ super.drop(event);
+ }
+
+ @Override
+ public boolean performDrop(Object data) {
+ userTableViewerCmp.refresh();
+ return true;
+ }
+ }
+
+ // LOCAL HELPERS
+ /** Appends a section with a title */
+ private Composite addSection(FormToolkit tk, Composite parent, String title) {
+ Section section = tk.createSection(parent, Section.TITLE_BAR);
+ GridData gd = EclipseUiUtils.fillWidth();
+ gd.verticalAlignment = PRE_TITLE_INDENT;
+ section.setLayoutData(gd);
+ section.setText(title);
+ Composite body = tk.createComposite(section, SWT.WRAP);
+ body.setLayoutData(EclipseUiUtils.fillAll());
+ section.setClient(body);
+ return body;
+ }
+
+ /** Creates label and multiline text. */
+ protected Text createLMT(Composite body, String label, String value) {
+ FormToolkit toolkit = getManagedForm().getToolkit();
+ Label lbl = toolkit.createLabel(body, label);
+ lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ Text text = toolkit.createText(body, value, SWT.BORDER | SWT.MULTI);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
+ return text;
+ }
+
+ /** Creates label and password. */
+ protected Text createLP(Composite body, String label, String value) {
+ FormToolkit toolkit = getManagedForm().getToolkit();
+ Label lbl = toolkit.createLabel(body, label);
+ lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ Text text = toolkit.createText(body, value, SWT.BORDER | SWT.PASSWORD);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ return text;
+ }
+
+ /** Creates label and text. */
+ protected Text createLT(Composite body, String label, String value) {
+ FormToolkit toolkit = getManagedForm().getToolkit();
+ Label lbl = toolkit.createLabel(body, label);
+ lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ Text text = toolkit.createText(body, value, SWT.BORDER);
+ text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ return text;
+ }
+
+ private class FormPartML implements ModifyListener {
+ private static final long serialVersionUID = 6299808129505381333L;
+ private AbstractFormPart formPart;
+
+ public FormPartML(AbstractFormPart generalPart) {
+ this.formPart = generalPart;
+ }
+
+ public void modifyText(ModifyEvent e) {
+ formPart.markDirty();
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.argeo.security.ui.admin.internal.parts;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.jcr.ArgeoNames;
+import org.argeo.security.UserAdminService;
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.CheckboxCellEditor;
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.ui.forms.AbstractFormPart;
+import org.eclipse.ui.forms.IManagedForm;
+import org.eclipse.ui.forms.editor.FormEditor;
+import org.eclipse.ui.forms.editor.FormPage;
+import org.eclipse.ui.forms.widgets.ScrolledForm;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+/**
+ * Display/edit the roles of a user.
+ */
+public class UserRolesPage extends FormPage implements ArgeoNames {
+ final static String ID = "argeoUserEditor.rolesPage";
+
+ private final static Log log = LogFactory.getLog(UserRolesPage.class);
+ private final static Image ROLE_CHECKED = SecurityAdminPlugin
+ .getImageDescriptor("icons/security.gif").createImage();
+
+ private TableViewer rolesViewer;
+ private UserAdminService userAdminService;
+ private List<String> roles;
+
+ public UserRolesPage(FormEditor editor, UserDetails userDetails,
+ UserAdminService userAdminService) {
+ super(editor, ID, "Roles");
+ setUserDetails(userDetails);
+ this.userAdminService = userAdminService;
+ }
+
+ public void setUserDetails(UserDetails userDetails) {
+ this.roles = new ArrayList<String>();
+ for (GrantedAuthority ga : userDetails.getAuthorities())
+ roles.add(ga.getAuthority());
+ if (rolesViewer != null)
+ rolesViewer.refresh();
+ }
+
+ protected void createFormContent(final IManagedForm mf) {
+ ScrolledForm form = mf.getForm();
+ form.setText("Roles");
+ FillLayout mainLayout = new FillLayout();
+ // ColumnLayout mainLayout = new ColumnLayout();
+ // mainLayout.minNumColumns = 1;
+ // mainLayout.maxNumColumns = 4;
+ // mainLayout.topMargin = 0;
+ // mainLayout.bottomMargin = 5;
+ // mainLayout.leftMargin = mainLayout.rightMargin =
+ // mainLayout.horizontalSpacing = mainLayout.verticalSpacing = 10;
+ form.getBody().setLayout(mainLayout);
+ createRolesPart(form.getBody());
+ }
+
+ /** Creates the role section */
+ protected void createRolesPart(Composite parent) {
+ Table table = new Table(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
+
+ AbstractFormPart part = new AbstractFormPart() {
+ public void commit(boolean onSave) {
+ // roles have already been modified in editing
+ super.commit(onSave);
+ if (log.isTraceEnabled())
+ log.trace("Role part committed");
+ }
+ };
+ getManagedForm().addPart(part);
+
+ // GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
+ // gridData.verticalSpan = 20;
+ // table.setLayoutData(gridData);
+ table.setLinesVisible(true);
+ table.setHeaderVisible(false);
+ rolesViewer = new TableViewer(table);
+
+ // check column
+ TableViewerColumn column = createTableViewerColumn(rolesViewer,
+ "checked", 20);
+ column.setLabelProvider(new ColumnLabelProvider() {
+ private static final long serialVersionUID = -1354458151271666525L;
+
+ public String getText(Object element) {
+ return null;
+ }
+
+ public Image getImage(Object element) {
+ String role = element.toString();
+ if (roles.contains(role)) {
+ return ROLE_CHECKED;
+ } else {
+ return null;
+ }
+ }
+ });
+ column.setEditingSupport(new RoleEditingSupport(rolesViewer, part));
+
+ // role column
+ column = createTableViewerColumn(rolesViewer, "Role", 200);
+ column.setLabelProvider(new ColumnLabelProvider() {
+ private static final long serialVersionUID = 2968056181744306838L;
+
+ public String getText(Object element) {
+ return element.toString();
+ }
+
+ public Image getImage(Object element) {
+ return null;
+ }
+ });
+ rolesViewer.setContentProvider(new RolesContentProvider());
+ rolesViewer.setInput(getEditorSite());
+ }
+
+ protected TableViewerColumn createTableViewerColumn(TableViewer viewer,
+ String title, int bound) {
+ final TableViewerColumn viewerColumn = new TableViewerColumn(viewer,
+ SWT.NONE);
+ final TableColumn column = viewerColumn.getColumn();
+ column.setText(title);
+ column.setWidth(bound);
+ column.setResizable(true);
+ column.setMoveable(true);
+ return viewerColumn;
+
+ }
+
+ public List<String> getRoles() {
+ return roles;
+ }
+
+ public void refresh() {
+ rolesViewer.refresh();
+ }
+
+ private class RolesContentProvider implements IStructuredContentProvider {
+ private static final long serialVersionUID = -1882254608698512781L;
+
+ public Object[] getElements(Object inputElement) {
+ return userAdminService.listEditableRoles().toArray();
+ }
+
+ public void dispose() {
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
+
+ /** Select the columns by editing the checkbox in the first column */
+ class RoleEditingSupport extends EditingSupport {
+ private static final long serialVersionUID = 4041402007711754376L;
+ private final TableViewer viewer;
+ private final AbstractFormPart formPart;
+
+ public RoleEditingSupport(TableViewer viewer, AbstractFormPart formPart) {
+ super(viewer);
+ this.viewer = viewer;
+ this.formPart = formPart;
+ }
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
+
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return true;
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ String role = element.toString();
+ return roles.contains(role);
+
+ }
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ Boolean inRole = (Boolean) value;
+ String role = element.toString();
+ if (inRole && !roles.contains(role)) {
+ roles.add(role);
+ formPart.markDirty();
+ } else if (!inRole && roles.contains(role)) {
+ roles.remove(role);
+ formPart.markDirty();
+ }
+ viewer.refresh();
+ }
+ }
+
+}
import org.argeo.jcr.ArgeoNames;
import org.argeo.security.ui.admin.SecurityAdminPlugin;
import org.argeo.security.ui.admin.internal.ColumnDefinition;
-import org.argeo.security.ui.admin.internal.CommonNameLP;
-import org.argeo.security.ui.admin.internal.MailLP;
import org.argeo.security.ui.admin.internal.UiAdminUtils;
import org.argeo.security.ui.admin.internal.UserAdminConstants;
import org.argeo.security.ui.admin.internal.UserAdminWrapper;
-import org.argeo.security.ui.admin.internal.UserDragListener;
-import org.argeo.security.ui.admin.internal.UserNameLP;
-import org.argeo.security.ui.admin.internal.UserTableDefaultDClickListener;
import org.argeo.security.ui.admin.internal.UserTableViewer;
+import org.argeo.security.ui.admin.internal.providers.CommonNameLP;
+import org.argeo.security.ui.admin.internal.providers.MailLP;
+import org.argeo.security.ui.admin.internal.providers.UserDragListener;
+import org.argeo.security.ui.admin.internal.providers.UserNameLP;
+import org.argeo.security.ui.admin.internal.providers.UserTableDefaultDClickListener;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
--- /dev/null
+package org.argeo.security.ui.admin.internal.providers;
+
+import org.osgi.service.useradmin.User;
+
+/** Simply declare a label provider that returns the common name of a user */
+public class CommonNameLP extends UserAdminAbstractLP {
+ private static final long serialVersionUID = 5256703081044911941L;
+
+ @Override
+ public String getText(User user) {
+ Object obj = user.getProperties().get(KEY_CN);
+ if (obj != null)
+ return (String) obj;
+ else
+ return "";
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.argeo.security.ui.admin.internal.providers;
+
+import org.osgi.service.useradmin.User;
+
+/** Simply declare a label provider that returns the Primary Mail for a user */
+public class MailLP extends UserAdminAbstractLP {
+ private static final long serialVersionUID = 8329764452141982707L;
+
+ @Override
+ public String getText(User user) {
+ Object obj = user.getProperties().get(KEY_MAIL);
+ if (obj != null)
+ return (String) obj;
+ else
+ return "";
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.argeo.security.ui.admin.internal.providers;
+
+import org.argeo.security.ui.admin.SecurityAdminImages;
+import org.eclipse.swt.graphics.Image;
+import org.osgi.service.useradmin.Role;
+import org.osgi.service.useradmin.User;
+
+public class RoleIconLP extends UserAdminAbstractLP {
+ private static final long serialVersionUID = 6550449442061090388L;
+
+ @Override
+ public String getText(User user) {
+ return "";
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ User user = (User) element;
+ if (user.getType() == Role.GROUP)
+ return SecurityAdminImages.ICON_GROUP;
+ else
+ return SecurityAdminImages.ICON_USER;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.argeo.security.ui.admin.internal.providers;
+
+import javax.naming.InvalidNameException;
+import javax.naming.ldap.LdapName;
+
+import org.argeo.security.ui.admin.internal.UiAdminUtils;
+import org.argeo.security.ui.admin.internal.UserAdminConstants;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.widgets.Display;
+import org.osgi.service.useradmin.User;
+
+/**
+ * Utility class that add font modifications to a column label provider
+ * depending on the given user properties
+ */
+public abstract class UserAdminAbstractLP extends ColumnLabelProvider implements
+ UserAdminConstants {
+ private static final long serialVersionUID = 137336765024922368L;
+
+ // private Font italic;
+ private Font bold;
+
+ @Override
+ public Font getFont(Object element) {
+ // Self as bold
+ try {
+ LdapName selfUserName = UiAdminUtils.getLdapName();
+ String userName = UiAdminUtils.getProperty((User) element,
+ UserAdminConstants.KEY_DN);
+ LdapName userLdapName = new LdapName(userName);
+ if (userLdapName.equals(selfUserName))
+ return bold;
+ } catch (InvalidNameException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ // Disabled as Italic
+ // Node userProfile = (Node) elem;
+ // if (!userProfile.getProperty(ARGEO_ENABLED).getBoolean())
+ // return italic;
+
+ return null;
+ // return super.getFont(element);
+ }
+
+ @Override
+ public String getText(Object element) {
+ User user = (User) element;
+ return getText(user);
+ }
+
+ public void setDisplay(Display display) {
+ // italic = JFaceResources.getFontRegistry().defaultFontDescriptor()
+ // .setStyle(SWT.ITALIC).createFont(display);
+ bold = JFaceResources.getFontRegistry().defaultFontDescriptor()
+ .setStyle(SWT.BOLD).createFont(display);
+ }
+
+ public abstract String getText(User user);
+}
--- /dev/null
+package org.argeo.security.ui.admin.internal.providers;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.DragSourceListener;
+import org.osgi.service.useradmin.User;
+
+public class UserDragListener implements DragSourceListener {
+ private static final long serialVersionUID = -2074337775033781454L;
+ private final Viewer viewer;
+
+ public UserDragListener(Viewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public void dragStart(DragSourceEvent event) {
+ // TODO implement finer checks
+ IStructuredSelection selection = (IStructuredSelection) viewer
+ .getSelection();
+ if (selection.isEmpty() || selection.size() > 1)
+ event.doit = false;
+ else
+ event.doit = true;
+ }
+
+ public void dragSetData(DragSourceEvent event) {
+ // TODO Support multiple selection
+ Object obj = ((IStructuredSelection) viewer.getSelection())
+ .getFirstElement();
+ if (obj != null) {
+ User user = (User) obj;
+ event.data = user.getName();
+ }
+ }
+
+ public void dragFinished(DragSourceEvent event) {
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.argeo.security.ui.admin.internal.providers;
+
+import org.osgi.service.useradmin.User;
+
+/** Simply declare a label provider that returns the username of a user */
+public class UserNameLP extends UserAdminAbstractLP {
+ private static final long serialVersionUID = 6550449442061090388L;
+
+ @Override
+ public String getText(User user) {
+ return user.getName();
+ }
+}
--- /dev/null
+package org.argeo.security.ui.admin.internal.providers;
+
+import org.argeo.ArgeoException;
+import org.argeo.eclipse.ui.workbench.WorkbenchUiPlugin;
+import org.argeo.security.ui.admin.internal.parts.UserEditor;
+import org.argeo.security.ui.admin.internal.parts.UserEditorInput;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.osgi.service.useradmin.User;
+
+/**
+ * Default double click listener for the various user tables, will open the
+ * clicked item in the editor
+ */
+public class UserTableDefaultDClickListener implements IDoubleClickListener {
+ public void doubleClick(DoubleClickEvent evt) {
+ if (evt.getSelection().isEmpty())
+ return;
+ Object obj = ((IStructuredSelection) evt.getSelection())
+ .getFirstElement();
+ User user = (User) obj;
+ // IWorkbench iw =
+ IWorkbenchWindow iww = WorkbenchUiPlugin.getDefault().getWorkbench()
+ .getActiveWorkbenchWindow();
+ IWorkbenchPage iwp = iww.getActivePage();
+ UserEditorInput uei = new UserEditorInput(user.getName());
+
+ try {
+ // IEditorPart editor =
+ iwp.openEditor(uei, UserEditor.ID);
+ } catch (PartInitException pie) {
+ throw new ArgeoException("Unable to open UserEditor for " + user,
+ pie);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.argeo.security.ui.admin.internal.providers;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.transaction.Status;
+import javax.transaction.UserTransaction;
+
+import org.argeo.ArgeoException;
+import org.argeo.security.ui.admin.SecurityAdminPlugin;
+import org.eclipse.ui.AbstractSourceProvider;
+import org.eclipse.ui.ISources;
+
+/** Notifies the UI on UserTransaction state change */
+public class UserTransactionProvider extends AbstractSourceProvider {
+ public final static String TRANSACTION_STATE = SecurityAdminPlugin.PLUGIN_ID
+ + ".userTransactionState";
+ public final static String STATUS_ACTIVE = "status.active";
+ public final static String STATUS_NO_TRANSACTION = "status.noTransaction";
+
+ /* DEPENDENCY INJECTION */
+ private UserTransaction userTransaction;
+
+ @Override
+ public String[] getProvidedSourceNames() {
+ return new String[] { TRANSACTION_STATE };
+ }
+
+ @Override
+ public Map<String, String> getCurrentState() {
+ Map<String, String> currentState = new HashMap<String, String>(1);
+ currentState.put(TRANSACTION_STATE, getInternalCurrentState());
+ return currentState;
+ }
+
+ @Override
+ public void dispose() {
+ }
+
+ private String getInternalCurrentState() {
+ try {
+ String transactionState;
+ if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION)
+ transactionState = STATUS_NO_TRANSACTION;
+ else
+ // if (userTransaction.getStatus() == Status.STATUS_ACTIVE)
+ transactionState = STATUS_ACTIVE;
+ return transactionState;
+ } catch (Exception e) {
+ throw new ArgeoException("Unable to begin transaction", e);
+ }
+ }
+
+ /** Publish the ability to notify a state change */
+ public void fireTransactionStateChange() {
+ fireSourceChanged(ISources.WORKBENCH, TRANSACTION_STATE,
+ getInternalCurrentState());
+ }
+
+ /* DEPENDENCY INJECTION */
+ public void setUserTransaction(UserTransaction userTransaction) {
+ this.userTransaction = userTransaction;
+ }
+}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.argeo.security.ui.admin.wizards;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.version.VersionManager;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.ArgeoException;
-import org.argeo.ArgeoMonitor;
-import org.argeo.eclipse.ui.EclipseArgeoMonitor;
-import org.argeo.eclipse.ui.parts.UsersTable;
-import org.argeo.jcr.ArgeoNames;
-import org.argeo.jcr.JcrUtils;
-import org.argeo.security.UserAdminService;
-import org.argeo.security.jcr.JcrUserDetails;
-import org.argeo.security.ui.PrivilegedJob;
-import org.argeo.security.ui.admin.SecurityAdminPlugin;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IPageChangeProvider;
-import org.eclipse.jface.dialogs.IPageChangedListener;
-import org.eclipse.jface.dialogs.PageChangedEvent;
-import org.eclipse.jface.wizard.IWizardContainer;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/** Wizard to update users */
-public class UserBatchUpdateWizard extends Wizard {
- private final static Log log = LogFactory
- .getLog(UserBatchUpdateWizard.class);
- private Session session;
- private UserAdminService userAdminService;
-
- // pages
- private ChooseCommandWizardPage chooseCommandPage;
- private ChooseUsersWizardPage userListPage;
- private ValidateAndLaunchWizardPage validatePage;
-
- // /////////////////////////////////////////////////
- // / Definition of the various implemented commands
- private final static String CMD_UPDATE_PASSWORD = "resetPassword";
- private final static String CMD_GROUP_MEMBERSHIP = "groupMembership";
-
- private final Map<String, String> commands = new HashMap<String, String>() {
- private static final long serialVersionUID = 1L;
- {
- put("Enable user(s)", ArgeoNames.ARGEO_ENABLED);
- put("Expire credentials", ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED);
- put("Expire account(s)", ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED);
- put("Lock account(s)", ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED);
- put("Reset password(s)", CMD_UPDATE_PASSWORD);
- // TODO implement role / group management
- // put("Add/Remove from group", CMD_GROUP_MEMBERSHIP);
- }
- };
-
- public UserBatchUpdateWizard(Session session,
- UserAdminService userAdminService) {
- this.session = session;
- this.userAdminService = userAdminService;
- }
-
- @Override
- public void addPages() {
- chooseCommandPage = new ChooseCommandWizardPage();
- addPage(chooseCommandPage);
- userListPage = new ChooseUsersWizardPage(session);
- addPage(userListPage);
- validatePage = new ValidateAndLaunchWizardPage(session);
- addPage(validatePage);
- }
-
- @Override
- public boolean performFinish() {
- if (!canFinish())
- return false;
-
- UpdateJob job = null;
- if (ArgeoNames.ARGEO_ENABLED.equals(chooseCommandPage.getCommand())) {
- job = new UpdateBoolean(session, userListPage.getSelectedUsers(),
- ArgeoNames.ARGEO_ENABLED,
- chooseCommandPage.getBoleanValue());
- } else if (ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED
- .equals(chooseCommandPage.getCommand())) {
- job = new UpdateBoolean(session, userListPage.getSelectedUsers(),
- ArgeoNames.ARGEO_CREDENTIALS_NON_EXPIRED,
- chooseCommandPage.getBoleanValue());
- } else if (ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED
- .equals(chooseCommandPage.getCommand())) {
- job = new UpdateBoolean(session, userListPage.getSelectedUsers(),
- ArgeoNames.ARGEO_ACCOUNT_NON_EXPIRED,
- chooseCommandPage.getBoleanValue());
- } else if (ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED.equals(chooseCommandPage
- .getCommand())) {
- job = new UpdateBoolean(session, userListPage.getSelectedUsers(),
- ArgeoNames.ARGEO_ACCOUNT_NON_LOCKED,
- chooseCommandPage.getBoleanValue());
- } else if (CMD_UPDATE_PASSWORD.equals(chooseCommandPage.getCommand())) {
- String newValue = chooseCommandPage.getPwdValue();
- if (newValue == null)
- throw new ArgeoException(
- "Password cannot be null or an empty string");
- job = new ResetPassword(session, userAdminService,
- userListPage.getSelectedUsers(), newValue);
- }
-
- if (job != null)
- job.schedule();
- return true;
- }
-
- public void setSession(Session session) {
- this.session = session;
- }
-
- public boolean canFinish() {
- if (this.getContainer().getCurrentPage() == validatePage)
- return true;
- return false;
- }
-
- // /////////////////////////
- // REEL UPDATE JOB
- private class UpdateBoolean extends UpdateJob {
- private String propertyName;
- private boolean value;
-
- public UpdateBoolean(Session session, List<Node> nodesToUpdate,
- String propertyName, boolean value) {
- super(session, nodesToUpdate);
- this.propertyName = propertyName;
- this.value = value;
- }
-
- protected void doUpdate(Node node) {
- try {
- node.setProperty(propertyName, value);
- } catch (RepositoryException re) {
- throw new ArgeoException(
- "Unable to update boolean value for node " + node, re);
- }
- }
- }
-
- private class ResetPassword extends UpdateJob {
- private String newValue;
- private UserAdminService userAdminService;
-
- public ResetPassword(Session session,
- UserAdminService userAdminService, List<Node> nodesToUpdate,
- String newValue) {
- super(session, nodesToUpdate);
- this.newValue = newValue;
- this.userAdminService = userAdminService;
- }
-
- protected void doUpdate(Node node) {
- try {
- String userId = node.getProperty(ArgeoNames.ARGEO_USER_ID)
- .getString();
- if (userAdminService.userExists(userId)) {
- JcrUserDetails userDetails = (JcrUserDetails) userAdminService
- .loadUserByUsername(userId);
- userAdminService.updateUser(userDetails
- .cloneWithNewPassword(newValue));
- }
- } catch (RepositoryException re) {
- throw new ArgeoException(
- "Unable to update boolean value for node " + node, re);
- }
- }
- }
-
- @SuppressWarnings("unused")
- private class AddToGroup extends UpdateJob {
- private String groupID;
- private Session session;
-
- public AddToGroup(Session session, List<Node> nodesToUpdate,
- String groupID) {
- super(session, nodesToUpdate);
- this.session = session;
- this.groupID = groupID;
- }
-
- protected void doUpdate(Node node) {
- log.info("Add/Remove to group actions are not yet implemented");
- // TODO implement this
- // try {
- // throw new ArgeoException("Not yet implemented");
- // } catch (RepositoryException re) {
- // throw new ArgeoException(
- // "Unable to update boolean value for node " + node, re);
- // }
- }
- }
-
- /**
- * Base privileged job that will be run asynchronously to perform the batch
- * update
- */
- private abstract class UpdateJob extends PrivilegedJob {
-
- private final Session currSession;
- private final List<Node> nodesToUpdate;
-
- protected abstract void doUpdate(Node node);
-
- public UpdateJob(Session session, List<Node> nodesToUpdate) {
- super("Perform update");
- try {
- this.currSession = session.getRepository().login();
- // "move" nodes to update in the new session
- // the "old" session will be closed by the calling command
- // before the job has effectively ran
- // TODO there must be a cleaner way to do.
- List<Node> nodes = new ArrayList<Node>();
- for (Node node : nodesToUpdate) {
- nodes.add(currSession.getNode(node.getPath()));
- }
- this.nodesToUpdate = nodes;
- } catch (RepositoryException e) {
- throw new ArgeoException("Error while dupplicating "
- + "session for job", e);
- }
- }
-
- @Override
- protected IStatus doRun(IProgressMonitor progressMonitor) {
- try {
- ArgeoMonitor monitor = new EclipseArgeoMonitor(progressMonitor);
- VersionManager vm = currSession.getWorkspace()
- .getVersionManager();
- int total = nodesToUpdate.size();
- monitor.beginTask("Performing change", total);
- for (Node node : nodesToUpdate) {
- String path = node.getPath();
- vm.checkout(path);
- doUpdate(node);
- currSession.save();
- vm.checkin(path);
- monitor.worked(1);
- }
- } catch (Exception e) {
- log.error("Cannot perform batch update on users", e);
- // e.printStackTrace();
-
- // Dig exception to find the root cause that will enable the
- // user to understand the problem
- Throwable cause = e;
- Throwable originalCause = e;
- while (cause != null) {
- if (log.isTraceEnabled())
- log.trace("Parent Cause message : "
- + cause.getMessage());
- originalCause = cause;
- cause = cause.getCause();
- }
- return new Status(IStatus.ERROR, SecurityAdminPlugin.PLUGIN_ID,
- "Cannot perform updates.", originalCause);
- } finally {
- JcrUtils.logoutQuietly(currSession);
- }
- return Status.OK_STATUS;
- }
- }
-
- // //////////////////////
- // Pages definition
- /** Displays a combo box that enables user to choose which action to perform */
- private class ChooseCommandWizardPage extends WizardPage {
- private static final long serialVersionUID = 1L;
-
- private Combo chooseCommandCmb;
- private Button trueChk;
- private Text valueTxt;
- private Text pwdTxt;
- private Text pwd2Txt;
-
- public ChooseCommandWizardPage() {
- super("Choose a command to run.");
- setTitle("Choose a command to run.");
- }
-
- @Override
- public void createControl(Composite parent) {
- GridLayout gl = new GridLayout();
- Composite container = new Composite(parent, SWT.NO_FOCUS);
- container.setLayout(gl);
-
- chooseCommandCmb = new Combo(container, SWT.NO_FOCUS);
- String[] values = commands.keySet().toArray(
- new String[commands.size()]);
- chooseCommandCmb.setItems(values);
- chooseCommandCmb.setLayoutData(new GridData(SWT.FILL, SWT.TOP,
- true, false));
-
- final Composite bottomPart = new Composite(container, SWT.NO_FOCUS);
- gl = new GridLayout();
- gl.horizontalSpacing = gl.marginWidth = gl.verticalSpacing = 0;
- bottomPart.setLayout(gl);
- bottomPart.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- true));
-
- chooseCommandCmb.addSelectionListener(new SelectionListener() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (getCommand().equals(CMD_UPDATE_PASSWORD))
- populatePasswordCmp(bottomPart);
- else if (getCommand().equals(CMD_GROUP_MEMBERSHIP))
- populateGroupCmp(bottomPart);
- else
- populateBooleanFlagCmp(bottomPart);
- bottomPart.pack(true);
- bottomPart.layout();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- setControl(container);
- }
-
- private void cleanParent(Composite parent) {
- if (parent.getChildren().length > 0) {
- for (Control control : parent.getChildren())
- control.dispose();
- }
- }
-
- private void populateBooleanFlagCmp(Composite parent) {
- cleanParent(parent);
- trueChk = new Button(parent, SWT.CHECK);
- trueChk.setText("Do it. (It will to the contrary if unchecked)");
- trueChk.setSelection(true);
- trueChk.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
- }
-
- private void populatePasswordCmp(Composite parent) {
- cleanParent(parent);
- Composite body = new Composite(parent, SWT.NO_FOCUS);
- body.setLayout(new GridLayout(2, false));
- body.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- pwdTxt = createLP(body, "New password", "");
- pwd2Txt = createLP(body, "Repeat password", "");
- }
-
- /** Creates label and password. */
- protected Text createLP(Composite body, String label, String value) {
- Label lbl = new Label(body, SWT.NONE);
- lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- lbl.setText(label);
- Text text = new Text(body, SWT.BORDER | SWT.PASSWORD);
- text.setText(value);
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- return text;
- }
-
- private void populateGroupCmp(Composite parent) {
- if (parent.getChildren().length > 0) {
- for (Control control : parent.getChildren())
- control.dispose();
- }
- trueChk = new Button(parent, SWT.CHECK);
- trueChk.setText("Add to group. (It will remove user(s) from the "
- + "corresponding group if unchecked)");
- trueChk.setSelection(true);
- trueChk.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
- }
-
- protected String getCommand() {
- return commands.get(chooseCommandCmb.getItem(chooseCommandCmb
- .getSelectionIndex()));
- }
-
- protected String getCommandLbl() {
- return chooseCommandCmb.getItem(chooseCommandCmb
- .getSelectionIndex());
- }
-
- protected boolean getBoleanValue() {
- // FIXME this is not consistent and will lead to errors.
- if (ArgeoNames.ARGEO_ENABLED.equals(getCommand()))
- return trueChk.getSelection();
- else
- return !trueChk.getSelection();
- }
-
- @SuppressWarnings("unused")
- protected String getStringValue() {
- String value = null;
- if (valueTxt != null) {
- value = valueTxt.getText();
- if ("".equals(value.trim()))
- value = null;
- }
- return value;
- }
-
- protected String getPwdValue() {
- String newPwd = null;
- if (pwdTxt == null || pwd2Txt == null)
- return null;
- if (!pwdTxt.getText().equals("") || !pwd2Txt.getText().equals("")) {
- if (pwdTxt.getText().equals(pwd2Txt.getText())) {
- newPwd = pwdTxt.getText();
- pwdTxt.setText("");
- pwd2Txt.setText("");
- } else {
- pwdTxt.setText("");
- pwd2Txt.setText("");
- throw new ArgeoException("Passwords are not equals");
- }
- }
- return newPwd;
- }
- }
-
- /**
- * Displays a list of users with a check box to be able to choose some of
- * them
- */
- private class ChooseUsersWizardPage extends WizardPage implements
- IPageChangedListener {
- private static final long serialVersionUID = 1L;
- private UsersTable userTableCmp;
- private Composite container;
- private Session session;
-
- public ChooseUsersWizardPage(Session session) {
- super("Choose Users");
- this.session = session;
- setTitle("Select users who will be impacted");
- }
-
- @Override
- public void createControl(Composite parent) {
- container = new Composite(parent, SWT.NONE);
- container.setLayout(new FillLayout());
- userTableCmp = new MyUserTableCmp(container, SWT.NO_FOCUS, session);
- userTableCmp.populate(true, true);
- setControl(container);
-
- // Add listener to update message when shown
- final IWizardContainer container = this.getContainer();
- if (container instanceof IPageChangeProvider) {
- ((IPageChangeProvider) container).addPageChangedListener(this);
- }
-
- }
-
- @Override
- public void pageChanged(PageChangedEvent event) {
- if (event.getSelectedPage() == this) {
- String msg = "Chosen batch action: "
- + chooseCommandPage.getCommandLbl();
- ((WizardPage) event.getSelectedPage()).setMessage(msg);
- }
- }
-
- protected List<Node> getSelectedUsers() {
- return userTableCmp.getSelectedUsers();
- }
-
- private class MyUserTableCmp extends UsersTable {
-
- private static final long serialVersionUID = 1L;
-
- public MyUserTableCmp(Composite parent, int style, Session session) {
- super(parent, style, session);
- }
-
- @Override
- protected void refreshFilteredList() {
- List<Node> nodes = new ArrayList<Node>();
- try {
- NodeIterator ni = listFilteredElements(session,
- getFilterString());
-
- users: while (ni.hasNext()) {
- Node currNode = ni.nextNode();
- String username = currNode.hasProperty(ARGEO_USER_ID) ? currNode
- .getProperty(ARGEO_USER_ID).getString() : "";
- if (username.equals(session.getUserID()))
- continue users;
- else
- nodes.add(currNode);
- }
- getTableViewer().setInput(nodes.toArray());
- } catch (RepositoryException e) {
- throw new ArgeoException("Unable to list users", e);
- }
- }
- }
- }
-
- /**
- * Recapitulation of input data before running real update
- */
- private class ValidateAndLaunchWizardPage extends WizardPage implements
- IPageChangedListener {
- private static final long serialVersionUID = 1L;
- private UsersTable userTableCmp;
- private Session session;
-
- public ValidateAndLaunchWizardPage(Session session) {
- super("Validate and launch");
- this.session = session;
- setTitle("Validate and launch");
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite mainCmp = new Composite(parent, SWT.NO_FOCUS);
- mainCmp.setLayout(new FillLayout());
-
- // Add listener to update user list when shown
- final IWizardContainer container = this.getContainer();
- if (container instanceof IPageChangeProvider) {
- ((IPageChangeProvider) container).addPageChangedListener(this);
- }
-
- userTableCmp = new UsersTable(mainCmp, SWT.NO_FOCUS, session);
- userTableCmp.populate(false, false);
- setControl(mainCmp);
- }
-
- @Override
- public void pageChanged(PageChangedEvent event) {
- if (event.getSelectedPage() == this) {
- @SuppressWarnings({ "unchecked", "rawtypes" })
- Object[] values = ((ArrayList) userListPage.getSelectedUsers())
- .toArray(new Object[userListPage.getSelectedUsers()
- .size()]);
- userTableCmp.getTableViewer().setInput(values);
- String msg = "Following batch action: ["
- + chooseCommandPage.getCommandLbl()
- + "] will be perfomed on the users listed below.\n"
- + "Are you sure you want to proceed?";
- ((WizardPage) event.getSelectedPage()).setMessage(msg);
- }
- }
-
- // private class MyUserTableCmp extends UserTableComposite {
- // public MyUserTableCmp(Composite parent, int style, Session session) {
- // super(parent, style, session);
- // }
- //
- // @Override
- // protected void refreshFilteredList() {
- // @SuppressWarnings({ "unchecked", "rawtypes" })
- //
- // setFilteredList(values);
- // }
- //
- // @Override
- // public void setVisible(boolean visible) {
- // super.setVisible(visible);
- // if (visible)
- // refreshFilteredList();
- // }
- // }
- }
-}
\ No newline at end of file