Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   *  or more contributor license agreements.  See the NOTICE file
   *  distributed with this work for additional information
   *  regarding copyright ownership.  The ASF licenses this file
   *  to you under the Apache License, Version 2.0 (the
   *  "License"); you may not use this file except in compliance
   *  with the License.  You may obtain a copy of the License at
   *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  *  Unless required by applicable law or agreed to in writing,
  *  software distributed under the License is distributed on an
  *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  *  KIND, either express or implied.  See the License for the
  *  specific language governing permissions and limitations
  *  under the License.
  */
 
 package com.github.rodionmoiseev.c10n;
 
 
 import java.util.*;
 
 @SuppressWarnings("WeakerAccess")//rationale: designed for 3rd party usage
 public abstract class C10NConfigBase {
     //DI
     private final C10NCoreModule coreModule = new C10NCoreModule();
     private final Map<StringC10NBundleBinderbundleBinders = new HashMap<StringC10NBundleBinder>();
     private final Map<Class<?>, C10NImplementationBinder<?>> binders = new HashMap<Class<?>, C10NImplementationBinder<?>>();
     private final Map<Class<? extends Annotation>, C10NAnnotationBinderannotationBinders = new HashMap<Class<? extends Annotation>, C10NAnnotationBinder>();
     private final List<C10NFilterBinder<?>> filterBinders = new ArrayList<C10NFilterBinder<?>>();
     private final List<C10NConfigBasechildConfigs = new ArrayList<C10NConfigBase>();
     private String keyPrefix = "";
 
     private boolean debug = false;
 
     private boolean configured = false;

    

To be implemented by subclasses of C10NConfigBase.

Configuration methods are as follows:

 
     protected abstract void configure();

    

Get the name of the package for which the current module is responsible.

The name of the package is used to determine which c10n interfaces this configuration is responsible for

The default implementation, which returns the string representation of the package of the configuration class, should suffice in most cases

Returns:
name of package the current module is responsible for
 
     protected String getConfigurationPackage() {
         Package pkg = getClass().getPackage();
         return pkg != null ? pkg.getName() : "";
     }
 
     void doConfigure() {
         if (!) {
             configure();
         }
          = true;
     }

    

Install the given child c10n configuration module

This will apply the configuration to all c10n interfaces located in the child configuration package or below.

Parameters:
childConfig child c10n configuration to install (not-null)
 
     protected void install(C10NConfigBase childConfig) {
        childConfig.doConfigure();
        .add(childConfig);
    }

    

Create a custom implementation binding for the given c10n interface

There are two basic usages:


   bind(Messages.class).to(JapaneseMessagesImpl.class, Locale.JAPANESE);
 

which will use the JapaneseMessagesImpl.class when locale is set to Locale.JAPANESE

The second usage is:


   bind(Messages.class).to(FallbackMessagesImpl.class);
 

which will use the FallbackMessagesImpl.class when no other implementation class was matched for the current locale.

Parameters:
c10nInterface C10N interface to create an implementation binding for (not-null)
<T> C10N interface type
Returns:
implementation binding DSL object
    protected <T> C10NImplementationBinder<T> bind(Class<T> c10nInterface) {
        C10NImplementationBinder<T> binder = new C10NImplementationBinder<T>();
        .put(c10nInterfacebinder);
        return binder;
    }

    

Sets the LocaleProvider for this configuration.

Locale provider is consulted every time a translation is requested, that is every time a method on an c10n interface is called.

As a rule, there should be only one locale provider per application. Any locale providers defined in child configurations (see install(com.github.rodionmoiseev.c10n.C10NConfigBase) are disregarded.

Because locale provider has to be consulted on every translation request LocaleProvider.getLocale() should avoid any CPU intensive processing

Default locale provider implementation always returns the same result as java.util.Locale.getDefault()

Parameters:
localeProvider custom locale provider (not-null)
    protected void setLocaleProvider(LocaleProvider localeProvider) {
        Preconditions.assertNotNull(localeProvider"localeProvider");
        this. = localeProvider;
    }

    

Fixes the java.util.Locale to the specified locale.

Generally useful when your application needs to create separate C10NMsgFactory instances for each locale.

Parameters:
locale Locale to use
    protected void setLocale(Locale locale) {
        this. = LocaleProviders.fixed(locale);
    }

    

Customise placeholder value for unresolved translations.

The default behaviour is to return a string in format:

   [InterfaceName].[MethodName]([ArgumentValues])
 

Parameters:
handler custom implementation of untranslated message handler (not-null)
    protected void setUntranslatedMessageHandler(UntranslatedMessageHandler handler) {
        Preconditions.assertNotNull(handler"handler");
        this. = handler;
    }

    

Create a method annotation binding to the specified locale

There are two basic usages:


   bindAnnotation(Ja.class).to(Locale.JAPANESE);
 

which will tell c10n to take the value given in the @Ja annotation whenever the current locale is Locale.JAPANESE

The second usage is:


   bindAnnotation(En.class);
 

which will make c10n always fallback to the value given in the @En annotation if no other annotation binding matched the current locale.

Note: Some default annotation bindings are defined in com.github.rodionmoiseev.c10n.annotations.DefaultC10NAnnotations. In order to use install(new DefaultC10NAnnotations()); somewhere in your configuration (see install(com.github.rodionmoiseev.c10n.C10NConfigBase)

Parameters:
annotationClass Class of the annotation to create a local binding for (not-null)
Returns:
annotation locale binding DSL object
    protected C10NAnnotationBinder bindAnnotation(Class<? extends AnnotationannotationClass) {
        Preconditions.assertNotNull(annotationClass"annotationClass");
        checkAnnotationInterface(annotationClass);
        C10NAnnotationBinder binder = new C10NAnnotationBinder();
        .put(annotationClassbinder);
        return binder;
    }

    

Create a filter binding for one or more argument types.

All arguments passed to c10n-interfaces with the specified type(s) will be converted to string using the filter generated by the given filter provider, instead of the conventional toString() method.

Filter creation (using C10NFilterProvider.get() method) will be deferred until the first call to a c10n-interface method with a matching argument type is executed.

Parameters:
c10NFilterProvider provider of filter implementation (not-null)
type method argument type to which the filter should be applied
Returns:
filter binding DSL object
See also:
C10NConfigBase.C10NFilterBinder
    protected <T> C10NFilterBinder<T> bindFilter(C10NFilterProvider<T> c10NFilterProviderClass<T> type) {
        Preconditions.assertNotNull(c10NFilterProvider"c10nFilterProvider");
        Preconditions.assertNotNull(type"type");
        C10NFilterBinder<T> filterBinder = new C10NFilterBinder<T>(c10NFilterProvidertype);
        .add(filterBinder);
        return filterBinder;
    }

    

Create a filter binding for one or more argument types.

All arguments passed to c10n-interfaces with the specified type(s) will be converted to string using this filter, instead of the conventional toString() method.

Parameters:
c10nFilter filter implementation (not-null)
type method argument type to which the filter should be applied
Returns:
filter binding DSL object
See also:
C10NConfigBase.C10NFilterBinder
    protected <T> C10NFilterBinder<T> bindFilter(C10NFilter<T> c10nFilterClass<T> type) {
        Preconditions.assertNotNull(c10nFilter"c10nFilter");
        Preconditions.assertNotNull(type"type");
        C10NFilterBinder<T> filterBinder = new C10NFilterBinder<T>(C10NFilters.staticFilterProvider(c10nFilter), type);
        .add(filterBinder);
        return filterBinder;
    }

    

Set global key prefix. All other keys will be automatically prepended with the global key.

Settings key prefix to an empty string resets to default behaviour (no prefix).

Parameters:
key the key to use at configuration scope (not null)
    protected void setKeyPrefix(String key) {
        Preconditions.assertNotNull(key"key");
         = key;
    }
    String getKeyPrefix() {
        return ;
    }

    

If set to 'true', c10n will output debugging information to std-out at configuration and lookup time.

Parameters:
debug debug flag
    protected void setDebug(boolean debug) {
        this. = debug;
    }
    boolean isDebug() {
        return ;
    }
        return ;
    }
    private void checkAnnotationInterface(Class<? extends AnnotationannotationClass) {
        if (noMethod(annotationClass"value") &&
                noMethod(annotationClass"intRes") &&
                noMethod(annotationClass"extRes"))
            throw new C10NConfigException("Annotation could not be bound because it's missing any of value()," +
                    " intRes() or extRes() methods that return String. " +
                    "Please add at least one of those methods with return type of String. " +
                    "annotationClass=" + annotationClass.getName());
    }
    private boolean noMethod(Class<? extends AnnotationannotationClassString methodName) {
        Method valueMethod;
        try {
            valueMethod = annotationClass.getMethod(methodName);
            if (!valueMethod.getReturnType().isAssignableFrom(String.class)) {
                return true;
            }
        } catch (NoSuchMethodException e) {
            return true;
        }
        return false;
    }
    protected C10NBundleBinder bindBundle(String baseName) {
        C10NBundleBinder binder = new C10NBundleBinder();
        .put(baseNamebinder);
        return binder;
    }
    List<ResourceBundlegetBundlesForLocale(Class<?> c10nInterfaceLocale locale) {
        List<ResourceBundleres = new ArrayList<ResourceBundle>();
        for (Entry<StringC10NBundleBinderentry : .entrySet()) {
            C10NBundleBinder binder = entry.getValue();
            if (binder.getBoundInterfaces().isEmpty()
                    || binder.getBoundInterfaces().contains(c10nInterface)) {
                res.add(ResourceBundle.getBundle(entry.getKey(), locale,
                        new EncodedResourceControl("UTF-8")));
            }
        }
        return res;
    }

    
For each annotation bound in this configuration find all locales it has been bound to.

Returns:
annotation -> set of locale mapping
        Map<Class<? extends Annotation>, Set<Locale>> res = new HashMap<Class<? extends Annotation>, Set<Locale>>();
        for (Entry<Class<? extends Annotation>, C10NAnnotationBinderentry : .entrySet()) {
            Set<Localelocales = getLocales(entry.getKey(), res);
            locales.add(entry.getValue().getLocale());
        }
        return res;
    }
    private Set<LocalegetLocales(Class<? extends AnnotationkeyMap<Class<? extends Annotation>, Set<Locale>> res) {
        Set<Localelocales = res.get(key);
        if (null == locales) {
            locales = new HashSet<Locale>();
            res.put(keylocales);
        }
        return locales;
    }
    Class<?> getBindingForLocale(Class<?> c10nInterfaceLocale locale) {
        C10NImplementationBinder<?> binder = .get(c10nInterface);
        if (null != binder) {
            Class<?> impl = binder.getBindingForLocale(locale);
            if (null != impl) {
                return impl;
            }
        }
        return null;
    }

    
List of all installed child configurations in the order they were installed.

Returns:
List of child configurations
        return ;
    }

    
Find all locales that have explicit implementation class bindings for this c10n interface.

Parameters:
c10nInterface interface to find bindings for (not-null)
Returns:
Set of locales (not-null)
    Set<LocalegetImplLocales(Class<?> c10nInterface) {
        Set<Localeres = new HashSet<Locale>();
        C10NImplementationBinder<?> binder = .get(c10nInterface);
        if (binder != null) {
            res.addAll(binder.bindings.keySet());
        }
        return res;
    }

    

Get a set of all locales explicitly declared in implementation bindings

Returns:
set of all bound locales
        Set<Localeres = new HashSet<Locale>();
        for (C10NImplementationBinder<?> binder : .values()) {
            res.addAll(binder.bindings.keySet());
        }
        return res;
    }

    
Get the current locale as stipulated by the locale provider

Returns:
current locale
        return .getLocale();
    }
    String getUntranslatedMessageString(Class<?> c10nInterfaceMethod methodObject[] methodArgs) {
        return .render(c10nInterfacemethodmethodArgs);
    }
    protected static class C10NAnnotationBinder {
        private Locale locale = .;
        public void toLocale(Locale locale) {
            Preconditions.assertNotNull(locale"locale");
            this. = locale;
        }
        public Locale getLocale() {
            return ;
        }
    }
    protected static final class C10NImplementationBinder<T> {
        private final Map<LocaleClass<?>> bindings = new HashMap<LocaleClass<?>>();
        public C10NImplementationBinder<T> to(Class<? extends T> toLocale forLocale) {
            .put(forLocaleto);
            return this;
        }
        public C10NImplementationBinder<T> to(Class<? extends T> to) {
            .put(.to);
            return this;
        }
        Class<?> getBindingForLocale(Locale locale) {
            return .get(locale);
        }
    }

    

Filter binding DSL object.

Use annotatedWith(java.lang.Class) method to restrict the filter to arguments annotated with the specified annotation(s). Multiple annotations may be specified using chained annotatedWith(java.lang.Class) methods.

    protected static final class C10NFilterBinder<T> {
        private final C10NFilterProvider<T> filter;
        private final Class<T> type;
        private final List<Class<? extends Annotation>> annotatedWith = new ArrayList<Class<? extends Annotation>>();
        private C10NFilterBinder(C10NFilterProvider<T> filterClass<T> type) {
            this. = filter;
            this. = type;
        }

        

Restrict filter application only to arguments annotated with the given annotation.

Multiple annotations can be specified using method chaining.

Parameters:
annotation annotation class to restrict filter application to
Returns:
this DLS object for method chaining
        public C10NFilterBinder<T> annotatedWith(Class<? extends Annotationannotation) {
            this..add(annotation);
            return this;
        }
        C10NFilterProvider<T> getFilterProvider() {
            return ;
        }
        Class<T> getType() {
            return ;
        }
        public List<Class<? extends Annotation>> getAnnotatedWith() {
            for (Class<? extends Annotationa : ) {
            }
            return ;
        }
    }
New to GrepCode? Check out our FAQ X