2 * Copyright (C) 2007-2012 Argeo GmbH
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org
.argeo
.eclipse
.ui
.specific
;
18 import java
.lang
.reflect
.Constructor
;
19 import java
.lang
.reflect
.Field
;
20 import java
.lang
.reflect
.Modifier
;
21 import java
.util
.MissingResourceException
;
22 import java
.util
.ResourceBundle
;
24 import org
.argeo
.util
.LocaleUtils
;
25 import org
.eclipse
.osgi
.util
.NLS
;
27 /** NLS attached to a given thread */
28 public class ThreadNLS
<T
extends NLS
> extends InheritableThreadLocal
<T
> {
29 public final static String DEFAULT_BUNDLE_LOCATION
= "/properties/plugin";
31 private final String bundleLocation
;
33 private Class
<T
> type
;
34 private Boolean utf8
= false;
36 public ThreadNLS(String bundleLocation
, Class
<T
> type
, Boolean utf8
) {
37 this.bundleLocation
= bundleLocation
;
42 public ThreadNLS(Class
<T
> type
) {
43 this(DEFAULT_BUNDLE_LOCATION
, type
, false);
47 protected T
initialValue() {
48 ResourceBundle bundle
= ResourceBundle
.getBundle(bundleLocation
,
49 LocaleUtils
.threadLocale
.get(), type
.getClassLoader());
52 NLS
.initializeMessages(bundleLocation
, type
);
53 Constructor
<T
> constructor
= type
.getConstructor();
54 constructor
.setAccessible(true);
55 result
= constructor
.newInstance();
56 final Field
[] fieldArray
= type
.getDeclaredFields();
57 for (int i
= 0; i
< fieldArray
.length
; i
++) {
58 int modifiers
= fieldArray
[i
].getModifiers();
59 if (String
.class.isAssignableFrom(fieldArray
[i
].getType())
60 && Modifier
.isPublic(modifiers
)
61 && !Modifier
.isStatic(modifiers
)) {
64 .getString(fieldArray
[i
].getName());
65 byte[] bytes
= value
.getBytes();
69 forcedValue
= new String(bytes
, "UTF8");
73 fieldArray
[i
].setAccessible(true);
74 fieldArray
[i
].set(result
, forcedValue
);
76 } catch (final MissingResourceException mre
) {
77 fieldArray
[i
].setAccessible(true);
78 fieldArray
[i
].set(result
, "");
79 mre
.printStackTrace();
84 } catch (final Exception ex
) {
85 throw new IllegalStateException(ex
.getMessage());