package example.hello.service.impl;

import static example.common.util.ExampleUtils.*;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.HandlerChain;
import javax.jws.WebService;

import example.hello.dto.HelloRequest;
import example.hello.dto.HelloResponse;
import example.hello.exception.HelloException;
import example.hello.manager.CommandMgr;
import example.hello.service.HelloService;
import example.hello.service.RemoteHelloService;

/**
 * Stateless Session Bean の例です。
 * 
 * @author glad
 */
@Stateless
@WebService(
        serviceName = "WsEjbHelloService",
        portName = "HelloPort",
        targetNamespace = "http://ejb.ws.service.hello.example/",
        endpointInterface = "example.hello.service.HelloService")
@HandlerChain(file = "/example/hello/service/ws/handler-chains.xml")
public class HelloServiceBean implements HelloService, RemoteHelloService {

    @EJB
    CommandMgr commandMgr;

    public HelloResponse sayHello(HelloRequest request) throws HelloException {
        String name = request.getName();
        if (name != null && name.startsWith("#")) {
            doCommand(name);
        }
        HelloResponse response = new HelloResponse();
        if (isBlank(name)) {
            response.setMessage("Hello, World!");
        } else {
            response.setMessage("Hello, " + name.trim() + '!');
        }
        return response;
    }

    /**
     * 例外の振る舞いを確認するためのメソッドです。
     */
    void doCommand(String command) throws HelloException {
        if ("#iae".equals(command)) {
            throw new IllegalArgumentException(command);
        } else if ("#error".equals(command)) {
            throw new Error("error");
        }
        commandMgr.doCommand(command);
    }

}
