KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > ui > antsupport > logger > RemoteAntBuildLogger


1 /*******************************************************************************
2  * Copyright (c) 2003, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.ant.internal.ui.antsupport.logger;
12
13
14 import java.io.BufferedReader JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.PrintStream JavaDoc;
17 import java.io.PrintWriter JavaDoc;
18 import java.io.StringReader JavaDoc;
19 import java.net.Socket JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.List JavaDoc;
23 import java.util.Map JavaDoc;
24
25 import org.apache.tools.ant.BuildEvent;
26 import org.apache.tools.ant.BuildException;
27 import org.apache.tools.ant.DefaultLogger;
28 import org.apache.tools.ant.Location;
29 import org.apache.tools.ant.Project;
30 import org.apache.tools.ant.Target;
31 import org.apache.tools.ant.util.StringUtils;
32 import org.eclipse.ant.internal.ui.antsupport.AntSecurityException;
33 import org.eclipse.ant.internal.ui.antsupport.InternalAntRunner;
34 import org.eclipse.ant.internal.ui.antsupport.RemoteAntMessages;
35 import org.eclipse.ant.internal.ui.antsupport.logger.util.AntDebugState;
36
37 /**
38  * Parts adapted from org.eclipse.jdt.internal.junit.runner.RemoteTestRunner
39  * A build logger that reports via a socket connection.
40  * See MessageIds for more information about the protocol.
41  */

42 public class RemoteAntBuildLogger extends DefaultLogger {
43
44     /** Time of the start of the build */
45     private long fStartTime = System.currentTimeMillis();
46
47     /**
48      * The client socket.
49      */

50     private Socket JavaDoc fEventSocket;
51     /**
52      * Print writer for sending messages
53      */

54     private PrintWriter JavaDoc fWriter;
55     /**
56      * Host to connect to, default is the localhost
57      */

58     protected String JavaDoc fHost= ""; //$NON-NLS-1$
59
/**
60      * Port to connect to.
61      */

62     private int fEventPort= -1;
63     
64     private String JavaDoc fProcessId= null;
65     
66     /**
67      * Is the debug mode enabled?
68      */

69     protected boolean fDebugMode= false;
70     
71     protected boolean fSentProcessId= false;
72     
73     private List JavaDoc fEventQueue;
74     
75     private String JavaDoc fLastFileName= null;
76     private String JavaDoc fLastTaskName= null;
77     
78     /* (non-Javadoc)
79      * @see org.apache.tools.ant.DefaultLogger#printMessage(java.lang.String, java.io.PrintStream, int)
80      */

81     protected void printMessage(String JavaDoc message, PrintStream JavaDoc stream, int priority) {
82         marshalMessage(priority, message);
83     }
84     
85     /**
86      * Connect to the remote Ant build listener.
87      */

88     protected void connect() {
89         if (fDebugMode) {
90             System.out.println("RemoteAntBuildLogger: trying to connect" + fHost + ":" + fEventPort); //$NON-NLS-1$ //$NON-NLS-2$
91
}
92         
93         for (int i= 1; i < 5; i++) {
94             try{
95                 fEventSocket= new Socket JavaDoc(fHost, fEventPort);
96                 fWriter= new PrintWriter JavaDoc(fEventSocket.getOutputStream(), true);
97                 return;
98             } catch(IOException JavaDoc e){
99             }
100             try {
101                 Thread.sleep(500);
102             } catch(InterruptedException JavaDoc e) {
103             }
104         }
105         shutDown();
106     }
107
108     /**
109      * Shutdown the connection to the remote build listener.
110      */

111     protected void shutDown() {
112         if (fEventQueue != null) {
113             fEventQueue.clear();
114         }
115         if (fWriter != null) {
116             fWriter.close();
117             fWriter= null;
118         }
119         
120         try {
121             if (fEventSocket != null) {
122                 fEventSocket.close();
123                 fEventSocket= null;
124             }
125         } catch(IOException JavaDoc e) {
126         }
127     }
128
129     private void sendMessage(String JavaDoc msg) {
130         if (fWriter == null) {
131             return;
132         }
133         
134         fWriter.println(msg);
135     }
136     
137     /* (non-Javadoc)
138      * @see org.apache.tools.ant.BuildListener#buildFinished(org.apache.tools.ant.BuildEvent)
139      */

140     public void buildFinished(BuildEvent event) {
141         if (!fSentProcessId) {
142             establishConnection();
143         }
144         handleException(event);
145         printMessage( getTimeString(System.currentTimeMillis() - fStartTime), out, Project.MSG_INFO);
146         shutDown();
147     }
148     
149     protected void handleException(BuildEvent event) {
150         Throwable JavaDoc exception = event.getException();
151         if (exception == null || exception instanceof AntSecurityException) {
152             return;
153         }
154         
155          StringBuffer JavaDoc message= new StringBuffer JavaDoc();
156          message.append(StringUtils.LINE_SEP);
157          message.append(RemoteAntMessages.getString("RemoteAntBuildLogger.1")); //$NON-NLS-1$
158
message.append(StringUtils.LINE_SEP);
159          if (Project.MSG_VERBOSE <= this.msgOutputLevel || !(exception instanceof BuildException)) {
160              message.append(StringUtils.getStackTrace(exception));
161          } else {
162              if (exception instanceof BuildException) {
163                  message.append(exception.toString()).append(StringUtils.LINE_SEP);
164              } else {
165                  message.append(exception.getMessage()).append(StringUtils.LINE_SEP);
166              }
167          }
168         message.append(StringUtils.LINE_SEP);
169         printMessage(message.toString(), out, Project.MSG_ERR);
170     }
171     
172     private String JavaDoc getTimeString(long milliseconds) {
173         long seconds = milliseconds / 1000;
174         long minutes = seconds / 60;
175         seconds= seconds % 60;
176
177         StringBuffer JavaDoc result= new StringBuffer JavaDoc(RemoteAntMessages.getString("RemoteAntBuildLogger.Total_time")); //$NON-NLS-1$
178
if (minutes > 0) {
179             result.append(minutes);
180             if (minutes > 1) {
181                 result.append(RemoteAntMessages.getString("RemoteAntBuildLogger._minutes_2")); //$NON-NLS-1$
182
} else {
183                 result.append(RemoteAntMessages.getString("RemoteAntBuildLogger._minute_3")); //$NON-NLS-1$
184
}
185         }
186         if (seconds > 0) {
187             if (minutes > 0) {
188                 result.append(' ');
189             }
190             result.append(seconds);
191     
192             if (seconds > 1) {
193                 result.append(RemoteAntMessages.getString("RemoteAntBuildLogger._seconds_4")); //$NON-NLS-1$
194
} else {
195                 result.append(RemoteAntMessages.getString("RemoteAntBuildLogger._second_5")); //$NON-NLS-1$
196
}
197         }
198         if (seconds == 0 && minutes == 0) {
199             result.append(milliseconds);
200             result.append(RemoteAntMessages.getString("RemoteAntBuildLogger._milliseconds_6")); //$NON-NLS-1$
201
}
202         return result.toString();
203     }
204             
205
206     /* (non-Javadoc)
207      * @see org.apache.tools.ant.BuildListener#targetStarted(org.apache.tools.ant.BuildEvent)
208      */

209     public void targetStarted(BuildEvent event) {
210         if (!fSentProcessId) {
211             establishConnection();
212         }
213
214         if (Project.MSG_INFO <= msgOutputLevel) {
215             marshalTargetMessage(event);
216         }
217     }
218
219     protected void establishConnection() {
220         if (fEventPort != -1) {
221             connect();
222         } else {
223             shutDown();
224             return;
225         }
226         
227         fSentProcessId= true;
228         StringBuffer JavaDoc message= new StringBuffer JavaDoc(MessageIds.PROCESS_ID);
229         message.append(fProcessId);
230         sendMessage(message.toString());
231         if (fEventQueue != null) {
232             for (Iterator JavaDoc iter = fEventQueue.iterator(); iter.hasNext();) {
233                 processEvent((BuildEvent)iter.next());
234             }
235             fEventQueue= null;
236         }
237     }
238
239     /* (non-Javadoc)
240      * @see org.apache.tools.ant.BuildListener#messageLogged(org.apache.tools.ant.BuildEvent)
241      */

242     public void messageLogged(BuildEvent event) {
243         if (event.getPriority() > msgOutputLevel && event.getPriority() != InternalAntRunner.MSG_PROJECT_HELP) {
244             return;
245         }
246         
247         if (!fSentProcessId) {
248             if (event.getPriority() == InternalAntRunner.MSG_PROJECT_HELP) {
249                 if (Project.MSG_INFO > msgOutputLevel) {
250                     return;
251                 }
252                 //no buildstarted or project started for project help option
253
establishConnection();
254                 return;
255             }
256             if (fEventQueue == null){
257                 fEventQueue= new ArrayList JavaDoc(10);
258             }
259             fEventQueue.add(event);
260             return;
261         }
262         
263         processEvent(event);
264     }
265
266     private void processEvent(BuildEvent event) {
267         if (event.getTask() != null & !emacsMode) {
268             try {
269                 marshalTaskMessage(event);
270             } catch (IOException JavaDoc e) {
271             }
272         } else {
273             marshalMessage(event);
274         }
275     }
276     
277     private void marshalMessage(BuildEvent event) {
278         String JavaDoc eventMessage= event.getMessage();
279         if (eventMessage.length() == 0) {
280             return;
281         }
282         marshalMessage(event.getPriority(), eventMessage);
283     }
284
285     protected void marshalMessage(int priority, String JavaDoc message) {
286         try {
287             BufferedReader JavaDoc r = new BufferedReader JavaDoc(new StringReader JavaDoc(message));
288             String JavaDoc line = r.readLine();
289             StringBuffer JavaDoc messageLine;
290             while (line != null) {
291                 messageLine= new StringBuffer JavaDoc();
292                 if (priority != -1) {
293                     messageLine.append(priority);
294                     messageLine.append(',');
295                 }
296                 messageLine.append(line);
297                 sendMessage(messageLine.toString());
298                 line = r.readLine();
299             }
300         } catch (IOException JavaDoc e) {
301         }
302     }
303
304     private void marshalTaskMessage(BuildEvent event) throws IOException JavaDoc {
305         String JavaDoc eventMessage= event.getMessage();
306         if (eventMessage.length() == 0) {
307             return;
308         }
309         BufferedReader JavaDoc r = new BufferedReader JavaDoc(new StringReader JavaDoc(eventMessage));
310         String JavaDoc line = r.readLine();
311         StringBuffer JavaDoc message;
312         String JavaDoc taskName= event.getTask().getTaskName();
313         if (taskName != null && taskName.equals(fLastTaskName)) {
314             taskName= ""; //$NON-NLS-1$
315
} else {
316             fLastTaskName= taskName;
317         }
318         Location location= event.getTask().getLocation();
319         String JavaDoc fileName= null;
320         int lineNumber= -1;
321         try {
322             fileName= location.getFileName();
323             lineNumber= location.getLineNumber();
324         } catch (NoSuchMethodError JavaDoc e) {
325             //older Ant
326
fileName= location.toString();
327         }
328         if (location.equals(Location.UNKNOWN_LOCATION)) {
329             fileName= location.toString();
330             lineNumber= -1;
331         }
332         int priority= event.getPriority();
333         while (line != null) {
334             message= new StringBuffer JavaDoc(MessageIds.TASK);
335             message.append(priority);
336             message.append(',');
337             message.append(taskName);
338             message.append(',');
339             message.append(line.length());
340             message.append(',');
341             message.append(line);
342             message.append(',');
343             if (!fileName.equals(fLastFileName)) {
344                 message.append(fileName.length());
345                 message.append(',');
346                 message.append(fileName);
347             }
348             message.append(',');
349             message.append(lineNumber);
350             sendMessage(message.toString());
351             fLastFileName= fileName;
352             line= r.readLine();
353         }
354     }
355     
356     private void marshalTargetMessage(BuildEvent event) {
357         Target target= event.getTarget();
358         Location location= AntDebugState.getLocation(target);
359         
360         StringBuffer JavaDoc message= new StringBuffer JavaDoc();
361         message.append(MessageIds.TARGET);
362         message.append(',');
363         message.append(target.getName());
364         message.append(':');
365         message.append(',');
366         if (location != null && location != Location.UNKNOWN_LOCATION) {
367             //if a target has a valid location then we are on an Ant that is
368
//new enough to have the accessor methods on Location
369
String JavaDoc fileName= location.getFileName();
370             message.append(fileName.length());
371             message.append(',');
372             message.append(fileName);
373             message.append(',');
374             message.append(location.getLineNumber());
375         }
376         sendMessage(message.toString());
377     }
378
379     /* (non-Javadoc)
380      * @see org.apache.tools.ant.BuildListener#buildStarted(org.apache.tools.ant.BuildEvent)
381      */

382     public void buildStarted(BuildEvent event) {
383         establishConnection();
384         super.buildStarted(event);
385     }
386     
387     public void configure(Map JavaDoc userProperties) {
388         String JavaDoc portProperty= (String JavaDoc) userProperties.remove("eclipse.connect.port"); //$NON-NLS-1$
389

390         if (portProperty != null) {
391             fEventPort= Integer.parseInt(portProperty);
392         }
393         
394         fProcessId= (String JavaDoc) userProperties.remove("org.eclipse.ant.core.ANT_PROCESS_ID"); //$NON-NLS-1$
395
}
396 }
Popular Tags