View Javadoc

1   /**
2    * This file Copyright (c) 2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.groovy.remote;
35  
36  import java.io.BufferedReader;
37  import java.io.File;
38  import java.io.FileReader;
39  import java.io.IOException;
40  import java.io.InputStreamReader;
41  import java.io.UnsupportedEncodingException;
42  import java.util.ArrayList;
43  import java.util.List;
44  
45  import org.apache.http.HttpEntity;
46  import org.apache.http.HttpResponse;
47  import org.apache.http.NameValuePair;
48  import org.apache.http.client.ClientProtocolException;
49  import org.apache.http.client.entity.UrlEncodedFormEntity;
50  import org.apache.http.client.methods.HttpGet;
51  import org.apache.http.client.methods.HttpPost;
52  import org.apache.http.impl.client.DefaultHttpClient;
53  import org.apache.http.message.BasicNameValuePair;
54  import org.apache.http.protocol.HTTP;
55  import org.apache.http.util.EntityUtils;
56  import org.slf4j.Logger;
57  import org.slf4j.LoggerFactory;
58  
59  
60  /**
61   * Remote client application connecting and executing Groovy Script against a
62   * Magnolia server instance.
63   * @version $Id$
64   *
65   */
66  public class RemoteClientConsole {
67  
68      /*Log*/
69      private static final Logger log = LoggerFactory.getLogger(RemoteClientConsole.class);
70  
71      /*Constants*/
72      private final String logingUri = "/.magnolia/pages/adminCentral.html?";
73      private final String groovyUri = "/.magnolia/pages/groovyInteractiveConsole.html?";
74  
75      /*Global Variable */
76      private DefaultHttpClient httpclient;
77      private String magnoliaUri;
78      private String user;
79      private String password;
80  
81      /**
82       * Parameter constructor.
83       * @param magnoliaUri: Magnolia uri like http://localhost:8080/magnolia-empty-webapp
84       * @param user: Mgnolia admin user
85       * @param password: Magnolia admin user password
86       */
87      public RemoteClientConsole(String magnoliaUri, String user, String password) {
88          super();
89          connect(magnoliaUri, user, password);
90      }
91  
92      /**
93       * Create a HTTP connection to the Magnolia server using a
94       * HTTP Form user/password authentification mechanism.
95       *
96       * @param magnoliaUri: Magnolia uri like http://localhost:8080/magnolia-empty-webapp
97       * @param user: Mgnolia admin user
98       * @param password: Magnolia admin user password
99       */
100     public boolean connect(String magnoliaUri, String user, String password) {
101         this.user = user;
102         this.password = password;
103         this.magnoliaUri = magnoliaUri;
104         log.debug("set private global variable magnoliaUri='"+magnoliaUri+"', user='"+user+"', passwoed='"+password+"'");
105         return connect();
106      }
107 
108     /**
109      * Create a HTTP connection to the Magnolia server using a
110      * HTTP Form user/password authentification mechanism.
111      */
112     private boolean connect() {
113         // init
114         boolean res = false;
115         HttpPost httpost = null;
116         HttpResponse response = null;
117         HttpEntity entity = null;
118         log.debug("Try to connect to magnoliaUri='"+magnoliaUri);
119         //If still connected, Reconnect
120         if(isConnected()){
121             log.warn("Still connected as we try to create a new connection. Will be disconnected first");
122             disconnect();
123         }
124 
125         try {
126             httpclient = new DefaultHttpClient();
127             // login post uri
128             httpost = new HttpPost(this.magnoliaUri + logingUri);
129             // in Parameter
130             List<NameValuePair> nvps = new ArrayList<NameValuePair>();
131             nvps.add(new BasicNameValuePair("mgnlUserId", this.user));
132             nvps.add(new BasicNameValuePair("mgnlUserPSWD", this.password));
133             httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
134             // request post
135             response = httpclient.execute(httpost);
136             // check and log result
137             System.out.println("Login form get: " + response.getStatusLine());
138             if (response.getStatusLine().toString().endsWith("200 OK")) {
139                 res = true;
140                 log.debug("Correctly connected to  magnoliaUri='"+magnoliaUri);
141             }else{
142                 log.warn("Could not establish a connection to magnoliaUri='"+magnoliaUri);
143             }
144             // Consume entity
145             entity = response.getEntity();
146             EntityUtils.consume(entity);
147 
148         }
149         catch (ClientProtocolException cpe) {
150             log.error("", cpe);
151             /*As this is called by a standalone java application, error log will also be redirect to the console*/
152             cpe.printStackTrace();
153         }
154         catch (UnsupportedEncodingException uee) {
155             log.error("", uee);
156             /*As this is called by a standalone java application, error log will also be redirect to the console*/
157             uee.printStackTrace();
158         }
159         catch (IOException ioe) {
160             log.error("", ioe);
161             /*As this is called by a standalone java application, error log will also be redirect to the console*/
162             ioe.printStackTrace();
163         }
164 
165         return res;
166     }
167 
168     /**
169      * Disconnect from Magnolia remote instance.
170      * @return: true if correctly disconnected
171      */
172     public boolean disconnect() {
173         boolean res = false;
174         if (httpclient != null && httpclient.getConnectionManager() != null) {
175             httpclient.getConnectionManager().shutdown();
176             log.debug("Correctly disconnected from magnoliaUri='"+magnoliaUri);
177             res = true;
178         }
179         return res;
180     }
181 
182     /**
183      * Check if still connected and authorized.
184      * @return: true if connected and authorized
185      */
186     public boolean isConnected() {
187         // init
188         boolean res = false;
189         HttpGet httpget = null;
190         HttpEntity entity = null;
191         try {
192             httpget = new HttpGet(magnoliaUri);
193             if (httpclient == null)
194                 return res;
195             HttpResponse response = httpclient.execute(httpget);
196 
197             // check if ended with 401 Unauthorized
198             if (!response.getStatusLine().toString().endsWith("401 Unauthorized")) {
199                 res = true;
200             }
201             // Consume entity
202             entity = response.getEntity();
203             EntityUtils.consume(entity);
204 
205         }
206         catch (ClientProtocolException cpe) {
207             log.error("",cpe);
208             /*As this is called by a standalone java application, error log will also be redirect to the console*/
209             cpe.printStackTrace();
210         }
211         catch (UnsupportedEncodingException uee) {
212             log.error("",uee);
213             /*As this is called by a standalone java application, error log will also be redirect to the console*/
214             uee.printStackTrace();
215         }
216         catch (IOException ioe) {
217             log.error("",ioe);
218             /*As this is called by a standalone java application, error log will also be redirect to the console*/
219             ioe.printStackTrace();
220         }
221 
222         return res;
223     }
224 
225     /**
226      * Execute the Groovy script defined in the incoming file in
227      * the Magnolia Groovy server environment.
228      *
229      * @param inputFile absolute file name
230      * @return the script result as String
231      */
232     public String execute(Object inputObject) {
233         // init
234         HttpPost httpost = null;
235         HttpResponse response = null;
236         StringBuffer sb = new StringBuffer();
237         BufferedReader rd = null;
238         HttpEntity entity = null;
239 
240         try {
241             // login post uri
242             httpost = new HttpPost(magnoliaUri + groovyUri);
243             // in Parameter
244             List<NameValuePair> nvps = new ArrayList<NameValuePair>();
245             if(inputObject instanceof File){
246                 nvps.add(new BasicNameValuePair("code", readFileAsString((File)inputObject)));
247             }else if(inputObject instanceof String){
248                 nvps.add(new BasicNameValuePair("code", (String)inputObject));
249             }else{
250                 return "Input parameter is not a String or a File";
251             }
252             nvps.add(new BasicNameValuePair("command", "evaluateGroovy"));
253             httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
254             // request post
255             response = httpclient.execute(httpost);
256 
257             // Get the output
258             entity = response.getEntity();
259             if (entity != null) {
260                 // Get the response
261                 rd = new BufferedReader(new InputStreamReader(entity.getContent()));
262                 String line;
263                 while ((line = rd.readLine()) != null) {
264                     sb.append(line);
265                 }
266                 EntityUtils.consume(entity);
267             }
268             else {
269                 sb.append("No result");
270             }
271 
272         }
273         catch (ClientProtocolException cpe) {
274             log.error("",cpe);
275             /*As this is called by a standalone java application, error log will also be redirect to the console*/
276             cpe.printStackTrace();
277         }
278         catch (UnsupportedEncodingException uee) {
279             log.error("",uee);
280             /*As this is called by a standalone java application, error log will also be redirect to the console*/
281             uee.printStackTrace();
282         }
283         catch (IOException ioe) {
284             log.error("",ioe);
285             /*As this is called by a standalone java application, error log will also be redirect to the console*/
286             ioe.printStackTrace();
287         }
288         finally {
289             if (rd != null) {
290                 try {
291                     rd.close();
292                 }
293                 catch (IOException e) {
294                     /*As this is called by a standalone java application, error log will also be redirect to the console*/
295                     e.printStackTrace();
296                 }
297             }
298         }
299         return sb.toString();
300 
301     }
302 
303     /**
304      * Get a String representing the file content.
305      * @throws java.io.IOException
306      */
307     private String readFileAsString(File file) throws java.io.IOException {
308         StringBuffer fileData = new StringBuffer(1000);
309         BufferedReader reader = null;
310         try{
311             reader = new BufferedReader(new FileReader(file));
312             char[] buf = new char[1024];
313             int numRead = 0;
314             while ((numRead = reader.read(buf)) != -1) {
315                 fileData.append(buf, 0, numRead);
316             }
317         }finally{
318             reader.close();
319         }
320 
321         return fileData.toString();
322     }
323 }