Example #1
0
  @Override
  public void handleMessage(final Message message) throws Fault {
    if (isResponseAlreadyHandled(message)) {
      return;
    }
    final MessageContentsList objs = MessageContentsList.getContentsList(message);
    if (objs == null || objs.isEmpty()) {
      return;
    }

    final Object responseObj = objs.get(0);
    if (Response.class.isInstance(responseObj)) {
      final Response response = Response.class.cast(responseObj);
      if (is404(message, response)) {
        switchResponse(message);
      }
    } else {
      final Object exchangeStatus = message.getExchange().get(Message.RESPONSE_CODE);
      final int status =
          exchangeStatus != null ? Integer.class.cast(exchangeStatus) : HttpsURLConnection.HTTP_OK;
      if (status == HttpsURLConnection.HTTP_NOT_FOUND) {
        switchResponse(message);
      }
    }
  }
Example #2
0
  private void processResponse(ServerProviderFactory providerFactory, Message message) {

    if (isResponseAlreadyHandled(message)) {
      return;
    }
    MessageContentsList objs = MessageContentsList.getContentsList(message);
    if (objs == null || objs.size() == 0) {
      return;
    }

    Object responseObj = objs.get(0);

    Response response = null;
    if (responseObj instanceof Response) {
      response = (Response) responseObj;
      if (response.getStatus() == 500
          && message.getExchange().get(JAXRSUtils.EXCEPTION_FROM_MAPPER) != null) {
        message.put(Message.RESPONSE_CODE, 500);
        return;
      }
    } else {
      int status = getStatus(message, responseObj != null ? 200 : 204);
      response = JAXRSUtils.toResponseBuilder(status).entity(responseObj).build();
    }

    Exchange exchange = message.getExchange();
    OperationResourceInfo ori =
        (OperationResourceInfo) exchange.get(OperationResourceInfo.class.getName());

    serializeMessage(providerFactory, message, response, ori, true);
  }
  private void doFromSoapMessage(Message message, Object sm) {
    SOAPMessage m = (SOAPMessage) sm;
    MessageContentsList list = (MessageContentsList) message.getContent(List.class);
    if (list == null) {
      list = new MessageContentsList();
      message.setContent(List.class, list);
    }
    Object o = m;

    if (StreamSource.class.isAssignableFrom(type)) {
      try {
        try (CachedOutputStream out = new CachedOutputStream()) {
          XMLStreamWriter xsw = StaxUtils.createXMLStreamWriter(out);
          StaxUtils.copy(new DOMSource(m.getSOAPPart()), xsw);
          xsw.close();
          o = new StreamSource(out.getInputStream());
        }
      } catch (Exception e) {
        throw new Fault(e);
      }
    } else if (SAXSource.class.isAssignableFrom(type)) {
      o = new StaxSource(new W3CDOMStreamReader(m.getSOAPPart()));
    } else if (Source.class.isAssignableFrom(type)) {
      o = new DOMSource(m.getSOAPPart());
    }
    list.set(0, o);
  }
 private void doDataSource(final Message message) {
   MessageContentsList list = (MessageContentsList) message.getContent(List.class);
   // reconstitute all the parts into a Mime data source
   if (message.getAttachments() != null
       && !message.getAttachments().isEmpty()
       && list != null
       && !list.isEmpty()
       && list.get(0) instanceof DataSource) {
     list.set(0, new MultiPartDataSource(message, (DataSource) list.get(0)));
   }
 }
  public void handleMessage(Message message) {
    try {
      NSStack nsStack = new NSStack();
      nsStack.push();

      BindingOperationInfo operation =
          (BindingOperationInfo) message.getExchange().get(BindingOperationInfo.class.getName());

      assert operation.getName() != null;

      XMLStreamWriter xmlWriter = getXMLStreamWriter(message);

      List<MessagePartInfo> parts = null;

      if (!isRequestor(message)) {
        parts = operation.getOutput().getMessageParts();
        addOperationNode(nsStack, message, xmlWriter, true, operation);
      } else {
        parts = operation.getInput().getMessageParts();
        addOperationNode(nsStack, message, xmlWriter, false, operation);
      }

      MessageContentsList objs = MessageContentsList.getContentsList(message);
      if (objs == null) {
        return;
      }

      for (MessagePartInfo part : parts) {
        if (objs.hasValue(part)) {
          Object o = objs.get(part);
          if (o == null) {
            // WSI-BP R2211 - RPC/Lit parts are not allowed to be xsi:nil
            throw new Fault(
                new org.apache.cxf.common.i18n.Message(
                    "BP_2211_RPCLIT_CANNOT_BE_NULL", LOG, part.getConcreteName()));
          }
          // WSI-BP R2737  -RPC/LIG part name space is empty
          // part.setConcreteName(new QName("", part.getConcreteName().getLocalPart()));
        }
      }
      writeParts(message, message.getExchange(), operation, objs, parts);

      // Finishing the writing.
      xmlWriter.writeEndElement();
    } catch (XMLStreamException e) {
      throw new Fault(e);
    }
  }
Example #6
0
    public void handleMessage(Message outMessage) throws Fault {

      MessageContentsList objs = MessageContentsList.getContentsList(outMessage);
      if (objs == null || objs.size() == 0) {
        return;
      }

      OutputStream os = outMessage.getContent(OutputStream.class);
      if (os == null) {
        XMLStreamWriter writer = outMessage.getContent(XMLStreamWriter.class);
        if (writer == null) {
          return;
        }
      }

      Object body = objs.get(0);
      Annotation[] customAnns = (Annotation[]) outMessage.get(Annotation.class.getName());
      Type t = outMessage.get(Type.class);
      doWriteBody(outMessage, body, t, customAnns, os);
    }
Example #7
0
  protected MessageContentsList getResponsePayloadList(
      org.apache.cxf.message.Exchange exchange, List<Source> elements) {
    BindingOperationInfo boi = exchange.getBindingOperationInfo();

    if (boi.isUnwrapped()) {
      boi = boi.getWrappedOperation();
      exchange.put(BindingOperationInfo.class, boi);
    }

    MessageContentsList answer = new MessageContentsList();

    int i = 0;
    if (boi.getOutput() != null) {
      for (MessagePartInfo partInfo : boi.getOutput().getMessageParts()) {
        if (elements != null && elements.size() > i) {
          answer.put(partInfo, elements.get(i++));
        }
      }
    }

    return answer;
  }
  public MediationMessage createMessage(CamelMediationMessage message) {

    // Get HTTP Exchange from SPML Exchange
    CamelMediationExchange spmlR2exchange = message.getExchange();
    Exchange exchange = spmlR2exchange.getExchange();

    logger.debug("Create Message Body from exchange " + exchange.getClass().getName());

    // Converting from CXF Message to SPML Message
    // Is this a CXF message?
    Message in = exchange.getIn();

    if (in.getBody() instanceof MessageContentsList) {

      MessageContentsList mclIn = (MessageContentsList) in.getBody();
      logger.debug("Using CXF Message Content : " + mclIn.get(0));

      MediationMessage body;
      LocalState lState = null;
      MediationState state = null;

      /*
      if (mclIn.get(0) instanceof RequestType) {
          // Process Saml Request in SOAP Channel
          // Try to restore provider state based on sessionIndex
          RequestType samlReq = (RequestType) mclIn.get(0);
          try {

              Method getSessionIndex = samlReq.getClass().getMethod("getSessionIndex");
              List<String> sessionIndexes = (List<String>) getSessionIndex.invoke(samlReq);

              if (sessionIndexes != null) {
                  if (sessionIndexes.size() > 0) {
                      // TODO : Right now we support only one session index!
                      String sessionIndex = sessionIndexes.get(0);

                      ProviderStateContext ctx = createProviderStateContext();
                      lState = ctx.retrieve("idpSsoSessionId", sessionIndex);

                      if (logger.isDebugEnabled())
                          logger.debug("Local state was" + (lState == null ? " NOT" : "") + " retrieved for ssoSessionId " + sessionIndex);
                  }
              }

          } catch (NoSuchMethodException e) {
              // Ignore this ...
              if (logger.isTraceEnabled())
                  logger.trace("SAML Request does not have session index : " + e.getMessage());

          } catch (InvocationTargetException e) {
              logger.error("Cannot recover local state : " + e.getMessage(), e);
          } catch (IllegalAccessException e) {
              logger.error("Cannot recover local state : " + e.getMessage(), e);
          }

      }

      if (lState == null) {
          // Create a new local state instance ?
          state = createMediationState(exchange);
      } else {
          state = new MediationStateImpl(lState);

      } */

      // Process Saml Response in SOAP Channel
      body = new MediationMessageImpl(in.getMessageId(), mclIn.get(0), null, null, null, state);

      return body;

    } else {
      throw new IllegalArgumentException("Unknown message type " + in.getBody());
    }
  }
  @Override
  public void handleMessage(Message message) throws Fault {

    if (checkETagSkipList(
        message.get(Message.PATH_INFO).toString(),
        message.get(Message.HTTP_REQUEST_METHOD).toString())) {
      log.info("Skipping ETagInInterceptor for URI : " + message.get(Message.PATH_INFO).toString());
      return;
    }

    OperationResourceInfo operationResource =
        message.getExchange().get(OperationResourceInfo.class);
    Map<String, List<String>> headers = CastUtils.cast((Map) message.get(Message.PROTOCOL_HEADERS));
    List<Object> arguments = MessageContentsList.getContentsList(message);
    try {
      Class aClass =
          Class.forName(operationResource.getMethodToInvoke().getDeclaringClass().getName());
      Method aClassMethod =
          aClass.getMethod(
              operationResource.getMethodToInvoke().getName() + RestApiConstants.GET_LAST_UPDATED,
              operationResource.getMethodToInvoke().getParameterTypes());
      Object o = aClass.newInstance();
      String lastUpdatedTime = String.valueOf(aClassMethod.invoke(o, arguments.toArray()));
      if (message.get(Message.HTTP_REQUEST_METHOD).equals(RestApiConstants.GET)) {
        if (!Objects.equals(lastUpdatedTime, "null")) {
          String eTag = ETagGenerator.getETag(lastUpdatedTime);
          if (headers.containsKey(HttpHeaders.IF_NONE_MATCH)) {
            String headerValue = headers.get(HttpHeaders.IF_NONE_MATCH).get(0);
            if (Objects.equals(eTag, headerValue)) {
              Response response = Response.notModified(eTag).build();
              message.getExchange().put(Response.class, response);
              return;
            }
          }
          message.getExchange().put(RestApiConstants.ETAG, eTag);
        }
      }
      /*
      If the request method is a PUT or a DELETE and the If-Match header is given then the ETag value for the
      resource and the header value will be compared and if they do not match then the flow will be terminated
      with 412 PRECONDITION FAILED
       */
      if (((RestApiConstants.PUT.equals(message.get(Message.HTTP_REQUEST_METHOD))
              || RestApiConstants.DELETE.equals(message.get(Message.HTTP_REQUEST_METHOD))))
          && headers.containsKey(HttpHeaders.IF_MATCH)) {
        String ifMatchHeaderValue;
        ifMatchHeaderValue = String.valueOf(headers.get(HttpHeaders.IF_MATCH).get(0));
        if (!Objects.equals(lastUpdatedTime, "null")) {
          String eTag = ETagGenerator.getETag(lastUpdatedTime);
          if (!Objects.equals(ifMatchHeaderValue, eTag)) {
            Response response = Response.status(Response.Status.PRECONDITION_FAILED).build();
            message.getExchange().put(Response.class, response);
          }
        }
      }
    } catch (ClassNotFoundException
        | NoSuchMethodException
        | IllegalAccessException
        | InvocationTargetException
        | InstantiationException e) {
      if (log.isDebugEnabled()) {
        log.debug(
            " Error while retrieving the ETag Resource timestamps due to " + e.getMessage(), e);
      }
    }
  }
  @Override
  protected void writeParts(
      Message message,
      Exchange exchange,
      BindingOperationInfo operation,
      MessageContentsList objs,
      List<MessagePartInfo> parts) {
    // TODO Auto-generated method stub
    OutputStream out = message.getContent(OutputStream.class);
    XMLStreamWriter origXmlWriter = message.getContent(XMLStreamWriter.class);
    Service service = exchange.getService();
    XMLStreamWriter xmlWriter = origXmlWriter;
    CachingXmlEventWriter cache = null;

    Object en = message.getContextualProperty(OUT_BUFFERING);
    boolean allowBuffer = true;
    boolean buffer = false;
    if (en != null) {
      buffer = Boolean.TRUE.equals(en) || "true".equals(en);
      allowBuffer = !(Boolean.FALSE.equals(en) || "false".equals(en));
    }
    // need to cache the events in case validation fails or buffering is enabled
    if (buffer || (allowBuffer && shouldValidate(message) && !isRequestor(message))) {
      cache = new CachingXmlEventWriter();
      try {
        cache.setNamespaceContext(origXmlWriter.getNamespaceContext());
      } catch (XMLStreamException e) {
        // ignorable, will just get extra namespace decls
      }
      xmlWriter = cache;
      out = null;
    }

    if (out != null
        && writeToOutputStream(message, operation.getBinding(), service)
        && !MessageUtils.isTrue(message.getContextualProperty(DISABLE_OUTPUTSTREAM_OPTIMIZATION))) {
      if (xmlWriter != null) {
        try {
          xmlWriter.writeCharacters("");
          xmlWriter.flush();
        } catch (XMLStreamException e) {
          throw new Fault(e);
        }
      }

      DataWriter<OutputStream> osWriter = getDataWriter(message, service, OutputStream.class);

      for (MessagePartInfo part : parts) {
        if (objs.hasValue(part)) {
          Object o = objs.get(part);
          osWriter.write(o, part, out);
        }
      }
    } else {
      DataWriter<XMLStreamWriter> dataWriter = new CustomDataWriter(prismContext);

      for (MessagePartInfo part : parts) {
        if (objs.hasValue(part)) {
          Object o = objs.get(part);
          dataWriter.write(o, part, xmlWriter);
        }
      }
    }
    if (cache != null) {
      try {
        for (XMLEvent event : cache.getEvents()) {
          StaxUtils.writeEvent(event, origXmlWriter);
        }
      } catch (XMLStreamException e) {
        throw new Fault(e);
      }
    }
  }
Example #11
0
  protected static List<Source> getPayloadBodyElements(Message message, Map<String, String> nsMap) {
    // take the namespace attribute from soap envelop
    Map<String, String> bodyNC = CastUtils.cast((Map<?, ?>) message.get("soap.body.ns.context"));
    if (bodyNC != null) {
      // if there is no Node and the addNamespaceContext option is enabled, this map is available
      nsMap.putAll(bodyNC);
    } else {
      Document soapEnv = (Document) message.getContent(Node.class);
      if (soapEnv != null) {
        NamedNodeMap attrs = soapEnv.getFirstChild().getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
          Node node = attrs.item(i);
          if (!node.getNodeValue().equals(Soap11.SOAP_NAMESPACE)
              && !node.getNodeValue().equals(Soap12.SOAP_NAMESPACE)) {
            nsMap.put(node.getLocalName(), node.getNodeValue());
          }
        }
      }
    }
    MessageContentsList inObjects = MessageContentsList.getContentsList(message);
    if (inObjects == null) {
      return new ArrayList<Source>(0);
    }
    org.apache.cxf.message.Exchange exchange = message.getExchange();
    BindingOperationInfo boi = exchange.getBindingOperationInfo();

    OperationInfo op = boi.getOperationInfo();

    if (boi.isUnwrapped()) {
      op = boi.getWrappedOperation().getOperationInfo();
    }

    List<MessagePartInfo> partInfos = null;
    boolean client = Boolean.TRUE.equals(message.get(Message.REQUESTOR_ROLE));
    if (client) {
      // it is a response
      partInfos = op.getOutput().getMessageParts();

    } else {
      // it is a request
      partInfos = op.getInput().getMessageParts();
    }

    List<Source> answer = new ArrayList<Source>();

    for (MessagePartInfo partInfo : partInfos) {
      if (!inObjects.hasValue(partInfo)) {
        continue;
      }

      Object part = inObjects.get(partInfo);

      if (part instanceof Holder) {
        part = ((Holder<?>) part).value;
      }

      if (part instanceof Source) {
        Element element = null;
        if (part instanceof DOMSource) {
          element = getFirstElement(((DOMSource) part).getNode());
        }

        if (element != null) {
          addNamespace(element, nsMap);
          answer.add(new DOMSource(element));
        } else {
          answer.add((Source) part);
        }

        if (LOG.isTraceEnabled()) {
          LOG.trace("Extract body element {}", element == null ? "null" : getXMLString(element));
        }
      } else if (part instanceof Element) {
        addNamespace((Element) part, nsMap);
        answer.add(new DOMSource((Element) part));
      } else {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Unhandled part type '{}'", part.getClass());
        }
      }
    }

    return answer;
  }