]> git.argeo.org Git - gpl/argeo-suite.git/blob - suite/core/CustomMaintenanceService.java
Prepare next development cycle
[gpl/argeo-suite.git] / suite / core / CustomMaintenanceService.java
1 package org.argeo.suite.core;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.URL;
6 import java.util.ArrayList;
7 import java.util.List;
8
9 import javax.jcr.ImportUUIDBehavior;
10 import javax.jcr.ItemExistsException;
11 import javax.jcr.Node;
12 import javax.jcr.RepositoryException;
13
14 import org.apache.commons.logging.Log;
15 import org.apache.commons.logging.LogFactory;
16 import org.argeo.entity.EntityType;
17 import org.argeo.jcr.JcrUtils;
18 import org.argeo.maintenance.AbstractMaintenanceService;
19
20 /** Base for custom initialisations. */
21 public abstract class CustomMaintenanceService extends AbstractMaintenanceService {
22 private final static Log log = LogFactory.getLog(AbstractMaintenanceService.class);
23
24 protected List<String> getTypologies() {
25 return new ArrayList<>();
26 }
27
28 protected String getTypologiesLoadBase() {
29 return "/sys/terms";
30 }
31
32 protected void loadTypologies(Node customBaseNode) throws RepositoryException, IOException {
33 List<String> typologies = getTypologies();
34 if (!typologies.isEmpty()) {
35 Node termsBase = JcrUtils.getOrAdd(customBaseNode, EntityType.terms.name(), EntityType.typologies.get());
36 for (String terms : typologies) {
37 loadTerms(termsBase, terms);
38 }
39 // TODO do not save here, so that upper layers can decide when to save
40 termsBase.getSession().save();
41 }
42 }
43
44 protected void loadTerms(Node termsBase, String name) throws IOException, RepositoryException {
45 try {
46 // if (termsBase.hasNode(name))
47 // return;
48
49 String termsLoadPath = getTypologiesLoadBase() + '/' + name + ".xml";
50 URL termsUrl = getClass().getClassLoader().getResource(termsLoadPath);
51 if (termsUrl == null)
52 throw new IllegalArgumentException("Terms '" + name + "' not found.");
53 try (InputStream in = termsUrl.openStream()) {
54 termsBase.getSession().importXML(termsBase.getPath(), in,
55 ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
56 } catch (ItemExistsException e) {
57 log.warn("Terms " + name + " exists with another UUID, removing it...");
58 termsBase.getNode(name).remove();
59 try (InputStream in = termsUrl.openStream()) {
60 termsBase.getSession().importXML(termsBase.getPath(), in,
61 ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
62 }
63 }
64 if (log.isDebugEnabled())
65 log.debug("Terms '" + name + "' loaded.");
66 // TODO do not save here, so that upper layers can decide when to save
67 termsBase.getSession().save();
68 } catch (RepositoryException | IOException e) {
69 log.error("Cannot load terms '" + name + "': " + e.getMessage());
70 throw e;
71 }
72 }
73
74 }