1 package org.apache.maven.usability.diagnostics;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.codehaus.plexus.PlexusConstants;
23 import org.codehaus.plexus.PlexusContainer;
24 import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException;
25 import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
26 import org.codehaus.plexus.context.Context;
27 import org.codehaus.plexus.context.ContextException;
28 import org.codehaus.plexus.logging.AbstractLogEnabled;
29 import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
30
31 import java.util.Iterator;
32 import java.util.List;
33
34 public class ErrorDiagnostics
35 extends AbstractLogEnabled
36 implements Contextualizable
37 {
38 public static final String ROLE = ErrorDiagnostics.class.getName();
39
40 private PlexusContainer container;
41
42 private List errorDiagnosers;
43
44 public void setErrorDiagnosers( List errorDiagnosers )
45 {
46 this.errorDiagnosers = errorDiagnosers;
47 }
48
49 public String diagnose( Throwable error )
50 {
51 List diags = errorDiagnosers;
52
53 boolean releaseDiags = false;
54 boolean errorProcessed = false;
55
56 String message = null;
57
58 try
59 {
60 if ( diags == null )
61 {
62 releaseDiags = true;
63
64 try
65 {
66 diags = container.lookupList( ErrorDiagnoser.ROLE );
67 }
68 catch ( ComponentLookupException e )
69 {
70 getLogger().error( "Failed to lookup the list of error diagnosers.", e );
71 }
72 }
73
74 if ( diags != null )
75 {
76 for ( Iterator it = diags.iterator(); it.hasNext(); )
77 {
78 ErrorDiagnoser diagnoser = (ErrorDiagnoser) it.next();
79
80 if ( diagnoser.canDiagnose( error ) )
81 {
82 errorProcessed = true;
83
84 message = diagnoser.diagnose( error );
85
86 break;
87 }
88 }
89 }
90 }
91 finally
92 {
93 if ( releaseDiags && diags != null )
94 {
95 try
96 {
97 container.releaseAll( diags );
98 }
99 catch ( ComponentLifecycleException e )
100 {
101 getLogger().debug( "Failed to release error diagnoser list.", e );
102 }
103 }
104
105 if ( !errorProcessed )
106 {
107 message = new PuntErrorDiagnoser().diagnose( error );
108 }
109 }
110
111 return message;
112 }
113
114 public void contextualize( Context context )
115 throws ContextException
116 {
117 this.container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
118 }
119
120 private static class PuntErrorDiagnoser
121 implements ErrorDiagnoser
122 {
123
124 public boolean canDiagnose( Throwable error )
125 {
126 return true;
127 }
128
129 public String diagnose( Throwable error )
130 {
131 StringBuffer message = new StringBuffer();
132
133 message.append( error.getMessage() );
134
135 DiagnosisUtils.appendRootCauseIfPresentAndUnique( error, message, false );
136
137 return message.toString();
138 }
139
140 }
141 }