KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > CreationException


1 /**
2  * Copyright (C) 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package com.google.inject;
18
19 import com.google.inject.spi.Message;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Collection JavaDoc;
22 import java.util.Collections JavaDoc;
23 import java.util.Comparator JavaDoc;
24 import java.util.Formatter JavaDoc;
25 import java.util.List JavaDoc;
26
27 /**
28  * Thrown when errors occur while creating a {@link Injector}. Includes a list
29  * of encountered errors. Typically, a client should catch this exception, log
30  * it, and stop execution.
31  *
32  * @author crazybob@google.com (Bob Lee)
33  */

34 public class CreationException extends RuntimeException JavaDoc {
35
36   final List JavaDoc<Message> errorMessages;
37
38   /**
39    * Constructs a new exception for the given errors.
40    */

41   public CreationException(Collection JavaDoc<Message> errorMessages) {
42     super();
43
44     // Sort the messages by source.
45
this.errorMessages = new ArrayList JavaDoc<Message>(errorMessages);
46     Collections.sort(this.errorMessages, new Comparator JavaDoc<Message>() {
47       public int compare(Message a, Message b) {
48         return a.getSourceString().compareTo(b.getSourceString());
49       }
50     });
51   }
52
53   public String JavaDoc getMessage() {
54     return createErrorMessage(errorMessages);
55   }
56
57   private static String JavaDoc createErrorMessage(Collection JavaDoc<Message> errorMessages) {
58     Formatter JavaDoc fmt = new Formatter JavaDoc().format("Guice configuration errors:%n%n");
59     int index = 1;
60     for (Message errorMessage : errorMessages) {
61       fmt.format("%s) Error at %s:%n", index++, errorMessage.getSourceString())
62          .format(" %s%n%n", errorMessage.getMessage());
63     }
64     return fmt.format("%s error[s]", errorMessages.size()).toString();
65   }
66
67   /**
68    * Gets the error messages which resulted in this exception.
69    */

70   public Collection JavaDoc<Message> getErrorMessages() {
71     return Collections.unmodifiableCollection(errorMessages);
72   }
73 }
74
Popular Tags