/** Transcribes from XML to types supported by BISDL or Transcribable Java objects. */
@SuppressWarnings("unchecked")
public class XMLTranscriptionInput implements TranscriptionInput {

  private static final CougarLogger logger =
      CougarLoggingUtils.getLogger(XMLTranscriptionInput.class);

  private static final QName keyAttName = new QName("key");

  private OMElement currentNode;

  public XMLTranscriptionInput(OMElement currentNode) {
    this.currentNode = currentNode;
  }

  public Object readObject(Parameter param, boolean client) throws Exception {
    Iterator iterator = currentNode.getChildrenWithLocalName(param.getName());
    if (!iterator.hasNext()) {
      return null;
    }

    return readObject(param.getParameterType(), (OMElement) iterator.next(), client);
  }

  private Object readObject(ParameterType paramType, OMElement node, boolean client)
      throws Exception {
    switch (paramType.getType()) {
      case BOOLEAN:
      case DOUBLE:
      case FLOAT:
      case INT:
      case LONG:
      case STRING:
      case ENUM:
      case DATE:
      case BYTE:
        return node == null
            ? null
            : readSimpleObject(paramType, node.getLocalName(), node.getText(), client);
      case OBJECT:
        // descend - note possibly two levels if inside a collection recursion
        OMElement _copy = this.currentNode;
        currentNode = node;

        Transcribable t = (Transcribable) paramType.getImplementationClass().newInstance();
        t.transcribe(this, TranscribableParams.getAll(), client);

        // ascend
        this.currentNode = _copy;
        return t;
      case MAP:
        Map map = new HashMap();
        for (Iterator i = node.getChildElements(); i.hasNext(); ) {
          OMElement element = (OMElement) i.next();
          Object key =
              readSimpleObject(
                  paramType.getComponentTypes()[0],
                  node.getLocalName(),
                  element.getAttributeValue(keyAttName),
                  client);
          map.put(
              key,
              readObject(
                  paramType.getComponentTypes()[1],
                  (OMElement) element.getChildElements().next(),
                  client));
        }
        return map;
      case LIST:
        if (paramType.getComponentTypes()[0].getType() == ParameterType.Type.BYTE) {
          try {
            return Base64Utils.decode(node.getText());
          } catch (Exception e) {
            String message = "Unable to parse " + node.getText() + " as type " + paramType;
            logger.log(Level.FINER, message, e);
            throw CougarMarshallingException.unmarshallingException("soap", message, e, client);
          }
        } else {
          List list = new ArrayList();
          for (Iterator i = node.getChildElements(); i.hasNext(); ) {
            list.add(readObject(paramType.getComponentTypes()[0], (OMElement) i.next(), client));
          }
          return list;
        }
      case SET:
        Set set = new HashSet();
        for (Iterator i = node.getChildElements(); i.hasNext(); ) {
          set.add(readObject(paramType.getComponentTypes()[0], (OMElement) i.next(), client));
        }
        return set;
    }
    return null;
  }

  private Object readSimpleObject(
      ParameterType paramType, String paramName, String textValue, boolean client) {
    try {
      switch (paramType.getType()) {
        case BOOLEAN:
          if (textValue.equalsIgnoreCase("true")) {
            return true;
          }
          if (textValue.equalsIgnoreCase("false")) {
            return false;
          }
          throw new IllegalArgumentException();
        case DOUBLE:
          return Double.valueOf(textValue);
        case FLOAT:
          return Float.valueOf(textValue);
        case INT:
          return Integer.valueOf(textValue);
        case LONG:
          return Long.valueOf(textValue);
        case STRING:
          return textValue;
        case ENUM:
          // this is converted to an enum further down in the Transcribable implementation so the
          // original raw value can be stored in a soft failure..
          return textValue;
        case DATE:
          return DateTimeUtility.parse(textValue);
        case BYTE:
          return Byte.valueOf(textValue);
      }
    } catch (Exception e) {
      throw exceptionDuringDeserialisation(paramType, paramName, e, client);
    }
    throw new UnsupportedOperationException(
        "Parameter Type " + paramType + " is not supported as a simple object type");
  }

  public static CougarValidationException exceptionDuringDeserialisation(
      ParameterType paramType, String paramName, Exception e, boolean client) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append("Unable to convert data in request to ");
    logBuffer.append(paramType.getType().name());
    logBuffer.append(" for parameter: ");
    logBuffer.append(paramName);
    String message = logBuffer.toString();

    logger.log(Level.FINER, message, e);
    throw CougarMarshallingException.unmarshallingException("xml", message, e, client);
  }
}
/** This class is used as a stub to facilitate NIO unit testing */
public class ServerClientFactory {
  private static CougarLogger logger = CougarLoggingUtils.getLogger(ServerClientFactory.class);

  public static final int COMMAND_STOP_SERVER = 1;
  public static final int COMMAND_SLEEP_60S = 2;
  public static final int COMMAND_ECHO_ARG2 = 100;
  public static final int COMMAND_FRAMEWORK_ERROR = 999;

  public static ExecutionVenueNioServer createServer(byte serverVersion, TlsNioConfig cfg) {
    CougarProtocol.setMinServerProtocolVersion(serverVersion);
    CougarProtocol.setMaxServerProtocolVersion(serverVersion);
    final ExecutionVenueNioServer server = new ExecutionVenueNioServer();
    server.setNioConfig(cfg);

    SocketTransportCommandProcessor cmdProcessor = new SocketTransportCommandProcessor();
    cmdProcessor.setIdentityResolverFactory(new IdentityResolverFactory());

    Executor executor =
        new Executor() {
          @Override
          public void execute(Runnable command) {
            Thread t = new Thread(command);
            t.start();
          }
        };

    GeoIPLocator geo = Mockito.mock(GeoIPLocator.class);
    SocketRMIMarshaller marshaller =
        new SocketRMIMarshaller(
            geo, new CommonNameCertInfoExtractor(), new DefaultSocketTimeResolver(true));
    IdentityResolverFactory identityResolverFactory = new IdentityResolverFactory();
    identityResolverFactory.setIdentityResolver(Mockito.mock(IdentityResolver.class));

    ExecutionVenue ev =
        new ExecutionVenue() {
          @Override
          public void registerOperation(
              String namespace,
              OperationDefinition def,
              Executable executable,
              ExecutionTimingRecorder recorder,
              long maxExecutionTime) {}

          @Override
          public OperationDefinition getOperationDefinition(OperationKey key) {
            return AbstractClientTest.OPERATION_DEFINITION;
          }

          @Override
          public Set<OperationKey> getOperationKeys() {
            return null;
          }

          @Override
          public void execute(
              ExecutionContext ctx,
              OperationKey key,
              Object[] args,
              ExecutionObserver observer,
              TimeConstraints timeConstraints) {
            switch (Integer.parseInt(args[1].toString())) {
              case COMMAND_STOP_SERVER:
                logger.log(Level.INFO, "Stopping server");
                server.stop();
                break;
              case COMMAND_SLEEP_60S:
                logger.log(Level.INFO, "Sleeping for 60s");
                try {
                  Thread.sleep(60000L);
                } catch (Exception e) {
                }
              case COMMAND_ECHO_ARG2:
                observer.onResult(new ExecutionResult(args[2]));
                break;
              case COMMAND_FRAMEWORK_ERROR:
                observer.onResult(
                    new ExecutionResult(
                        new CougarServiceException(
                            ServerFaultCode.FrameworkError, AbstractClientTest.BANG)));
                break;
            }
          }

          public void execute(
              final ExecutionContext ctx,
              final OperationKey key,
              final Object[] args,
              final ExecutionObserver observer,
              Executor executor,
              final TimeConstraints timeConstraints) {
            executor.execute(
                new Runnable() {
                  @Override
                  public void run() {
                    execute(ctx, key, args, observer, timeConstraints);
                  }
                });
          }

          @Override
          public void setPreProcessors(List<ExecutionPreProcessor> preProcessorList) {}

          @Override
          public void setPostProcessors(List<ExecutionPostProcessor> preProcessorList) {}
        };

    cmdProcessor.setExecutor(executor);
    cmdProcessor.setMarshaller(marshaller);
    cmdProcessor.setExecutionVenue(ev);
    ServiceBindingDescriptor desc =
        new SocketBindingDescriptor() {
          @Override
          public OperationBindingDescriptor[] getOperationBindings() {
            return new OperationBindingDescriptor[] {
              new SocketOperationBindingDescriptor(
                  AbstractClientTest.OPERATION_DEFINITION.getOperationKey())
            };
          }

          @Override
          public ServiceVersion getServiceVersion() {
            return AbstractClientTest.OPERATION_DEFINITION.getOperationKey().getVersion();
          }

          @Override
          public String getServiceName() {
            return AbstractClientTest.OPERATION_DEFINITION.getOperationKey().getServiceName();
          }

          @Override
          public Protocol getServiceProtocol() {
            return Protocol.SOCKET;
          }
        };
    cmdProcessor.bind(desc);
    cmdProcessor.onCougarStart();

    final NioLogger nioLogger = new NioLogger("ALL");
    ExecutionVenueServerHandler handler =
        new ExecutionVenueServerHandler(nioLogger, cmdProcessor, new HessianObjectIOFactory());
    server.setServerHandler(handler);

    IoSessionManager sessionManager = new IoSessionManager();
    sessionManager.setNioLogger(nioLogger);
    sessionManager.setMaxTimeToWaitForRequestCompletion(5000);
    server.setSessionManager(sessionManager);

    return server;
  }

  public static TlsNioConfig getDefaultConfig() {
    TlsNioConfig cfg = new TlsNioConfig();
    cfg.setNioLogger(new NioLogger("ALL"));

    cfg.setReuseAddress(true);
    cfg.setTcpNoDelay(true);

    return cfg;
  }

  public static ExecutionVenueNioServer createServer(String host, int port, byte serverVersion) {
    return createServer(host, port, serverVersion, getDefaultConfig());
  }

  public static ExecutionVenueNioServer createServer(
      String host, int port, byte serverVersion, TlsNioConfig cfg) {
    cfg.setListenAddress(host);
    cfg.setListenPort(port);

    return createServer(serverVersion, cfg);
  }

  public static ExecutionVenueNioClient createClient(String connectionString, NioConfig cfg) {
    GeoIPLocator geo = Mockito.mock(GeoIPLocator.class);
    SocketRMIMarshaller marshaller =
        new SocketRMIMarshaller(
            geo, new CommonNameCertInfoExtractor(), new DefaultSocketTimeResolver());
    IdentityResolverFactory factory = new IdentityResolverFactory();
    factory.setIdentityResolver(Mockito.mock(IdentityResolver.class));

    NioLogger logger = new NioLogger("ALL");
    ExecutionVenueNioClient client =
        new ExecutionVenueNioClient(
            logger,
            cfg,
            new HessianObjectIOFactory(),
            new ClientConnectedObjectManager(),
            null,
            connectionString,
            new JMXReportingThreadPoolExecutor(
                30, 60, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()),
            new JMXReportingThreadPoolExecutor(
                30, 60, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()),
            new DNSBasedAddressResolver());
    client.setMarshaller(marshaller);

    return client;
  }

  public static ExecutionVenueNioClient createClient(String connectionString) {
    return createClient(connectionString, getDefaultConfig());
  }
}
Beispiel #3
0
@ManagedResource
public class HealthServiceImpl implements HealthService {
  static final CougarLogger logger = CougarLoggingUtils.getLogger(HealthServiceImpl.class);

  private MonitorRegistry monitorRegistry;

  @Override
  public void init(ContainerContext cc) {
    this.monitorRegistry = cc.getMonitorRegistry();
  }

  @Override
  public HealthSummaryResponse isHealthy(final RequestContext ctx, TimeConstraints timeConstraints)
      throws HealthException {
    HealthSummaryResponse response = new HealthSummaryResponse();

    if (isSystemInService()) {
      response.setHealthy(getHealth());
    } else {
      response.setHealthy(RestrictedHealthStatus.FAIL);
    }
    return response;
  }

  private RestrictedHealthStatus getHealth() throws HealthException {
    RestrictedHealthStatus currentState = RestrictedHealthStatus.OK;

    if (monitorRegistry == null) {
      logger.log(Level.SEVERE, "MonitorRegistry is null");
      throw new HealthException(ResponseCode.InternalError, HealthExceptionErrorCodeEnum.NULL);
    }
    StatusAggregator agg = monitorRegistry.getStatusAggregator();
    if (agg == null) {
      logger.log(Level.SEVERE, "StatusAggregator is null");
      throw new HealthException(ResponseCode.InternalError, HealthExceptionErrorCodeEnum.NULL);
    }
    Status status = agg.getStatus();
    if (status == null) {
      logger.log(Level.SEVERE, "Status is null");
      throw new HealthException(ResponseCode.InternalError, HealthExceptionErrorCodeEnum.NULL);
    }
    if (status.equals(Status.FAIL)) {
      currentState = RestrictedHealthStatus.FAIL;
    }
    return currentState;
  }

  @Override
  public HealthDetailResponse getDetailedHealthStatus(
      RequestContext reqCtx, TimeConstraints timeConstraints) throws HealthException {
    HealthDetailResponse detail = new HealthDetailResponse();

    List<SubComponentStatus> subStatuses = new ArrayList<>();
    for (Monitor m : monitorRegistry.getMonitorSet()) {
      SubComponentStatus scs = new SubComponentStatus();
      scs.setName(m.getName());
      Status monitorStatus = m.getStatus();
      scs.setStatus(getHealthStatus(monitorStatus));
      subStatuses.add(scs);
    }
    detail.setSubComponentList(subStatuses);
    if (!isSystemInService()) {
      detail.setHealth(HealthStatus.OUT_OF_SERVICE);
    } else {
      detail.setHealth(getHealthStatus(monitorRegistry.getStatusAggregator().getStatus()));
    }
    return detail;
  }

  private HealthStatus getHealthStatus(Status status) {
    switch (status) {
      case OK:
      case WARN:
      case FAIL:
        return HealthStatus.valueOf(status.name());
    }
    throw new IllegalArgumentException("Cannot convert Status." + status + " to a HealthStatus");
  }

  @ManagedAttribute
  public boolean isSystemInService() {
    for (Monitor m : monitorRegistry.getMonitorSet()) {
      if (m instanceof InOutServiceMonitor) {
        return ((InOutServiceMonitor) m).isInService();
      }
    }
    return true;
  }

  @ManagedAttribute
  public boolean isSystemHealthy() {
    try {
      HealthStatus status =
          getDetailedHealthStatus(null, DefaultTimeConstraints.NO_CONSTRAINTS).getHealth();
      return status == HealthStatus.OK || status == HealthStatus.WARN;

    } catch (HealthException e) {
      return false;
    }
  }
}