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