1 17 package org.alfresco.tools; 18 19 import org.alfresco.service.ServiceRegistry; 20 import org.alfresco.service.cmr.security.AuthenticationService; 21 import org.alfresco.util.ApplicationContextHelper; 22 import org.springframework.context.ApplicationContext; 23 24 25 30 public abstract class Tool 31 { 32 33 private ToolContext toolContext; 34 35 private ApplicationContext appContext; 36 37 private ServiceRegistry serviceRegistry; 38 39 40 47 ToolContext processArgs(String [] args) 48 throws ToolException 49 { 50 return new ToolContext(); 51 } 52 53 56 void displayHelp() 57 { 58 System.out.println("Sorry. Help is not available."); 59 } 60 61 66 abstract void execute() 67 throws ToolException; 68 69 74 abstract String getToolName(); 75 76 81 final ApplicationContext getApplicationContext() 82 { 83 return appContext; 84 } 85 86 91 final ServiceRegistry getServiceRegistry() 92 { 93 return serviceRegistry; 94 } 95 96 101 final void log(String msg) 102 { 103 if (toolContext.isQuiet() == false) 104 { 105 System.out.println(msg); 106 } 107 } 108 109 114 final void logVerbose(String msg) 115 { 116 if (toolContext.isVerbose()) 117 { 118 log(msg); 119 } 120 } 121 122 127 final void start(String [] args) 128 { 129 try 130 { 131 toolContext = processArgs(args); 133 toolContext.validate(); 134 135 try 136 { 137 if (toolContext.isHelp()) 138 { 139 displayHelp(); 141 } 142 else 143 { 144 log(getToolName()); 146 initialiseRepository(); 147 login(); 148 execute(); 149 log(getToolName() + " successfully completed."); 150 } 151 System.exit(0); 152 } 153 catch (ToolException e) 154 { 155 displayError(e); 156 System.exit(-1); 157 } 158 } 159 catch(ToolException e) 160 { 161 System.out.println(e.getMessage()); 162 System.out.println(); 163 displayHelp(); 164 System.exit(-1); 165 } 166 catch (Throwable e) 167 { 168 System.out.println("The following error has occurred:"); 169 System.out.println(e.getMessage()); 170 e.printStackTrace(); 171 System.exit(-1); 172 } 173 } 174 175 178 private void login() 179 { 180 AuthenticationService auth = (AuthenticationService) serviceRegistry.getAuthenticationService(); 182 auth.authenticate(toolContext.getUsername(), toolContext.getPassword().toCharArray()); 183 log("Connected as " + toolContext.getUsername()); 184 } 185 186 189 private void initialiseRepository() 190 { 191 appContext = ApplicationContextHelper.getApplicationContext(); 192 serviceRegistry = (ServiceRegistry) appContext.getBean(ServiceRegistry.SERVICE_REGISTRY); 193 } 194 195 200 private void displayError(Throwable e) 201 { 202 System.out.println(e.getMessage()); 203 if (toolContext != null && toolContext.isVerbose()) 204 { 205 e.printStackTrace(); 206 } 207 } 208 209 } 210 | Popular Tags |