@Override
  public Response toResponse(Throwable exception) {
    if (logger.isEntryEnabled()) logger.entry("toResponse", exception);

    // Notwithstanding the efforts below to only log genuine error conditions
    // in normal production use, unconditionally stacktrace all exceptions
    // if trace is on.
    if (logger.isDebugEnabled()) logger.stacktrace(exception);

    ResponseBuilder responseBuilder;

    /* check if this is our special case of a wrapped, checked exception */
    if (exception instanceof AmcRuntimeomiserException) {
      exception = ((AmcRuntimeomiserException) exception).getAmcException();
    }

    if (exception instanceof LocalizedException) {
      responseBuilder = Response.status(((LocalizedException) exception).getHttpStatusCode());
      responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
      responseBuilder.entity(new ExceptionResponse(exception));

      if (exception instanceof AmcRuntimeException
          && ((AmcRuntimeException) exception).getMessageCode().equals("CWZBA0504E")) {
        // Stacktrace if this exception didn't have a specific message.
        // Exceptions with messages represent exceptional conditions in
        // WAMC's environment (eg, appliance gone away) rather than
        // errors in WAMC itself, and they generally don't require a
        // stacktrace to figure out what happened.
        logError(exception.getCause() == null ? exception : exception.getCause());
      }
    } else {
      responseBuilder = Response.status(Status.INTERNAL_SERVER_ERROR);
      responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
      final String message =
          (exception.getLocalizedMessage() == null)
              ? exception.getClass().getCanonicalName()
              : exception.getClass().getName() + ": " + exception.getLocalizedMessage();
      responseBuilder.entity(
          new ExceptionResponse(
              SecurityContext.getContext().getUser(),
              new Date(),
              "CWZBA0504E_UNEXPECTED_ERROR",
              message));

      // Always stacktrace un-wrapped exceptions, as they always represent
      // an unexpected error.
      logError(exception);
    }

    Response response = responseBuilder.build();

    if (logger.isEntryEnabled()) logger.exit("toResponse", response);
    return response;
  }
  @Before
  public void setUp() throws Exception {
    device = mock(Device.class);
    manager = mock(Manager.class);
    ManagedSet defaultManagedSet = mock(ManagedSet.class);

    when(manager.getManagedSet(Constants.DEFAULT_MANAGED_SET)).thenReturn(defaultManagedSet);

    appliance = new WamtAppliance(manager, device);
    SecurityContext.setContext("test-user");

    EntityManager manager = PersistenceTools.setPersistenceContext();
    ActionStatusImpl status = mock(ActionStatusImpl.class);
    when(manager.find(ActionStatusImpl.class, new Long(0))).thenReturn(status);
  }