Stuart McCulloch | 4482c70 | 2012-06-15 13:27:53 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (c) OSGi Alliance (2012). All Rights Reserved. |
| 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 aQute.libg.reporter; |
| 18 | |
| 19 | import java.lang.reflect.*; |
| 20 | import java.util.*; |
| 21 | |
| 22 | import aQute.libg.reporter.Messages.ERROR; |
| 23 | import aQute.libg.reporter.Messages.WARNING; |
| 24 | |
| 25 | public class ReporterMessages { |
| 26 | |
| 27 | @SuppressWarnings("unchecked") |
| 28 | public static <T> T base(final Reporter reporter, Class<T> messages) { |
| 29 | return (T) Proxy.newProxyInstance(messages.getClassLoader(), new Class[] { |
| 30 | messages |
| 31 | }, new InvocationHandler() { |
| 32 | |
| 33 | public Object invoke(Object target, Method method, Object[] args) throws Throwable { |
| 34 | if (reporter.isExceptions()) { |
| 35 | for (Object o : args) { |
| 36 | if (o instanceof Throwable) |
| 37 | ((Throwable) o).printStackTrace(); |
| 38 | } |
| 39 | } |
| 40 | String format; |
| 41 | Message d = method.getAnnotation(Message.class); |
| 42 | if (d == null) { |
| 43 | String name = method.getName(); |
| 44 | StringBuilder sb = new StringBuilder(); |
| 45 | sb.append(name.charAt(0)); |
| 46 | for (int i = 1; i < name.length(); i++) { |
| 47 | char c = name.charAt(i); |
| 48 | switch (c) { |
| 49 | case '_' : |
| 50 | sb.append(" %s, "); |
| 51 | break; |
| 52 | |
| 53 | default : |
| 54 | if (Character.isUpperCase(c)) { |
| 55 | sb.append(" "); |
| 56 | c = Character.toLowerCase(c); |
| 57 | } |
| 58 | sb.append(c); |
| 59 | } |
| 60 | } |
| 61 | format = sb.toString(); |
| 62 | } else |
| 63 | format = d.value(); |
| 64 | |
| 65 | try { |
| 66 | if (method.getReturnType() == ERROR.class) { |
| 67 | reporter.error(format, args); |
| 68 | } else if (method.getReturnType() == WARNING.class) { |
| 69 | reporter.warning(format, args); |
| 70 | } else |
| 71 | reporter.trace(format, args); |
| 72 | } |
| 73 | catch (IllegalFormatException e) { |
| 74 | reporter.error("Formatter failed: %s %s %s", method.getName(), format, Arrays.toString(args)); |
| 75 | } |
| 76 | return null; |
| 77 | } |
| 78 | }); |
| 79 | } |
| 80 | } |