midpoint的官网文档虽说较详细,但是很多示例代码的使用却介绍的很一般,本篇将记录一些midpoint框架的开发示例。
1.本地接口调用
IDM model接口的调用官网介绍地址为:https://wiki.evolveum.com/display/midPoint/IDM+Model+Interface+Introduction 其对本地调用Model完成数据的存储进行了较详细的介绍,但是并没有完整的示例代码,下面将会贴出一份完整的创建用户的示例代码,如下:
package org.test.page;
import java.util.Collection;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.springframework.beans.factory.annotation.Autowired;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.model.api.ModelService;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.web.application.AuthorizationAction;
import com.evolveum.midpoint.web.application.PageDescriptor;
import com.evolveum.midpoint.web.application.Url;
import com.evolveum.midpoint.web.component.AjaxSubmitButton;
import com.evolveum.midpoint.web.component.form.Form;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
@PageDescriptor(
urls = {
@Url(mountUrl = "/demohw2", matchUrlForSecurity = "/demohw2")
},
action = {
@AuthorizationAction(actionUri = "http://midpoint.evolveum.com/xml/ns/public/security/authorization-ui-3#demohw",
label = "DemoHelloWord.auth.usersAll.label",
description = "DemoHelloWord.auth.usersAll.description")
})
public class DemoPage2 extends WebPage {
//该处使用的是com.evolveum.midpoint.model.impl.controller.ModelController作为ModelService
@SpringBean(name = "modelController")
private ModelService modelService;
ModelService modelService;
public DemoPage2(PageParameters parameters) {
super(parameters);
DetailForm userForm=new DetailForm("userForm");
add(userForm);
AjaxSubmitButton button = new AjaxSubmitButton("save") {
};
userForm.setDefaultButton(button);
userForm.add(button);
}
public DemoPage2() {
this(null);
}
class DetailForm extends Form{
private TextField usernameField;
private PasswordTextField passwordField;
private TextField descriptionField;
public DetailForm(String id) {
super(id);
usernameField = new TextField("username", Model.of(""));
passwordField = new PasswordTextField("password", Model.of(""));
descriptionField = new TextField("description", Model.of(""));
add(usernameField);
add(passwordField);
add(descriptionField);
}
public final void onSubmit() {
String username = (String)usernameField.getDefaultModelObject();
String password = (String)passwordField.getDefaultModelObject();
String description = (String)descriptionField.getDefaultModelObject();
//-------------------------创建用户核心代码-------------------------------- UserType userType = new UserType();
userType.setName(new PolyStringType(username));
userType.setDescription(description);
CredentialsType pwdc = new CredentialsType();
PasswordType pwdType = new PasswordType();
ProtectedStringType st = new ProtectedStringType();
st.setClearValue(password);
pwdType.setValue(st);
pwdc.setPassword(pwdType);
userType.setCredentials(pwdc);
PrismObject<UserType> user = userType.asPrismObject(); // parse or instantiate the user
try {
WebComponentUtil.encryptCredentials(user, true, getMidpointApplication());
getPrismContext().adopt(user, UserType.class);
ObjectDelta<UserType> userAddDelta = ObjectDelta.createAddDelta(user);
Collection<ObjectDelta<? extends ObjectType>> deltas = MiscSchemaUtil.createCollection(userAddDelta);
OperationResult result = new OperationResult(DemoPage2.class+".save");
Task task = createSimpleTask("save");
modelService.executeChanges(deltas, null, task, result);//创建用户
setResponsePage(DemoPage.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2.Rest方式调用
官网Rest方式的介绍网址为https://wiki.evolveum.com/display/midPoint/REST+API
Rest方式的示例代码如下:
import java.io.Exception;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
public class RestDemo{
public static void main(String[] args){
Client client = ClientBuilder.newClient();
String authUser = "administrator";
String authPass = "5ecr3t";
String authorizationCode = "Basic " + org.apache.cxf.common.util.Base64Utility
.encode((authUser + ":" + (authPass == null ? "" : authPass)).getBytes());
String userOid = "00000000-0000-0000-0000-000000000002";
String roleOid = "00000000-0000-0000-0000-000000000004";
try {
HashMap<String,String> binding=new HashMap<String,String>();
binding.put("userOid", userOid);
binding.put("roleOid", roleOid);
String restBody = this.getTemplatedXmlBody("/modify-user-assign-role.xml", binding);
Entity<String> postBody = Entity.xml(restBody);
String baseUrl = "http://localhost:10088/midpoint/ws/rest";
WebTarget base = client.target(baseUrl);
WebTarget searchResource = base.path("/users/"+userOid);
Response response = searchResource.request(MediaType.APPLICATION_XML_TYPE)
.header("Authorization", authorizationCode)
.post(postBody,Response.class);
if(response.getStatus()==200) {
String result = response.readEntity(String.class);
System.out.println("权限修改成功");
}else {
System.out.println("权限修改失败,响应错误码时:"+response.getStatus());
}
}catch(Exception e) {
e.printStackTrace();
}finally {
client.close();
}
}
private String getTemplatedXmlBody(String template,Map binding) {
String result="";
try {
SimpleTemplateEngine engine = new SimpleTemplateEngine();
InputStream is=this.getClass().getResourceAsStream(template);
InputStreamReader reader = new InputStreamReader(is);
Writable w = engine.createTemplate(reader).make(binding);
reader.close();
result = w.toString();
} catch (Exception e) {
e.printStackTrace();
return result;
}
}
modify-user-assign-role.xml内容如下
<objectModification
xmlns='http://midpoint.evolveum.com/xml/ns/public/common/api-types-3'
xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3">
<itemDelta>
<t:modificationType>add</t:modificationType>
<t:path>c:assignment</t:path>
<t:value>
<c:targetRef oid="${roleOid}" type="c:RoleType" />
</t:value>
</itemDelta>
</objectModification>
更多业务处理的Rest方式的xml示例可在源码工程中的samples/rest下找到,如下图:
3.WebService方式
官网中该方式为客户端方式使用midpoint,官网介绍地址为https://wiki.evolveum.com/display/midPoint/Model+Web+Service+Client+Sample
从该介绍中我们知道可以在源码提供的示例代码model-client-sample工程中进行学习,项目结构如下图:
下面时一个简单的WebService方式的示例代码:
package com.evolveum.midpoint.testing.model.client.sample;
import com.evolveum.midpoint.model.client.ModelClientUtil;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage;
import com.evolveum.midpoint.xml.ns._public.model.model_3.ModelPortType;
import com.evolveum.midpoint.xml.ns._public.model.model_3.ModelService;
import com.evolveum.prism.xml.ns._public.query_3.QueryType;
import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.wss4j.dom.handler.WSHandlerConstants;
import org.apache.wss4j.dom.WSConstants;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.dom.DOMResult;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static final String ADM_USERNAME = "administrator";
public static final String ADM_PASSWORD = "5ecr3t";
private static final String DEFAULT_ENDPOINT_URL = "http://localhost:8080/model/model-3";
public static void main(String[] args) {
try {
ModelPortType modelPort = createModelPort(args);
UserType userAdministrator = searchUserByName(modelPort, "administrator");
System.out.println("Got administrator user: "+userAdministrator.getOid());
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
public static ModelPortType createModelPort(String[] args) {
String endpointUrl = DEFAULT_ENDPOINT_URL;
if (args.length > 0) {
endpointUrl = args[0];
}
System.out.println("Endpoint URL: "+endpointUrl);
// uncomment this if you want to use Fiddler or any other proxy
//ProxySelector.setDefault(new MyProxySelector("127.0.0.1", 8888));
ModelService modelService = new ModelService();
ModelPortType modelPort = modelService.getModelPort();
BindingProvider bp = (BindingProvider)modelPort;
Map<String, Object> requestContext = bp.getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointUrl);
org.apache.cxf.endpoint.Client client = ClientProxy.getClient(modelPort);
org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint();
Map<String,Object> outProps = new HashMap<>();
outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
outProps.put(WSHandlerConstants.USER, ADM_USERNAME);
outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST);
outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName());
WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);
cxfEndpoint.getOutInterceptors().add(wssOut);
// enable the following to get client-side logging of outgoing requests and incoming responses
cxfEndpoint.getOutInterceptors().add(new LoggingOutInterceptor());
cxfEndpoint.getInInterceptors().add(new LoggingInInterceptor());
return modelPort;
}
private static UserType searchUserByName(ModelPortType modelPort, String username) throws SAXException, IOException, FaultMessage, JAXBException {
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
Holder<ObjectListType> objectListHolder = new Holder<>();
Holder<OperationResultType> resultHolder = new Holder<>();
modelPort.searchObjects(ModelClientUtil.getTypeQName(UserType.class), createUserQuery1(username), options, objectListHolder, resultHolder);
ObjectListType objectList = objectListHolder.value;
List<ObjectType> objects = objectList.getObject();
if (objects.isEmpty()) {
return null;
}
if (objects.size() == 1) {
return (UserType) objects.get(0);
}
throw new IllegalStateException("Expected to find a single user with username '"+username+"' but found "+objects.size()+" users instead");
}
private static QueryType createUserQuery1(String username) throws JAXBException, SAXException, IOException {
// WARNING: in a real case make sure that the username is properly escaped before putting it in XML
SearchFilterType filter = ModelClientUtil.parseSearchFilterType(
"<equal xmlns='http://prism.evolveum.com/xml/ns/public/query-3' xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3' >" +
"<path>c:name</path>" +
"<value>" + username + "</value>" +
"</equal>"
);
QueryType query = new QueryType();
query.setFilter(filter);
return query;
}
}