org.wisepersist.gwtmockito.ng.fakes.FakeMessagesProvider.java Source code

Java tutorial

Introduction

Here is the source code for org.wisepersist.gwtmockito.ng.fakes.FakeMessagesProvider.java

Source

/*
 * Copyright (c) 2013 Google Inc.
 * Copyright (c) 2016 WisePersist.org
 *
 * Licensed 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 org.wisepersist.gwtmockito.ng.fakes;

import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.safehtml.shared.SafeUri;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * Provides fake implementations of {@link com.google.gwt.i18n.client.Messages},
 * {@link com.google.gwt.resources.client.CssResource}, and
 * {@link com.google.gwt.safehtml.client.SafeHtmlTemplates}. The fake
 * implementations implement methods by returning Strings of SafeHtml instances
 * based on the method name and the arguments passed to it. The exact format of
 * the message is undefined and is subject to change.
 *
 * @author ekuefler@google.com (Erik Kuefler)
 * @param <T> The actual type class of the {@link FakeProvider} interface.
 */
public class FakeMessagesProvider<T> implements FakeProvider<T> {

    /**
     * Returns a new instance of the given type that implements methods as
     * described in the class description.
     *
     * @param type Interface to be implemented by the returned type.
     */
    @Override
    @SuppressWarnings("unchecked") // safe since the proxy implements type
    public final T getFake(final Class<?> type) {
        return (T) Proxy.newProxyInstance(FakeMessagesProvider.class.getClassLoader(), new Class<?>[] { type }, //NOPMD
                new InvocationHandler() {
                    @Override
                    public Object invoke(final Object proxy, final Method method, final Object[] args) //NOPMD
                            throws Exception {
                        return doInvoke(method, args);
                    }
                });
    }

    /**
     * Fake invoking on a specified method with arguments.
     *
     * @param method The method specified.
     * @param args The arguments specified.
     * @return The result object.
     */
    private Object doInvoke(final Method method, final Object... args) {
        final Object result;
        if (method.getName().equals("ensureInjected")) {
            result = true;
        } else if (method.getReturnType() == String.class) {
            result = buildMessage(method, args);
        } else if (method.getReturnType() == SafeHtml.class) {
            result = SafeHtmlUtils.fromTrustedString(buildMessage(method, args));
        } else {
            throw new IllegalArgumentException(method.getName() + " must return either String or SafeHtml");
        }
        return result;
    }

    /**
     * Builds message of a method with arguments.
     *
     * @param method The method specified.
     * @param args The arguments specified.
     * @return The message string specified.
     */
    private String buildMessage(final Method method, final Object... args) {
        final StringBuilder message = new StringBuilder(method.getName());
        final String msgStr;
        if (args == null || args.length == 0) {
            msgStr = message.toString();
        } else {
            message.append('(');
            message.append(stringify(args[0]));
            for (final Object arg : Arrays.asList(args).subList(1, args.length)) {
                message.append(", ").append(stringify(arg));
            }
            msgStr = message.append(')').toString();
        }
        return msgStr;
    }

    /**
     * Stringifies an object.
     *
     * @param arg The object arg specified.
     * @return The string of the object.
     */
    private String stringify(final Object arg) {
        final String result;
        if (arg == null) {
            result = "null";
        } else if (arg instanceof SafeHtml) {
            result = ((SafeHtml) arg).asString();
        } else if (arg instanceof SafeUri) {
            result = ((SafeUri) arg).asString();
        } else {
            result = arg.toString();
        }
        return result;
    }
}