2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.services.common.config;
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.util.ArrayList;
31 import java.util.Enumeration;
32 import java.util.Hashtable;
33 import java.util.List;
35 import org.apache.commons.io.FileUtils;
36 import org.collectionspace.services.common.ServiceMain;
37 import org.collectionspace.services.common.api.JEEServerDeployment;
38 import org.collectionspace.services.common.api.Tools;
39 import org.collectionspace.services.config.service.ServiceBindingType;
40 import org.collectionspace.services.config.service.ServiceObjectType;
41 import org.collectionspace.services.config.tenant.RepositoryDomainType;
42 import org.collectionspace.services.config.tenant.TenantBindingConfig;
43 import org.collectionspace.services.config.tenant.TenantBindingType;
44 import org.collectionspace.services.config.types.PropertyItemType;
46 import ch.elca.el4j.services.xmlmerge.Configurer;
47 import ch.elca.el4j.services.xmlmerge.config.AttributeMergeConfigurer;
48 import ch.elca.el4j.services.xmlmerge.config.ConfigurableXmlMerge;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * ServicesConfigReader reads service layer specific configuration
56 * $LastChangedRevision: $
59 public class TenantBindingConfigReaderImpl
60 extends AbstractConfigReaderImpl<List<TenantBindingType>> {
61 final private static String TENANT_BINDINGS_ERROR = "Tenant bindings error: ";
62 final private static String TENANT_BINDINGS_DELTA_FILENAME = JEEServerDeployment.TENANT_BINDINGS_FILENAME_PREFIX + ".delta.xml";
63 final private static String MERGED_SUFFIX = ".merged.xml";
65 final Logger logger = LoggerFactory.getLogger(TenantBindingConfigReaderImpl.class);
66 private List<TenantBindingType> tenantBindingTypeList;
67 //tenant id, tenant binding
68 private Hashtable<String, TenantBindingType> tenantBindings =
69 new Hashtable<String, TenantBindingType>();
71 private Hashtable<String, RepositoryDomainType> domains =
72 new Hashtable<String, RepositoryDomainType>();
73 //tenant-qualified servicename, service binding
74 private Hashtable<String, ServiceBindingType> serviceBindings =
75 new Hashtable<String, ServiceBindingType>();
77 //tenant-qualified service object name to service name, service binding
78 private Hashtable<String, ServiceBindingType> docTypes =
79 new Hashtable<String, ServiceBindingType>();
82 public TenantBindingConfigReaderImpl(String serverRootDir) {
87 public String getFileName() {
88 return TENANT_BINDINGS_DELTA_FILENAME;
91 protected File getTenantsRootDir() {
93 String errMessage = null;
95 String tenantsRootPath = getConfigRootDir() + File.separator + JEEServerDeployment.TENANT_BINDINGS_ROOTDIRNAME;
96 File tenantsRootDir = new File(tenantsRootPath);
97 if (tenantsRootDir.exists() == true) {
98 result = tenantsRootDir;
99 if (logger.isDebugEnabled() == true) {
100 logger.debug("The home directory for all tenants is at: " + result.getCanonicalPath());
103 errMessage = "The home directory for all tenants is missing or inaccesible: ";
105 errMessage = errMessage + tenantsRootDir.getCanonicalPath();
106 } catch (IOException ioException) {
107 errMessage = errMessage + tenantsRootDir.getAbsolutePath();
110 } catch (IOException e) {
111 // Log this exception, but continue anyway. Caller should handle the null result gracefully.
115 if (errMessage != null) {
116 logger.error(errMessage);
123 * Take the directory of the prototype bindings and the directory of the delta bindings. Merge the two and create (replace) a file
124 * named "tenant-bindings.xml"
127 private InputStream merge(File srcFile, File deltaFile) throws IOException {
128 InputStream result = null;
130 FileInputStream srcStream = new FileInputStream(srcFile);
131 FileInputStream deltaStream = new FileInputStream(deltaFile);
132 InputStream[] inputStreamArray = {srcStream, deltaStream};
134 Configurer configurer = new AttributeMergeConfigurer();
135 result = new ConfigurableXmlMerge(configurer).merge(inputStreamArray);
136 } catch (Exception e) {
137 logger.error("Could not merge tenant configuration delta file: " +
138 deltaFile.getCanonicalPath(), e);
141 // Try to save the merge output to a file that is suffixed with ".merged.xml" in the same directory
142 // as the delta file.
144 if (result != null) {
145 File outputDir = deltaFile.getParentFile();
146 String mergedFileName = outputDir.getAbsolutePath() + File.separator +
147 JEEServerDeployment.TENANT_BINDINGS_FILENAME_PREFIX + MERGED_SUFFIX;
148 File mergedOutFile = new File(mergedFileName);
150 FileUtils.copyInputStreamToFile(result, mergedOutFile);
151 } catch (IOException e) {
152 logger.warn("Could not create a copy of the merged tenant configuration at: " +
155 result.reset(); //reset the stream even if the file create failed.
162 public void read(boolean useAppGeneratedBindings) throws Exception {
163 String tenantsRootPath = getTenantsRootDir().getAbsolutePath();
164 read(tenantsRootPath, useAppGeneratedBindings);
168 public void read(String tenantRootDirPath, boolean useAppGeneratedBindings) throws Exception {
169 File tenantsRootDir = new File(tenantRootDirPath);
170 if (tenantsRootDir.exists() == false) {
171 throw new Exception("Cound not find tenant bindings root directory: " +
174 File protoBindingsFile = new File(tenantRootDirPath + File.separator +
175 JEEServerDeployment.TENANT_BINDINGS_PROTOTYPE_FILENAME);
177 List<File> tenantDirs = getDirectories(tenantsRootDir);
178 tenantBindingTypeList = readTenantConfigs(protoBindingsFile, tenantDirs, useAppGeneratedBindings);
180 for (TenantBindingType tenantBinding : tenantBindingTypeList) {
181 if(tenantBindings.get(tenantBinding.getId()) != null) {
182 TenantBindingType tenantBindingOld = tenantBindings.get(tenantBinding.getId());
183 logger.error("Ignoring duplicate binding definition for tenant id="
184 + tenantBinding.getId()
185 + " existing name=" + tenantBindingOld.getName()
186 + " conflicting (ignored) name=" + tenantBinding.getName());
189 tenantBindings.put(tenantBinding.getId(), tenantBinding);
190 readDomains(tenantBinding);
191 readServiceBindings(tenantBinding);
192 if (logger.isInfoEnabled()) {
193 logger.info("Finished reading tenant bindings for tenant id=" + tenantBinding.getId()
194 + " name=" + tenantBinding.getName());
200 * Take the directory of the prototype bindings and the directory of the delta bindings. Merge the two and create (replace) a file
201 * named "tenant-bindings.xml"
203 private static String merge(String original, String patch) {
204 InputStream result = null;
206 Configurer configurer = new AttributeMergeConfigurer();
209 FileInputStream ins1 = new FileInputStream(".\\src\\main\\resources\\File1.xml");
210 FileInputStream ins2 = new FileInputStream(".\\src\\main\\resources\\File2.xml");
211 InputStream[] inputStreamArray = {ins1, ins2};
213 result = new ConfigurableXmlMerge(configurer).merge(inputStreamArray);
214 // result = new ConfigurableXmlMerge(configurer).merge(new String[] {original, patch});
215 } catch (Exception e) {
216 // TODO Auto-generated catch block
219 File mergedOutFile = new File(".\\target\\merged.xml");
221 FileUtils.copyInputStreamToFile(result, mergedOutFile);
222 } catch (IOException e) {
223 // TODO Auto-generated catch block
232 * Merge and read the prototype bindsings with each tenant specific bindings delta to create the final
235 * @param protoBindingsFile - The prototypical bindings file.
236 * @param tenantDirList - The list of tenant directories containing tenant specific bindings
237 * @return A list of tenant bindings.
238 * @throws IOException Signals that an I/O exception has occurred.
240 List<TenantBindingType> readTenantConfigs(File protoBindingsDir, List<File> tenantDirList, boolean useAppGeneratedBindings) throws IOException {
241 List<TenantBindingType> result = new ArrayList<TenantBindingType>();
244 // Iterate through a list of directories.
246 for (File tenantDir : tenantDirList) {
247 boolean found = false;
248 String errMessage = null;
250 File tenantBindingsProtoFile = null;
251 if (useAppGeneratedBindings == true) {
252 String tenantName = tenantDir.getName(); // By convention, the directory name should be the tenant name
253 tenantBindingsProtoFile = new File(protoBindingsDir.getAbsolutePath() + File.separator + tenantName +
254 "-" + JEEServerDeployment.TENANT_BINDINGS_PROTOTYPE_FILENAME);
256 tenantBindingsProtoFile = new File(protoBindingsDir + File.separator +
257 JEEServerDeployment.TENANT_BINDINGS_PROTOTYPE_FILENAME);
260 File configFile = new File(tenantDir.getAbsoluteFile() + File.separator + getFileName());
261 if (configFile.exists() == true) {
262 InputStream tenantBindingsStream = this.merge(tenantBindingsProtoFile, configFile);
263 TenantBindingConfig tenantBindingConfig = null;
265 tenantBindingConfig = (TenantBindingConfig) parse(tenantBindingsStream,
266 TenantBindingConfig.class);
267 } catch (Exception e) {
268 logger.error("Could not parse the merged tenant bindings.", e);
270 if (tenantBindingConfig != null) {
271 TenantBindingType binding = tenantBindingConfig.getTenantBinding();
272 if (binding != null) {
275 if (logger.isInfoEnabled() == true) {
276 logger.info("Parsed tenant configureation for: " + binding.getDisplayName());
279 errMessage = "Cound not parse the tentant bindings in: ";
282 errMessage = "Could not parse the tenant bindings file: ";
285 errMessage = "Cound not find a tenant configuration file: ";
287 if (found == false) {
288 if (logger.isErrorEnabled() == true) {
289 errMessage = errMessage != null ? errMessage : TENANT_BINDINGS_ERROR;
290 logger.error(errMessage + configFile.getAbsolutePath());
298 private void readDomains(TenantBindingType tenantBinding) throws Exception {
299 for (RepositoryDomainType domain : tenantBinding.getRepositoryDomain()) {
300 String key = getTenantQualifiedIdentifier(tenantBinding.getId(),
302 domains.put(key, domain);
306 private void readServiceBindings(TenantBindingType tenantBinding) throws Exception {
307 for (ServiceBindingType serviceBinding : tenantBinding.getServiceBindings()) {
308 String key = getTenantQualifiedServiceName(tenantBinding.getId(),
309 serviceBinding.getName());
310 serviceBindings.put(key, serviceBinding);
312 if (serviceBinding!=null){
313 ServiceObjectType objectType = serviceBinding.getObject();
314 if (objectType!=null){
315 String docType = objectType.getName();
316 String docTypeKey = getTenantQualifiedIdentifier(tenantBinding.getId(), docType);
317 docTypes.put(docTypeKey, serviceBinding);
320 if (logger.isTraceEnabled()) {
321 logger.trace("readServiceBindings() added service "
323 + " workspace=" + serviceBinding.getName());
329 public List<TenantBindingType> getConfiguration() {
330 return tenantBindingTypeList;
334 * getTenantBindings returns all the tenant bindings read from configuration
337 public Hashtable<String, TenantBindingType> getTenantBindings() {
338 return tenantBindings;
342 * getTenantBinding gets tenant binding for given tenant
346 public TenantBindingType getTenantBinding(
348 return tenantBindings.get(tenantId);
352 * getRepositoryDomain gets repository domain configuration for the given name
356 public RepositoryDomainType getRepositoryDomain(String domainName) {
357 return domains.get(domainName.trim());
361 * getRepositoryDomain gets repository domain configuration for the given service
362 * and given tenant id
367 public RepositoryDomainType getRepositoryDomain(String tenantId, String serviceName) {
368 ServiceBindingType serviceBinding = getServiceBinding(tenantId, serviceName);
369 if (serviceBinding == null) {
370 throw new IllegalArgumentException("no service binding found for " + serviceName
371 + " of tenant with id=" + tenantId);
373 String repoDomain = serviceBinding.getRepositoryDomain();
374 if (repoDomain == null) {
375 if (logger.isTraceEnabled()) {
376 logger.trace("No repository domain configured for " + serviceName
377 + " of tenant with id=" + tenantId);
381 String key = this.getTenantQualifiedIdentifier(tenantId, repoDomain.trim());
382 return domains.get(key);
386 * getServiceBinding gets service binding for given tenant for a given service
391 public ServiceBindingType getServiceBinding(
392 String tenantId, String serviceName) {
393 String key = getTenantQualifiedServiceName(tenantId, serviceName);
394 return serviceBindings.get(key);
398 * getServiceBinding gets service binding for given tenant for a given service
403 public ServiceBindingType getServiceBindingForDocType (String tenantId, String docType) {
404 String key = getTenantQualifiedIdentifier(tenantId, docType);
405 return docTypes.get(key);
409 * getServiceBinding gets service binding for given tenant for a given service
414 public List<ServiceBindingType> getServiceBindingsByType(
415 String tenantId, String serviceType) {
416 List<String> serviceTypes = new ArrayList<String>(1);
417 serviceTypes.add(serviceType);
418 return getServiceBindingsByType(tenantId, serviceTypes);
421 * getServiceBindingsByType gets service bindings for a given tenant
422 * for the services that fall within a supplied set of service type(s)
424 * @param serviceTypes
427 public List<ServiceBindingType> getServiceBindingsByType(
428 String tenantId, List<String> serviceTypes) {
429 ArrayList<ServiceBindingType> list = null;
430 TenantBindingType tenant = tenantBindings.get(tenantId);
431 if (tenant != null) {
432 for (ServiceBindingType sb : tenant.getServiceBindings()) {
433 if (serviceTypes.contains(sb.getType())) {
435 list = new ArrayList<ServiceBindingType>();
447 * @return the properly qualified service name
449 public static String getTenantQualifiedServiceName(
450 String tenantId, String serviceName) {
451 // return tenantId + "." + serviceName.toLowerCase();
452 return getTenantQualifiedIdentifier(tenantId, serviceName.toLowerCase());
455 public static String getTenantQualifiedIdentifier(String tenantId, String identifier) {
456 return tenantId + "." + identifier;
459 * Sets properties in the passed list on the local properties for this TenantBinding.
460 * Note: will only set properties not already set on the TenantBinding.
463 * @param propagateToServices If true, recurses to set set properties
464 * on the associated services.
466 public void setDefaultPropertiesOnTenants(List<PropertyItemType> propList,
467 boolean propagateToServices) {
468 // For each tenant, set properties in list that are not already set
469 if (propList == null || propList.isEmpty()) {
472 for (TenantBindingType tenant : tenantBindings.values()) {
473 for (PropertyItemType prop : propList) {
474 TenantBindingUtils.setPropertyValue(tenant,
475 prop, TenantBindingUtils.SET_PROP_IF_MISSING);
477 if (propagateToServices) {
478 TenantBindingUtils.propagatePropertiesToServices(tenant,
479 TenantBindingUtils.SET_PROP_IF_MISSING);
484 public String getResourcesDir(){
485 return getConfigRootDir() + File.separator + RESOURCES_DIR_NAME;
490 * Returns a list of tenant identifiers (tenant IDs).
492 * @return a list of tenant IDs
494 public List<String> getTenantIds() {
495 List<String> tenantIds = new ArrayList<String>();
497 Hashtable<String, TenantBindingType> tenantBindings = getTenantBindings();
498 if (tenantBindings != null && !tenantBindings.isEmpty()) {
499 Enumeration keys = tenantBindings.keys();
500 while (keys.hasMoreElements()) {
501 tenantId = (String) keys.nextElement();
502 if (Tools.notBlank(tenantId)) {
503 tenantIds.add(tenantId);