@Test
  public void testInterceptMessageConstruction() throws Exception {
    MessageConstructionInterceptor interceptor =
        new AbstractMessageConstructionInterceptor() {
          @Override
          public boolean supportsMessageType(String messageType) {
            return MessageType.XML.toString().equalsIgnoreCase(messageType);
          }

          @Override
          protected Message interceptMessage(
              Message message, String messageType, TestContext context) {
            return new DefaultMessage("Intercepted!");
          }

          @Override
          protected String getName() {
            return "MockInterceptor";
          }
        };

    Message in = new DefaultMessage("Hello Citrus!");
    Message intercepted =
        interceptor.interceptMessageConstruction(in, MessageType.XML.toString(), context);
    Assert.assertEquals(intercepted.getPayload(String.class), "Intercepted!");

    intercepted =
        interceptor.interceptMessageConstruction(in, MessageType.PLAINTEXT.toString(), context);
    Assert.assertEquals(intercepted.getPayload(String.class), "Hello Citrus!");
  }
Exemplo n.º 2
0
 // -----------------------------------------------------------
 public static GetFileReturnType getFileResponse(Socket s) throws GenericException {
   // GOELogger log = new GOELogger("/home/arbab/storageLogs/ws.log");
   // System.out.println("INITIALIZED THE LOGGER");
   GetFileReturnType r = new GetFileReturnType();
   Message m = Message.receive(s);
   byte[] payload;
   // IP
   if (m.getMessageType() != MessageType.GET_FILE_RSP)
     throw new GenericException("Error, received invalid type: " + m.getMessageType());
   else payload = m.getPayload();
   r.IP = payload.toString();
   System.out.println("IP: " + r.IP);
   // Port
   m = new Message(MessageType.SEND_NEXT_PARAM);
   try {
     m.send(s);
   } catch (IOException e) {
     throw new GenericException("error " + e);
   }
   m = Message.receive(s);
   if (m.getMessageType() != MessageType.NEXT_PARAM_RQT) {
     throw new GenericException("Error, received invalid type: " + m.getMessageType());
   } else {
     payload = m.getPayload();
     r.Port = (payload[0] << 8) + payload[1];
   }
   // tid
   m = new Message(MessageType.SEND_NEXT_PARAM);
   try {
     m.send(s);
   } catch (IOException e) {
     throw new GenericException("error " + e);
   }
   m = Message.receive(s);
   if (m.getMessageType() != MessageType.NEXT_PARAM_RQT) {
     throw new GenericException("Error, received invalid type: " + m.getMessageType());
   } else {
     payload = m.getPayload();
     // r.tid = (long)(payload[0] << 24) + (long)(payload[1] << 16) +
     // (long)(payload[2] << 8) + (long)payload[3];
     // log.write("%%%%%% " + (long)payload[0] + " " + (long)payload[1] + " " +
     // (long)payload[2] + " " + (long)payload[3] + "\n", false);
     // log.write( (0x000000FF & ((long)payload[0])) + "\n",false);
     // log.write( (0x000000FF & ((long)payload[1])) + "\n",false);
     // log.write( (0x000000FF & ((long)payload[2])) + "\n",false);
     // log.write( (0x000000FF & ((long)payload[3])) + "\n",false);
     r.tid =
         (0x000000FF & ((long) payload[0] << 24))
             + (0x000000FF & ((long) payload[1] << 16))
             + (0x000000FF & ((long) payload[2] << 8))
             + (0x000000FF & ((long) payload[3]));
   }
   return r;
 }
Exemplo n.º 3
0
  @Override
  public void validateMessagePayload(
      Message receivedMessage,
      Message controlMessage,
      XmlMessageValidationContext validationContext,
      TestContext context)
      throws ValidationException {
    log.info("Start XML message validation");

    try {
      if (validationContext.isSchemaValidationEnabled()) {
        validateXMLSchema(receivedMessage, validationContext);
        validateDTD(validationContext.getDTDResource(), receivedMessage);
      }

      validateNamespaces(validationContext.getControlNamespaces(), receivedMessage);
      validateMessageContent(receivedMessage, controlMessage, validationContext, context);

      if (controlMessage != null) {
        Assert.isTrue(
            controlMessage.getHeaderData().size() <= receivedMessage.getHeaderData().size(),
            "Failed to validate header data XML fragments - found "
                + receivedMessage.getHeaderData().size()
                + " header fragments, expected "
                + controlMessage.getHeaderData().size());

        for (int i = 0; i < controlMessage.getHeaderData().size(); i++) {
          validateXmlHeaderFragment(
              receivedMessage.getHeaderData().get(i),
              controlMessage.getHeaderData().get(i),
              validationContext,
              context);
        }
      }

      log.info("XML message validation successful: All values OK");
    } catch (ClassCastException e) {
      throw new CitrusRuntimeException(e);
    } catch (DOMException e) {
      throw new CitrusRuntimeException(e);
    } catch (LSException e) {
      throw new CitrusRuntimeException(e);
    } catch (IllegalArgumentException e) {
      log.error(
          "Failed to validate:\n" + XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));
      throw new ValidationException("Validation failed:", e);
    } catch (ValidationException ex) {
      log.error(
          "Failed to validate:\n" + XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));
      throw ex;
    }
  }
Exemplo n.º 4
0
 void deliverIncomingMessage(final Message message) {
   long mid = message.getMessageId();
   long rmid = message.getRequestMessageId();
   Object payload = null;
   Exception exception = null;
   if (message.getFlag() == Message.ERROR) {
     exception = (Exception) message.getPayload();
     exception.printStackTrace();
   } else {
     payload = message.getPayload();
   }
   ipci.deliverIncomingMessage(message.getIPCHandle(), mid, rmid, payload, exception);
 }
Exemplo n.º 5
0
 public void send(Message message) {
   boolean rc;
   rc = sock.sendMore(message.getHeader());
   if (!rc) assert (false);
   rc = sock.send(message.getPayload());
   if (!rc) assert (false);
 }
Exemplo n.º 6
0
 // -----------------------------------------------------------
 // --------------------HANDSHAKING FUNCTIONS------------------
 public static byte[] transactionAddedResponse(Socket s) throws GenericException {
   Message m = Message.receive(s);
   if (m.getMessageType() == MessageType.TRANS_ADDED_RSP) {
     System.out.println(m.getPayload().toString());
     // long tid = (long)(m.getPayload()[0]<<24) +
     // (long)(m.getPayload()[1]<<16) + (long)(m.getPayload()[2]<<8) +
     // (long)(m.getPayload()[3]);
     // if(m.getPayload().length > 4) {
     // }
     // return tid;
     return m.getPayload();
   } else {
     System.out.println(
         "Error, got "
             + m.getMessageType()
             + " when "
             + MessageType.TRANS_ADDED_RSP
             + " was expected.");
     throw new GenericException(m.getMessageType().getDescription());
   }
 }
Exemplo n.º 7
0
 // -----------------------------------------------------------
 public static listFilesRequestType listFilesResponse(Socket s) throws GenericException {
   byte[] payload;
   int numFiles;
   Message m = Message.receive(s);
   if (m.getMessageType() != MessageType.LIST_FILES_RSP)
     throw new GenericException("Error, received invalid type: " + m.getMessageType());
   else {
     payload = m.getPayload();
     numFiles = (payload[0] << 24) + (payload[1] << 16) + (payload[2] << 8) + payload[3];
   }
   System.out.println(numFiles + " files to be received");
   listFilesRequestType fileList = new listFilesRequestType(numFiles);
   for (int i = 0; i < numFiles; i++) {
     // m.setMessageType(MessageType.SEND_NEXT_PARAM);
     m = new Message(MessageType.SEND_NEXT_PARAM);
     try {
       m.send(s);
     } catch (IOException e) {
       throw new GenericException("error " + e);
     }
     m = Message.receive(s);
     if (m.getMessageType() != MessageType.FILE_NAME_RQT
         && m.getMessageType() != MessageType.DIR_NAME_RQT) {
       throw new GenericException("Error, received invalid type: " + m.getMessageType());
     } else {
       payload = m.getPayload();
       fileList.name[i] = byteArrayToString(payload);
       if (m.getMessageType() == MessageType.FILE_NAME_RQT) {
         fileList.isDir[i] = false;
         System.out.println("File: " + fileList.name[i]);
       } else {
         fileList.isDir[i] = true;
         System.out.println("Directory: " + fileList.name[i]);
       }
     }
   } // end for
   return (fileList);
 }
Exemplo n.º 8
0
  /**
   * Validate message payloads by comparing to a control message.
   *
   * @param receivedMessage
   * @param validationContext
   * @param context
   */
  protected void validateMessageContent(
      Message receivedMessage,
      Message controlMessage,
      XmlMessageValidationContext validationContext,
      TestContext context) {
    if (controlMessage == null || controlMessage.getPayload() == null) {
      log.info("Skip message payload validation as no control message was defined");
      return;
    }

    if (!(controlMessage.getPayload() instanceof String)) {
      throw new IllegalArgumentException(
          "DomXmlMessageValidator does only support message payload of type String, "
              + "but was "
              + controlMessage.getPayload().getClass());
    }

    String controlMessagePayload = controlMessage.getPayload(String.class);

    if (receivedMessage.getPayload() == null
        || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {
      Assert.isTrue(
          !StringUtils.hasText(controlMessagePayload),
          "Unable to validate message payload - received message payload was empty, control message payload is not");
      return;
    } else if (!StringUtils.hasText(controlMessagePayload)) {
      return;
    }

    log.info("Start XML tree validation ...");

    Document received = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));
    Document source = XMLUtils.parseMessagePayload(controlMessagePayload);

    XMLUtils.stripWhitespaceNodes(received);
    XMLUtils.stripWhitespaceNodes(source);

    if (log.isDebugEnabled()) {
      log.debug("Received message:\n" + XMLUtils.serialize(received));
      log.debug("Control message:\n" + XMLUtils.serialize(source));
    }

    validateXmlTree(
        received,
        source,
        validationContext,
        namespaceContextBuilder.buildContext(receivedMessage, validationContext.getNamespaces()),
        context);
  }
Exemplo n.º 9
0
 // ------------------------------------------------------------
 private boolean respondToDatagram(
     DatagramPacket receivePacket,
     ServerDescription[] validServers,
     boolean addToFile,
     int expectedServers)
     throws IOException {
   boolean serverAdded = false;
   StorageServer serv = new StorageServer();
   try {
     if (receivePacket.getData()[0] == MessageType.ADD_SERV_RQT.getType()) {
       extractPacketData(serv, receivePacket);
       int servNo = findServer(validServers, serv.IP, serv.port);
       int index = servAlreadyConnected(serv);
       /*
        * if(expectedServers == 0) { Message m = new
        * Message(MessageType.COPY_FILE_RQT); m.send(serv.sock); return(false);
        * } else if(expectedServers == 1) { Message m = new
        * Message(MessageType.COPY_FILE_RSP); m.send(serv.sock); return(false);
        * } else if(expectedServers == 2) { Message m = new
        * Message(MessageType.DELETE_DIR_RQT); m.send(serv.sock);
        * return(false); } else { Message m = new
        * Message(MessageType.DELETE_DIR_RSP); m.send(serv.sock); }
        * if(expectedServers > 2) { return false; }
        */
       if (servNo > 0 || addToFile) {
         if (index >= 0) {
           System.out.println("Reconnection of a server, removing stale values");
           serverList.remove(index);
         }
         Message m = new Message(MessageType.SEND_NEXT_PARAM);
         m.send(serv.sock);
         m = Message.receive(serv.sock);
         if (m.getMessageType() != MessageType.NEXT_PARAM_RQT) {
           m = new Message(MessageType.ERR_UNEXPECTED_CLT);
           m.send(serv.sock);
           return (false);
         } else {
           byte[] payload = new byte[2];
           payload = m.getPayload();
           serv.httpPort = payload[0] & 0xff;
           serv.httpPort <<= 8;
           serv.httpPort += payload[1] & 0xff;
           if (servNo > 0) {
             serv.servNo = servNo;
           }
           if (servNo < 0) {
             try {
               validServers[expectedServers].IP = ServerDescription.IPStrToByteArr(serv.IP);
               validServers[expectedServers].port = serv.port;
               validServers[expectedServers].serverNumber = findMinUnusedServNum(validServers);
               serv.servNo = validServers[expectedServers].serverNumber;
               addToFile(serv, validServers[expectedServers].serverNumber);
               serverAdded = true;
             } catch (GenericException e) {
               m = new Message(MessageType.ERR_UNEXPECTED_CLT);
               m.send(serv.sock);
               return (false);
             }
           }
           // By default, external IP = internal IP
           serv.externalName = serv.IP;
           Iterator itr = ipPairs.iterator();
           // if we find an external IP that is associated with the
           // internal IP for this server, change the external IP
           // address for this server to match
           while (itr.hasNext()) {
             String[] pair = (String[]) itr.next();
             // mylog.write("pair[0]: " + pair[0] + "servIP: " + serv.IP +
             // "\n", true);
             if (pair[0].equals(serv.IP)) {
               // mylog.write("found ext int match\n", true);
               serv.externalName = pair[1];
               /*
                * Runtime runtime = Runtime.getRuntime(); String[] args = new
                * String[]{"sh", "-c", "ssh -f -i " + keyfile + " root@" + gwIP
                * + " \"perl stoptcppr.pl " + serv.externalIP + "\""}; Process
                * proc = runtime.exec(args); args = new String[]{"sh", "-c",
                * "ssh -f -i " + keyfile + " root@" + gwIP +
                * " \"perl tcppr.pl " + serv.externalIP + " " + serv.IP +
                * "\""}; proc = runtime.exec(args);
                */
               break;
             }
           }
           serverList.add(serv);
           m = new Message(MessageType.ADD_SERV_RSP);
           payload[0] = (byte) ((servNo >> 8) & 0xff);
           payload[1] = (byte) (servNo & 0xff);
           m.addPayload(payload);
           m.send(serv.sock);
         }
       } else {
         Message m = new Message(MessageType.ERR_UNEXPECTED_CLT);
         m.send(serv.sock);
       }
     }
     return (serverAdded);
   } catch (IOException e) {
     Message m = new Message(MessageType.INTERNAL_SERVER_ERR);
     m.send(serv.sock);
     throw new IOException(e);
   } catch (GenericException e) {
     Message m = new Message(MessageType.INTERNAL_SERVER_ERR);
     m.send(serv.sock);
     throw new IOException(e.getMessage());
   }
 }
Exemplo n.º 10
0
 public AbstractMessage(Message message) {
   this(message.getDescriptor(), message.getArguments());
   this.messagePayload = message.getPayload();
 }
Exemplo n.º 11
0
  /**
   * Validate namespaces in message. The method compares namespace declarations in the root element
   * of the received message to expected namespaces. Prefixes are important too, so differing
   * namespace prefixes will fail the validation.
   *
   * @param expectedNamespaces
   * @param receivedMessage
   */
  protected void validateNamespaces(
      Map<String, String> expectedNamespaces, Message receivedMessage) {
    if (CollectionUtils.isEmpty(expectedNamespaces)) {
      return;
    }

    if (receivedMessage.getPayload() == null
        || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {
      throw new ValidationException(
          "Unable to validate message namespaces - receive message payload was empty");
    }

    log.info("Start XML namespace validation");

    Document received = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));

    Map<String, String> foundNamespaces =
        XMLUtils.lookupNamespaces(receivedMessage.getPayload(String.class));

    if (foundNamespaces.size() != expectedNamespaces.size()) {
      throw new ValidationException(
          "Number of namespace declarations not equal for node "
              + XMLUtils.getNodesPathName(received.getFirstChild())
              + " found "
              + foundNamespaces.size()
              + " expected "
              + expectedNamespaces.size());
    }

    for (Entry<String, String> entry : expectedNamespaces.entrySet()) {
      String namespace = entry.getKey();
      String url = entry.getValue();

      if (foundNamespaces.containsKey(namespace)) {
        if (!foundNamespaces.get(namespace).equals(url)) {
          throw new ValidationException(
              "Namespace '"
                  + namespace
                  + "' values not equal: found '"
                  + foundNamespaces.get(namespace)
                  + "' expected '"
                  + url
                  + "' in reference node "
                  + XMLUtils.getNodesPathName(received.getFirstChild()));
        } else {
          log.info(
              "Validating namespace " + namespace + " value as expected " + url + " - value OK");
        }
      } else {
        throw new ValidationException(
            "Missing namespace "
                + namespace
                + "("
                + url
                + ") in node "
                + XMLUtils.getNodesPathName(received.getFirstChild()));
      }
    }

    log.info("XML namespace validation finished successfully: All values OK");
  }
Exemplo n.º 12
0
  /**
   * Validate message with a XML schema.
   *
   * @param receivedMessage
   * @param validationContext
   */
  protected void validateXMLSchema(
      Message receivedMessage, XmlMessageValidationContext validationContext) {
    if (receivedMessage.getPayload() == null
        || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {
      return;
    }

    try {
      Document doc = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));

      if (!StringUtils.hasText(doc.getFirstChild().getNamespaceURI())) {
        return;
      }

      log.info("Starting XML schema validation ...");

      XmlValidator validator = null;
      XsdSchemaRepository schemaRepository = null;
      if (validationContext.getSchema() != null) {
        validator =
            applicationContext
                .getBean(validationContext.getSchema(), XsdSchema.class)
                .createValidator();
      } else if (validationContext.getSchemaRepository() != null) {
        schemaRepository =
            applicationContext.getBean(
                validationContext.getSchemaRepository(), XsdSchemaRepository.class);
      } else if (schemaRepositories.size() == 1) {
        schemaRepository = schemaRepositories.get(0);
      } else if (schemaRepositories.size() > 0) {
        for (XsdSchemaRepository repository : schemaRepositories) {
          if (repository.canValidate(doc)) {
            schemaRepository = repository;
          }
        }

        if (schemaRepository == null) {
          throw new CitrusRuntimeException(
              String.format(
                  "Failed to find proper schema repository in Spring bean context for validating element '%s(%s)'",
                  doc.getFirstChild().getLocalName(), doc.getFirstChild().getNamespaceURI()));
        }
      } else {
        log.warn(
            "Neither schema instance nor schema repository defined - skipping XML schema validation");
        return;
      }

      if (schemaRepository != null) {
        if (!schemaRepository.canValidate(doc)) {
          throw new CitrusRuntimeException(
              String.format(
                  "Unable to find proper XML schema definition for element '%s(%s)' in schema repository '%s'",
                  doc.getFirstChild().getLocalName(),
                  doc.getFirstChild().getNamespaceURI(),
                  schemaRepository.getName()));
        }

        List<Resource> schemas = new ArrayList<>();
        for (XsdSchema xsdSchema : schemaRepository.getSchemas()) {
          if (xsdSchema instanceof XsdSchemaCollection) {
            for (Resource resource : ((XsdSchemaCollection) xsdSchema).getSchemaResources()) {
              schemas.add(resource);
            }
          } else if (xsdSchema instanceof WsdlXsdSchema) {
            for (Resource resource : ((WsdlXsdSchema) xsdSchema).getSchemaResources()) {
              schemas.add(resource);
            }
          } else {
            synchronized (transformerFactory) {
              ByteArrayOutputStream bos = new ByteArrayOutputStream();
              try {
                transformerFactory
                    .newTransformer()
                    .transform(xsdSchema.getSource(), new StreamResult(bos));
              } catch (TransformerException e) {
                throw new CitrusRuntimeException(
                    "Failed to read schema " + xsdSchema.getTargetNamespace(), e);
              }
              schemas.add(new ByteArrayResource(bos.toByteArray()));
            }
          }
        }

        validator =
            XmlValidatorFactory.createValidator(
                schemas.toArray(new Resource[schemas.size()]), WsdlXsdSchema.W3C_XML_SCHEMA_NS_URI);
      }

      SAXParseException[] results = validator.validate(new DOMSource(doc));
      if (results.length == 0) {
        log.info("Schema of received XML validated OK");
      } else {
        log.error(
            "Schema validation failed for message:\n"
                + XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));

        // Report all parsing errors
        log.debug("Found " + results.length + " schema validation errors");
        StringBuilder errors = new StringBuilder();
        for (SAXParseException e : results) {
          errors.append(e.toString());
          errors.append("\n");
        }
        log.debug(errors.toString());

        throw new ValidationException("Schema validation failed:", results[0]);
      }
    } catch (IOException e) {
      throw new CitrusRuntimeException(e);
    } catch (SAXException e) {
      throw new CitrusRuntimeException(e);
    }
  }