]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
116599fe7e26cb3edb0eb4ccf2938b47deb9b8de
[tmp/jakarta-migration.git] /
1 package org.collectionspace.services.common.vocabulary;
2
3 import java.util.List;
4 import java.util.regex.Matcher;
5 import java.util.regex.Pattern;
6
7 import javax.ws.rs.core.Response;
8
9 import org.collectionspace.services.client.AuthorityClient;
10 import org.collectionspace.services.client.PoxPayloadIn;
11 import org.collectionspace.services.common.ServiceMain;
12 import org.collectionspace.services.common.api.Tools;
13 import org.collectionspace.services.common.context.MultipartServiceContextImpl;
14 import org.collectionspace.services.common.context.ServiceContext;
15 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
16 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
17 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityIdentifierUtils;
18 import org.collectionspace.services.config.service.ServiceBindingType;
19 import org.collectionspace.services.config.tenant.RemoteClientConfig;
20 import org.collectionspace.services.config.tenant.RemoteClientConfigurations;
21 import org.collectionspace.services.config.tenant.TenantBindingType;
22 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
23 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
24 import org.collectionspace.services.common.document.DocumentException;
25
26 //import org.dom4j.DocumentException;
27 import org.nuxeo.ecm.core.api.DocumentModel;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 @SuppressWarnings("rawtypes")
32 public class AuthorityServiceUtils {
33         private static final Logger logger = LoggerFactory.getLogger(AuthorityServiceUtils.class);
34         //
35         // Used to keep track if an authority item's is deprecated
36         public static final String DEFAULT_REMOTECLIENT_CONFIG_NAME = "default";
37         public static final String IS_DEPRECATED_PROPERTY = "IS_DEPRECATED_PROPERTY";
38         public static final Boolean DEPRECATED = true;
39         public static final Boolean NOT_DEPRECATED = !DEPRECATED;
40
41         // Used to keep track if an authority item's rev number should be updated
42         public static final String SHOULD_UPDATE_REV_PROPERTY = "SHOULD_UPDATE_REV_PROPERTY";
43         public static final boolean UPDATE_REV = true;
44         public static final boolean DONT_UPDATE_REV = !UPDATE_REV;
45
46         // Used to keep track if an authority item is a locally proposed member of a SAS authority
47         public static final String IS_PROPOSED_PROPERTY = "IS_PROPOSED";
48         public static final Boolean PROPOSED = true;
49         public static final Boolean NOT_PROPOSED = !PROPOSED;
50         public static final Boolean SAS_ITEM = true;
51         public static final Boolean NOT_SAS_ITEM = !SAS_ITEM;
52
53         public static final Boolean NO_CHANGE = null;
54
55         // Matches the domain name part of a refname. For example, "core.collectionspace.org" of
56         // urn:cspace:core.collectionspace.org:personauthorities:name(person):item:name(BigBird1461101206103)'Big Bird'.
57         public static final     Pattern REFNAME_DOMAIN_PATTERN = Pattern.compile("(urn:cspace:)(([a-z]{1,}\\.?)*)");
58
59         /*
60          * Try to find a named remote client configuration in the current tenant bindings.  If the value of the incoming param 'remoteClientConfigName' is
61          * blank or null, we'll try to find a name in the authority service's bindings.  If we can't find a name there, we'll try using the default name.
62          *
63          * If the incoming param 'remoteClientConfigName' is not null, we'll look through all the named remote client configurations in the tenant's binding
64          * to find the configuration.  If we can't find the named configuration, we'll throw an exception.
65          *
66          * If there are no remote client configurations in the tenant's bindings, we'll throw an exception.
67          */
68         public static final RemoteClientConfig getRemoteClientConfig(ServiceContext ctx, String remoteClientConfigName) throws Exception {
69                 RemoteClientConfig result = null;
70
71                 TenantBindingType tenantBinding = ServiceMain.getInstance().getTenantBindingConfigReader().getTenantBinding(ctx.getTenantId());
72                 RemoteClientConfigurations remoteClientConfigurations = tenantBinding.getRemoteClientConfigurations();
73                 if (remoteClientConfigurations != null) {
74                         if (Tools.isEmpty(remoteClientConfigName) == true) {
75                                 // Since the authority instance didn't specify a remote client config name, let's see if the authority type's service bindings specifies one
76                                 ServiceBindingType serviceBindingType =
77                                                 ServiceMain.getInstance().getTenantBindingConfigReader().getServiceBinding(ctx.getTenantId(), ctx.getServiceName());
78                                 remoteClientConfigName = serviceBindingType.getRemoteClientConfigName();
79                         }
80                         //
81                         // If we still don't have a remote client config name, let's use the default value.
82                         //
83                         if (Tools.isEmpty(remoteClientConfigName) == true) {
84                                 remoteClientConfigName = DEFAULT_REMOTECLIENT_CONFIG_NAME;
85                         }
86
87                         List<RemoteClientConfig> remoteClientConfigList = remoteClientConfigurations.getRemoteClientConfig();
88                         for (RemoteClientConfig config : remoteClientConfigList) {
89                                 if (config.getName().equalsIgnoreCase(remoteClientConfigName)) {
90                                         result = config;
91                                         break;
92                                 }
93                         }
94                 } else {
95                         String errMsg = String.format("No remote client configurations could be found in the tenant bindings for tenant named '%s'.",
96                                         ctx.getTenantName());
97                         logger.error(errMsg);
98                         throw new Exception(errMsg);
99                 }
100
101                 if (result == null) {
102                         String errMsg = String.format("Could not find a remote client configuration named '%s' in the tenant bindings for tenant named '%s'",
103                                         remoteClientConfigName, ctx.getTenantName());
104                         logger.error(errMsg);
105                         throw new Exception(errMsg);
106                 }
107
108                 return result;
109         }
110
111         /**
112          * Make a request to the SAS Server for an authority payload.
113          *
114          * @param ctx
115          * @param specifier
116          * @param responseType
117          * @return
118          * @throws Exception
119          */
120         public static PoxPayloadIn requestPayloadInFromRemoteServer(ServiceContext ctx, String remoteClientConfigName, Specifier specifier, Class responseType) throws Exception {
121                 PoxPayloadIn result = null;
122
123                 RemoteClientConfig remoteClientConfig = getRemoteClientConfig(ctx, remoteClientConfigName);
124                 AuthorityClient client = (AuthorityClient) ctx.getClient(remoteClientConfig);
125
126                 Response res = client.read(specifier.getURNValue());
127                 try {
128                         int statusCode = res.getStatus();
129                         if (statusCode == org.apache.commons.httpclient.HttpStatus.SC_OK) {
130                                 result = new PoxPayloadIn((String)res.readEntity(responseType)); // Get the entire response!
131                         } else {
132                                 String errMsg = String.format("Could not retrieve authority information for '%s' on remote server '%s'.  Server returned status code %d",
133                                                 specifier.getURNValue(), remoteClientConfig.getUrl(), statusCode);
134                                 if (logger.isDebugEnabled()) {
135                                         logger.debug(errMsg);
136                                 }
137                                 throw new DocumentException(statusCode, errMsg);
138                         }
139                 } finally {
140                         res.close();
141                 }
142
143                 return result;
144         }
145
146         //
147         // Makes a call to the remote SAS server for a authority item payload
148         //
149         public static PoxPayloadIn requestPayloadInFromRemoteServer(
150                         AuthorityItemSpecifier specifier,
151                         String remoteClientConfigName,
152                         String serviceName,
153                         Class responseType,
154                         boolean syncHierarchicalRelationships) throws Exception {
155                 PoxPayloadIn result = null;
156
157                 ServiceContext authorityCtx = new MultipartServiceContextImpl(serviceName);
158                 RemoteClientConfig remoteClientConfig = getRemoteClientConfig(authorityCtx, remoteClientConfigName);
159                 AuthorityClient client = (AuthorityClient) authorityCtx.getClient(remoteClientConfig);
160                 Response res = client.readItem(specifier.getParentSpecifier().getURNValue(), specifier.getItemSpecifier().getURNValue(),
161                                 AuthorityClient.INCLUDE_DELETED_ITEMS, syncHierarchicalRelationships);
162
163                 try {
164                         int statusCode = res.getStatus();
165                         if (statusCode == org.apache.commons.httpclient.HttpStatus.SC_OK) {
166                                 result = new PoxPayloadIn((String)res.readEntity(responseType)); // Get the entire response.
167                         } else {
168                                 String errMsg = String.format("Could not retrieve authority item information for '%s:%s' on remote server '%s'.  Server returned status code %d",
169                                                 specifier.getParentSpecifier().getURNValue(), specifier.getItemSpecifier().getURNValue(), remoteClientConfig.getUrl(), statusCode);
170                                 if (logger.isDebugEnabled()) {
171                                         logger.debug(errMsg);
172                                 }
173                                 throw new DocumentException(statusCode, errMsg);
174                         }
175                 } finally {
176                         res.close();
177                 }
178
179                 return result;
180         }
181
182         public static boolean setAuthorityItemDeprecated(ServiceContext ctx,
183                         DocumentModel docModel, String authorityItemCommonSchemaName, Boolean flag) throws Exception {
184                 boolean result = false;
185
186                 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.DEPRECATED,
187                                 new Boolean(flag));
188                 CoreSessionInterface repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession();
189                 repoSession.saveDocument(docModel);
190                 result = true;
191
192                 return result;
193         }
194
195         /*
196          * The domain name part of refnames on a remote SAS may not match that of local refnames.
197          * Update all the payload's refnames with the local domain name.
198          */
199         public static PoxPayloadIn localizeRefNameDomains(ServiceContext ctx, PoxPayloadIn payload) throws org.dom4j.DocumentException {
200                 String localDomain = ctx.getTenantName();
201                 Matcher matcher = REFNAME_DOMAIN_PATTERN.matcher(payload.getXmlPayload());
202                 StringBuffer localizedXmlBuffer = new StringBuffer();
203
204                 while (matcher.find() == true) {
205                         String remoteDomain = matcher.group(2);
206
207                         if (logger.isDebugEnabled()) {
208                                 logger.debug("Replacing " + remoteDomain + " with " + localDomain);
209                         }
210
211                         matcher.appendReplacement(localizedXmlBuffer, matcher.group(1) + localDomain);
212                 }
213
214                 matcher.appendTail(localizedXmlBuffer);
215
216                 if (logger.isTraceEnabled()) {
217                         logger.trace(String.format("Updated payload:\n%s", localizedXmlBuffer));
218                 }
219
220                 return new PoxPayloadIn(localizedXmlBuffer.toString());
221         }
222
223         /**
224          * Mark the authority item as deprecated.
225          *
226          * @param ctx
227          * @param itemInfo
228          * @throws Exception
229          */
230         public static boolean markAuthorityItemAsDeprecated(ServiceContext ctx, String authorityItemCommonSchemaName, AuthorityItemSpecifier authorityItemSpecifier) throws Exception {
231                 boolean result = false;
232
233                 try {
234                         DocumentModel docModel = NuxeoUtils.getDocFromSpecifier(ctx, (CoreSessionInterface)ctx.getCurrentRepositorySession(),
235                                         authorityItemCommonSchemaName, authorityItemSpecifier);
236                         result = setAuthorityItemDeprecated(ctx, docModel, authorityItemCommonSchemaName, AuthorityServiceUtils.DEPRECATED);
237                 } catch (Exception e) {
238                         logger.warn(String.format("Could not mark item '%s' as deprecated.", authorityItemSpecifier.getItemSpecifier().getURNValue()), e);
239                         throw e;
240                 }
241
242                 return result;
243         }
244 }