View Javadoc

1   /*
2    * Copyright 2015 Data Archiving and Networked Services (an institute of
3    * Koninklijke Nederlandse Akademie van Wetenschappen), King's College London,
4    * Georg-August-Universitaet Goettingen Stiftung Oeffentlichen Rechts
5    *
6    * Licensed under the EUPL, Version 1.1 or – as soon they will be approved by
7    * the European Commission - subsequent versions of the EUPL (the "Licence");
8    * You may not use this work except in compliance with the Licence.
9    * You may obtain a copy of the Licence at:
10   *
11   * https://joinup.ec.europa.eu/software/page/eupl
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the Licence is distributed on an "AS IS" basis,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the Licence for the specific language governing
17   * permissions and limitations under the Licence.
18   */
19  
20  package eu.ehri.project.commands;
21  
22  import com.google.common.collect.Maps;
23  import com.google.common.collect.Ordering;
24  import com.tinkerpop.frames.FramedGraph;
25  import com.tinkerpop.frames.FramedGraphFactory;
26  import com.tinkerpop.frames.modules.javahandler.JavaHandlerModule;
27  import eu.ehri.project.core.Tx;
28  import eu.ehri.project.core.TxGraph;
29  import eu.ehri.project.core.impl.TxNeo4jGraph;
30  import org.apache.commons.cli.AlreadySelectedException;
31  import org.apache.commons.cli.CommandLine;
32  import org.apache.commons.cli.MissingArgumentException;
33  import org.apache.commons.cli.MissingOptionException;
34  import org.apache.commons.cli.UnrecognizedOptionException;
35  
36  import java.lang.reflect.InvocationTargetException;
37  import java.util.Arrays;
38  import java.util.Collections;
39  import java.util.Map;
40  
41  /**
42   * Entry point for launching admin commands.
43   */
44  public class CmdEntryPoint extends BaseCommand {
45  
46      /**
47       * Default return codes for shell tools.
48       * <p>
49       * 0 means 'OK', 1 'bad arguments', 2 'bad data',
50       * 3 'bad permissions'
51       */
52      public enum RetCode {
53  
54          OK(0),
55          BAD_ARGS(1),
56          BAD_DATA(2),
57          BAD_PERMS(3);
58  
59          private final int code;
60  
61          RetCode(int code) {
62              this.code = code;
63          }
64  
65          public int getCode() {
66              return code;
67          }
68      }
69  
70      /**
71       * Constructor.
72       */
73      public CmdEntryPoint() {
74          super();
75      }
76  
77      private static final Map<String, Class<? extends Command>> COMMANDS;
78  
79      static {
80          Map<String, Class<? extends Command>> mmap = Maps.newHashMap();
81          mmap.put(EadImport.NAME, EadImport.class);
82          mmap.put(DcImport.NAME, DcImport.class);
83          mmap.put(CsvDocDescImport.NAME, CsvDocDescImport.class);
84          mmap.put(UshmmEadImport.NAME, UshmmEadImport.class);
85          mmap.put(EacImport.NAME, EacImport.class);
86          mmap.put(EagImport.NAME, EagImport.class);
87          mmap.put(UserListEntities.NAME, UserListEntities.class);
88          mmap.put(ListEntities.NAME, ListEntities.class);
89          mmap.put(GetEntity.NAME, GetEntity.class);
90          mmap.put(LoadFixtures.NAME, LoadFixtures.class);
91          mmap.put(Initialize.NAME, Initialize.class);
92          mmap.put(GenSchema.NAME, GenSchema.class);
93          mmap.put(UserAdd.NAME, UserAdd.class);
94          mmap.put(UserMod.NAME, UserMod.class);
95          mmap.put(EntityAdd.NAME, EntityAdd.class);
96          mmap.put(PersonalitiesImport.NAME, PersonalitiesImport.class);
97          mmap.put(DeleteEntities.NAME, DeleteEntities.class);
98          mmap.put(RelationAdd.NAME, RelationAdd.class);
99          mmap.put(SkosVocabularyImport.NAME, SkosVocabularyImport.class);
100         mmap.put(CsvConceptImport.NAME, CsvConceptImport.class);
101         // adaptation of UserAdd for adding countries
102         mmap.put(CountryAdd.NAME, CountryAdd.class);
103         mmap.put(EadAsVirtualCollectionImport.NAME, EadAsVirtualCollectionImport.class);
104         mmap.put(GraphSON.NAME, GraphSON.class);
105         mmap.put(Check.NAME, Check.class);
106 
107         COMMANDS = Collections.unmodifiableMap(mmap);
108     }
109 
110     @Override
111     public String getHelp() {
112         try {
113             String sep = System.getProperty("line.separator");
114             StringBuilder buffer = new StringBuilder(String.format(
115                     "Command line interface for the EHRI graph database.%n%n " +
116                             "The following commands are available:%n%n"));
117             for (String key : Ordering.natural().sortedCopy(COMMANDS.keySet())) {
118                 Command cmd = COMMANDS.get(key).getConstructor().newInstance();
119                 buffer.append(String.format("  %-20s %s", key, cmd.getHelp()));
120                 buffer.append(sep);
121             }
122             buffer.append(sep);
123             buffer.append("Use 'help <command>' for usage details.");
124             return buffer.toString();
125         } catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException
126                 |InstantiationException e) {
127             throw new RuntimeException(e);
128         }
129     }
130 
131     @Override
132     public String getUsage() {
133         return "Usage: cmd <command> <command-args ... >";
134     }
135 
136     @Override
137     public int execWithOptions(FramedGraph<?> graph, CommandLine cmdLine) throws Exception {
138         System.err.println(getHelp());
139         return 1;
140     }
141 
142     public static int run(String[] args) throws Exception {
143 
144         if (args.length < 2) {
145             return new CmdEntryPoint().exec(null, args);
146         } else if (args[1].equals("help")) {
147             if (args.length > 2 && COMMANDS.containsKey(args[2])) {
148                 Command cmd = COMMANDS.get(args[2]).getConstructor().newInstance();
149                 System.err.println(cmd.getDetailedHelp());
150                 return RetCode.BAD_ARGS.getCode();
151             } else {
152                 return new CmdEntryPoint().exec(null, args);
153             }
154         } else {
155             if (COMMANDS.containsKey(args[1])) {
156                 Command cmd = COMMANDS.get(args[1]).getConstructor().newInstance();
157                 FramedGraph<? extends TxGraph> graph
158                         = new FramedGraphFactory(new JavaHandlerModule()).create(
159                         new TxNeo4jGraph(args[0]));
160                 try (Tx tx = graph.getBaseGraph().beginTx()) {
161                     int res = cmd.exec(graph, Arrays.copyOfRange(args, 2, args.length));
162                     if (res == RetCode.OK.getCode()) {
163                         tx.success();
164                     } else {
165                         tx.failure();
166                     }
167                 } catch (MissingArgumentException |MissingOptionException|AlreadySelectedException|
168                         UnrecognizedOptionException e) {
169                     // options or parameters where not correct, so print the correct usage
170                     System.err.println(e.getMessage());
171                     System.err.println(cmd.getUsage());
172                     return RetCode.BAD_ARGS.getCode();
173                 } catch (Exception e) {
174                     e.printStackTrace();
175                     System.err.println("Error: " + e.getMessage());
176                     return RetCode.BAD_ARGS.getCode();
177                 } finally {
178                     graph.shutdown();
179                 }
180             } else {
181                 System.err.println("Unrecognised command: " + args[1]);
182                 return RetCode.BAD_ARGS.getCode();
183             }
184         }
185         return RetCode.OK.getCode();
186     }
187 
188     /**
189      * Application launcher.
190      */
191     public static void main(String[] args) throws Exception {
192         System.exit(run(args));
193     }
194 }