View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  
22  package org.opencastproject.serviceregistry.impl;
23  
24  import static org.opencastproject.db.Queries.namedQuery;
25  import static org.opencastproject.util.IoSupport.loadPropertiesFromUrl;
26  import static org.opencastproject.util.data.Monadics.mlist;
27  
28  import org.opencastproject.db.DBSession;
29  import org.opencastproject.db.DBSessionFactory;
30  import org.opencastproject.serviceregistry.api.IncidentService;
31  import org.opencastproject.serviceregistry.api.ServiceRegistry;
32  import org.opencastproject.workflow.api.WorkflowService;
33  
34  import org.apache.commons.io.FilenameUtils;
35  import org.osgi.framework.Bundle;
36  import org.osgi.framework.BundleEvent;
37  import org.osgi.framework.BundleListener;
38  import org.osgi.service.component.ComponentContext;
39  import org.osgi.service.component.annotations.Activate;
40  import org.osgi.service.component.annotations.Component;
41  import org.osgi.service.component.annotations.Deactivate;
42  import org.osgi.service.component.annotations.Reference;
43  import org.slf4j.Logger;
44  import org.slf4j.LoggerFactory;
45  
46  import java.net.URL;
47  import java.util.Enumeration;
48  import java.util.List;
49  import java.util.Properties;
50  
51  import javax.persistence.EntityManagerFactory;
52  
53  @Component(
54    property = {
55      "service.description=Incident service"
56    },
57    immediate = true,
58    service = { IncidentService.class }
59  )
60  public class OsgiIncidentService extends AbstractIncidentService implements BundleListener {
61    /** The logging instance */
62    private static final Logger logger = LoggerFactory.getLogger(OsgiIncidentService.class);
63  
64    public static final String INCIDENT_L10N_DIR = "incident-l10n";
65  
66    /** Reference to the receipt service registry */
67    private ServiceRegistry serviceRegistry;
68  
69    /** Reference to the receipt workflow service */
70    private WorkflowService workflowService;
71  
72    private DBSessionFactory dbSessionFactory;
73    private EntityManagerFactory emf;
74    private DBSession db;
75  
76    @Override
77    protected ServiceRegistry getServiceRegistry() {
78      return serviceRegistry;
79    }
80  
81    @Override
82    protected WorkflowService getWorkflowService() {
83      return workflowService;
84    }
85  
86    @Override
87    protected DBSession getDBSession() {
88      return db;
89    }
90  
91    /**
92     * Sets the service registry
93     *
94     * @param serviceRegistry
95     *          the service registry
96     */
97    @Reference
98    protected void setServiceRegistry(ServiceRegistry serviceRegistry) {
99      this.serviceRegistry = serviceRegistry;
100   }
101 
102   /**
103    * Sets the workflow service
104    *
105    * @param workflowService
106    *          the workflow service
107    */
108   @Reference(name  = "workflowService")
109   public void setWorkflowService(WorkflowService workflowService) {
110     this.workflowService = workflowService;
111   }
112 
113   /**
114    * OSGi callback on component activation.
115    */
116   @Activate
117   public void activate(ComponentContext cc) {
118     logger.info("Activating persistence manager for job incidents");
119     db = dbSessionFactory.createSession(emf);
120     // scan bundles for incident localizations
121     cc.getBundleContext().addBundleListener(this);
122     for (Bundle b : cc.getBundleContext().getBundles()) {
123       storeIncidentTexts(b);
124     }
125   }
126 
127   /**
128    * Closes entity manager factory.
129    */
130   @Deactivate
131   public void deactivate() {
132     db.close();
133   }
134 
135   /** OSGi DI */
136   @Reference(target = "(osgi.unit.name=org.opencastproject.serviceregistry)")
137   void setEntityManagerFactory(EntityManagerFactory emf) {
138     this.emf = emf;
139   }
140 
141   @Reference
142   public void setDBSessionFactory(DBSessionFactory dbSessionFactory) {
143     this.dbSessionFactory = dbSessionFactory;
144   }
145 
146   @Override
147   public void bundleChanged(BundleEvent event) {
148     switch (event.getType()) {
149       case BundleEvent.INSTALLED:
150         storeIncidentTexts(event.getBundle());
151         break;
152       case BundleEvent.STOPPED:
153       case BundleEvent.UNINSTALLED:
154         // todo to support deletion of texts the service has to store a mapping
155         // from bundle-id -> text-base-keys, e.g. 125 -> "org.opencastproject.composer"
156         // In the end deletion is not really necessary, texts may simply be overwritten or just
157         // eat up some database space.
158         break;
159       default:
160         // do nothing
161     }
162   }
163 
164   private static final String PROPERTIES_GLOB = "*.properties";
165 
166   private void storeIncidentTexts(Bundle bundle) {
167     logger.debug("Scanning bundle {}, (ID {}) for incident localizations", bundle.getSymbolicName(),
168             bundle.getBundleId());
169     final Enumeration<?> l10n = bundle.findEntries(INCIDENT_L10N_DIR, PROPERTIES_GLOB, false);
170     while (l10n != null && l10n.hasMoreElements()) {
171       final URL resourceUrl = (URL) l10n.nextElement();
172       final String resourceFileName = resourceUrl.getPath();
173       // e.g. org.opencastproject.composer.properties or org.opencastproject.composer_de.properties
174       final String fullResourceName = FilenameUtils.getBaseName(resourceFileName);
175       final String[] fullResourceNameParts = fullResourceName.split("_");
176       // part 0 contains the key base, e.g. org.opencastproject.composer
177       final String keyBase = fullResourceNameParts[0];
178       final List<String> locale = mlist(fullResourceNameParts).drop(1).value();
179       final Properties texts = loadPropertiesFromUrl(resourceUrl);
180       for (String key : texts.stringPropertyNames()) {
181         final String text = texts.getProperty(key);
182         final String dbKey = mlist(keyBase, key).concat(locale).mkString(".");
183         logger.debug("Storing text {}={}", dbKey, text);
184         db.execTx(namedQuery.persistOrUpdate(IncidentTextDto.mk(dbKey, text)));
185       }
186     }
187   }
188 }