]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d083dc02b586c24756cfdc881ebe6a24dd7284c8
[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(AuthorityIdentifierUtils.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     /*
56      * Try to find a named remote client configuration in the current tenant bindings.  If the value of the incoming param 'remoteClientConfigName' is
57      * 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.
58      * 
59      * If the incoming param 'remoteClientConfigName' is not null, we'll look through all the named remote client configurations in the tenant's binding
60      * to find the configuration.  If we can't find the named configuration, we'll throw an exception.
61      * 
62      * If there are no remote client configurations in the tenant's bindings, we'll throw an exception.
63      */
64         public static final RemoteClientConfig getRemoteClientConfig(ServiceContext ctx, String remoteClientConfigName) throws Exception {
65         RemoteClientConfig result = null;
66         
67         TenantBindingType tenantBinding = ServiceMain.getInstance().getTenantBindingConfigReader().getTenantBinding(ctx.getTenantId());
68         RemoteClientConfigurations remoteClientConfigurations = tenantBinding.getRemoteClientConfigurations();
69         if (remoteClientConfigurations != null) {
70                 if (Tools.isEmpty(remoteClientConfigName) == true) {
71                         // Since the authority instance didn't specify a remote client config name, let's see if the authority type's service bindings specifies one
72                         ServiceBindingType serviceBindingType =
73                                         ServiceMain.getInstance().getTenantBindingConfigReader().getServiceBinding(ctx.getTenantId(), ctx.getServiceName());
74                         remoteClientConfigName = serviceBindingType.getRemoteClientConfigName();
75                 }
76                 //
77                 // If we still don't have a remote client config name, let's use the default value.
78                 //
79                 if (Tools.isEmpty(remoteClientConfigName) == true) {
80                         remoteClientConfigName = DEFAULT_REMOTECLIENT_CONFIG_NAME;
81                 }
82                 
83                 List<RemoteClientConfig> remoteClientConfigList = remoteClientConfigurations.getRemoteClientConfig();
84                 for (RemoteClientConfig config : remoteClientConfigList) {
85                         if (config.getName().equalsIgnoreCase(remoteClientConfigName)) {
86                                 result = config;
87                                 break;
88                         }
89                 }
90         } else {
91                 String errMsg = String.format("No remote client configurations could be found in the tenant bindings for tenant named '%s'.",
92                                 ctx.getTenantName());
93                 logger.error(errMsg);
94                 throw new Exception(errMsg);
95         }
96         
97         if (result == null) {
98                 String errMsg = String.format("Could not find a remote client configuration named '%s' in the tenant bindings for tenant named '%s'",
99                                 remoteClientConfigName, ctx.getTenantName());
100                 logger.error(errMsg);
101                 throw new Exception(errMsg);
102         }
103         
104         return result;
105     }
106     
107     /**
108      * Make a request to the SAS Server for an authority payload.
109      * 
110      * @param ctx
111      * @param specifier
112      * @param responseType
113      * @return
114      * @throws Exception
115      */
116     static public PoxPayloadIn requestPayloadInFromRemoteServer(ServiceContext ctx, String remoteClientConfigName, Specifier specifier, Class responseType) throws Exception {
117         PoxPayloadIn result = null;
118         
119         RemoteClientConfig remoteClientConfig = getRemoteClientConfig(ctx, remoteClientConfigName);
120         AuthorityClient client = (AuthorityClient) ctx.getClient(remoteClientConfig);
121         
122         Response res = client.read(specifier.getURNValue());
123         try {
124                 int statusCode = res.getStatus();
125                 if (statusCode == org.apache.commons.httpclient.HttpStatus.SC_OK) {
126                     result = new PoxPayloadIn((String)res.readEntity(responseType)); // Get the entire response!                                        
127                 } else {
128                         String errMsg = String.format("Could not retrieve authority information for '%s' on remote server '%s'.  Server returned status code %d",
129                                         specifier.getURNValue(), remoteClientConfig.getUrl(), statusCode);
130                         if (logger.isDebugEnabled()) {
131                             logger.debug(errMsg);
132                         }
133                         throw new DocumentException(statusCode, errMsg);
134                 }
135         } finally {
136                 res.close();
137         }
138         
139         return result;
140     }
141     
142     //
143     // Makes a call to the remote SAS server for a authority item payload
144     //    
145     static public PoxPayloadIn requestPayloadInFromRemoteServer(
146                 AuthorityItemSpecifier specifier, 
147                 String remoteClientConfigName, 
148                 String serviceName, 
149                 Class responseType, 
150                 boolean syncHierarchicalRelationships) throws Exception {
151         PoxPayloadIn result = null;
152         
153         ServiceContext authorityCtx = new MultipartServiceContextImpl(serviceName);
154         RemoteClientConfig remoteClientConfig = getRemoteClientConfig(authorityCtx, remoteClientConfigName);
155         AuthorityClient client = (AuthorityClient) authorityCtx.getClient(remoteClientConfig);
156         Response res = client.readItem(specifier.getParentSpecifier().getURNValue(), specifier.getItemSpecifier().getURNValue(),
157                         AuthorityClient.INCLUDE_DELETED_ITEMS, syncHierarchicalRelationships);
158         
159         try {
160                 int statusCode = res.getStatus();
161                 if (statusCode == org.apache.commons.httpclient.HttpStatus.SC_OK) {
162                     result = new PoxPayloadIn((String)res.readEntity(responseType)); // Get the entire response.
163                 } else {
164                         String errMsg = String.format("Could not retrieve authority item information for '%s:%s' on remote server '%s'.  Server returned status code %d",
165                                         specifier.getParentSpecifier().getURNValue(), specifier.getItemSpecifier().getURNValue(), remoteClientConfig.getUrl(), statusCode);
166                         if (logger.isDebugEnabled()) {
167                             logger.debug(errMsg);
168                         }
169                         throw new DocumentException(statusCode, errMsg);
170                 }               
171         } finally {
172                 res.close();
173         }
174         
175         return result;
176     }
177     
178     static public boolean setAuthorityItemDeprecated(ServiceContext ctx,
179                 DocumentModel docModel, String authorityItemCommonSchemaName, Boolean flag) throws Exception {
180         boolean result = false;
181         
182         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.DEPRECATED,
183                         new Boolean(flag));
184         CoreSessionInterface repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession();
185         repoSession.saveDocument(docModel);
186         result = true;
187         
188         return result;
189     }
190     
191     /*
192      * The domain name part of refnames on SAS may not match that of local refnames, so we need to update all the payload's
193      * refnames with the correct domain name
194      */
195         static public PoxPayloadIn filterRefnameDomains(ServiceContext ctx,
196                         PoxPayloadIn payload) throws org.dom4j.DocumentException {
197                 PoxPayloadIn result = null;
198
199                 
200                 String payloadStr = payload.getXmlPayload();
201                 Pattern p = Pattern.compile("(urn:cspace:)(([a-z]{1,}\\.?)*)"); // matches the domain name part of a RefName.  For example, matches "core.collectionspace.org" of RefName urn:cspace:core.collectionspace.org:personauthorities:name(person):item:name(BigBird1461101206103)'Big Bird'
202                 Matcher m = p.matcher(payloadStr);
203
204                 StringBuffer filteredPayloadStr = new StringBuffer();
205                 while (m.find() == true) {
206                         if (logger.isDebugEnabled()) {
207                                 logger.debug("Replacing: " + m.group(2));
208                         }
209                         m.appendReplacement(filteredPayloadStr, m.group(1) + ctx.getTenantName());
210                 }
211                 m.appendTail(filteredPayloadStr);
212                 result = new PoxPayloadIn(filteredPayloadStr.toString());
213
214                 if (logger.isDebugEnabled()) {
215                         logger.debug(String.format("", filteredPayloadStr));
216                 }
217
218                 return result;
219         }
220     
221     /**
222      * Mark the authority item as deprecated.
223      * 
224      * @param ctx
225      * @param itemInfo
226      * @throws Exception
227      */
228     static public boolean markAuthorityItemAsDeprecated(ServiceContext ctx, String authorityItemCommonSchemaName, AuthorityItemSpecifier authorityItemSpecifier) throws Exception {
229         boolean result = false;
230         
231         try {
232                 DocumentModel docModel = NuxeoUtils.getDocFromSpecifier(ctx, (CoreSessionInterface)ctx.getCurrentRepositorySession(),
233                                 authorityItemCommonSchemaName, authorityItemSpecifier);
234                 result = setAuthorityItemDeprecated(ctx, docModel, authorityItemCommonSchemaName, AuthorityServiceUtils.DEPRECATED);
235         } catch (Exception e) {
236                 logger.warn(String.format("Could not mark item '%s' as deprecated.", authorityItemSpecifier.getItemSpecifier().getURNValue()), e);
237                 throw e;
238         }
239         
240         return result;
241     }
242 }