Esempio n. 1
1
    /**
     * Called for an incoming message.
     *
     * @param inMessage
     */
    public void onMessage(Message inMessage) {
      // disposable exchange, swapped with real Exchange on correlation
      inMessage.setExchange(new ExchangeImpl());
      inMessage.getExchange().put(Bus.class, bus);
      inMessage.put(Message.DECOUPLED_CHANNEL_MESSAGE, Boolean.TRUE);
      inMessage.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_OK);

      // remove server-specific properties
      // inMessage.remove(AbstractHTTPDestination.HTTP_REQUEST);
      // inMessage.remove(AbstractHTTPDestination.HTTP_RESPONSE);
      inMessage.remove(Message.ASYNC_POST_RESPONSE_DISPATCH);
      updateResponseCode(inMessage);

      // cache this inputstream since it's defer to use in case of async
      try {
        InputStream in = inMessage.getContent(InputStream.class);
        if (in != null) {
          CachedOutputStream cos = new CachedOutputStream();
          IOUtils.copy(in, cos);
          inMessage.setContent(InputStream.class, cos.getInputStream());
        }
        observer.onMessage(inMessage);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
Esempio n. 2
0
    public void prepare(final Message message) throws IOException {
      if (!Boolean.TRUE.equals(message.getExchange().get(LocalConduit.DIRECT_DISPATCH))) {
        final Exchange exchange = (Exchange) message.getExchange().get(LocalConduit.IN_EXCHANGE);

        AbstractWrappedOutputStream cout =
            new AbstractWrappedOutputStream() {
              protected void onFirstWrite() throws IOException {
                final PipedInputStream stream = new PipedInputStream();
                wrappedStream = new PipedOutputStream(stream);

                final MessageImpl m = new MessageImpl();
                localDestinationFactory.copy(message, m);
                m.setContent(InputStream.class, stream);

                final Runnable receiver =
                    new Runnable() {
                      public void run() {
                        if (exchange != null) {
                          exchange.setInMessage(m);
                        }
                        conduit.getMessageObserver().onMessage(m);
                      }
                    };

                new Thread(receiver).start();
              }
            };

        message.setContent(OutputStream.class, cout);

      } else {
        CachedOutputStream stream = new CachedOutputStream();
        message.setContent(OutputStream.class, stream);
      }
    }
Esempio n. 3
0
 public void handleMessage(Message message) throws Fault {
   final OutputStream os = message.getContent(OutputStream.class);
   final Writer iowriter = message.getContent(Writer.class);
   if (os == null && iowriter == null) {
     return;
   }
   Logger logger = getMessageLogger(message);
   if (logger.isLoggable(Level.INFO) || writer != null) {
     // Write the output while caching it for the log message
     boolean hasLogged = message.containsKey(LOG_SETUP);
     if (!hasLogged) {
       message.put(LOG_SETUP, Boolean.TRUE);
       if (os != null) {
         final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(os);
         if (threshold > 0) {
           newOut.setThreshold(threshold);
         }
         if (limit > 0) {
           newOut.setCacheLimit(limit);
         }
         message.setContent(OutputStream.class, newOut);
         newOut.registerCallback(new LoggingCallback(logger, message, os));
       } else {
         message.setContent(Writer.class, new LogWriter(logger, message, iowriter));
       }
     }
   }
 }
Esempio n. 4
0
 public void handleMessage(Message message) throws Fault {
   createExchangeId(message);
   final OutputStream os = message.getContent(OutputStream.class);
   if (os != null) {
     LoggingCallback callback = new LoggingCallback(sender, message, os, limit);
     message.setContent(OutputStream.class, createCachingOut(message, os, callback));
   } else {
     final Writer iowriter = message.getContent(Writer.class);
     if (iowriter != null) {
       message.setContent(
           Writer.class, new LogEventSendingWriter(sender, message, iowriter, limit));
     }
   }
 }
 protected void transformOS(Message message, OutputStream out) {
   CachedOutputStream wrapper = new CachedOutputStream();
   CachedOutputStreamCallback callback =
       new XSLTCachedOutputStreamCallback(getXSLTTemplate(), out);
   wrapper.registerCallback(callback);
   message.setContent(OutputStream.class, wrapper);
 }
 protected void transformXWriter(Message message, XMLStreamWriter xWriter) {
   CachedWriter writer = new CachedWriter();
   XMLStreamWriter delegate = StaxUtils.createXMLStreamWriter(writer);
   XSLTStreamWriter wrapper = new XSLTStreamWriter(getXSLTTemplate(), writer, delegate, xWriter);
   message.setContent(XMLStreamWriter.class, wrapper);
   message.put(AbstractOutDatabindingInterceptor.DISABLE_OUTPUTSTREAM_OPTIMIZATION, Boolean.TRUE);
 }
Esempio n. 7
0
  protected void handle(Message message) throws SequenceFault, RMException {
    LOG.entering(getClass().getName(), "handleMessage");
    // This message capturing mechanism will need to be changed at some point.
    // Until then, we keep this interceptor here and utilize the robust
    // option to avoid the unnecessary message capturing/caching.
    if (!MessageUtils.isTrue(message.getContextualProperty(Message.ROBUST_ONEWAY))) {
      InputStream is = message.getContent(InputStream.class);
      if (is != null) {
        CachedOutputStream saved = new CachedOutputStream();
        try {
          IOUtils.copy(is, saved);

          saved.flush();
          is.close();
          saved.lockOutputStream();

          LOG.fine("Capturing the original RM message");
          RewindableInputStream ris = RewindableInputStream.makeRewindable(saved.getInputStream());
          message.setContent(InputStream.class, ris);
          message.put(RMMessageConstants.SAVED_CONTENT, ris);
        } catch (Exception e) {
          throw new Fault(e);
        }
      }
    }
  }
    @Override
    public void onClose(CachedOutputStream cos) {
      long l = LOG.logStart();
      byte[] buf = new byte[1024];
      int len;
      InputStream is;
      try {
        is = cos.getInputStream();
        while ((len = is.read(buf)) > 0) {
          logOutputStream.write(buf, 0, len);
        }
      } catch (IOException ex) {
        LOG.logError(l, ex);
      }
      LoggingMessage buffer = setupBuffer(message, fout);
      LOG.log(buffer.toString());

      try {
        // empty out the cache
        cos.lockOutputStream();
        cos.resetOut(null, false);
      } catch (Exception ex) {
        LOG.logWarn(l, "Error clearing cache: " + ex.getMessage(), null);
      }
      message.setContent(OutputStream.class, origStream);
    }
  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);
  }
Esempio n. 10
0
 private void checkCachedStream(Message m, OutputStream osOriginal, boolean enabled)
     throws Exception {
   XMLStreamWriter writer = null;
   if (enabled) {
     writer = m.getContent(XMLStreamWriter.class);
   } else {
     writer = (XMLStreamWriter) m.get(XMLStreamWriter.class.getName());
   }
   if (writer instanceof CachingXmlEventWriter) {
     CachingXmlEventWriter cache = (CachingXmlEventWriter) writer;
     if (cache.getEvents().size() != 0) {
       XMLStreamWriter origWriter = null;
       try {
         origWriter = StaxUtils.createXMLStreamWriter(osOriginal);
         for (XMLEvent event : cache.getEvents()) {
           StaxUtils.writeEvent(event, origWriter);
         }
       } finally {
         StaxUtils.close(origWriter);
       }
     }
     m.setContent(XMLStreamWriter.class, null);
     return;
   }
   if (enabled) {
     OutputStream os = m.getContent(OutputStream.class);
     if (os != osOriginal && os instanceof CachedOutputStream) {
       CachedOutputStream cos = (CachedOutputStream) os;
       if (cos.size() != 0) {
         cos.writeCacheTo(osOriginal);
       }
     }
   }
 }
Esempio n. 11
0
 protected void doRunInterceptorChain(Message m) {
   try {
     m.getInterceptorChain().doIntercept(m);
   } catch (Exception ex) {
     m.setContent(Exception.class, ex);
   }
 }
    public void prepare(final Message message) throws IOException {
      inMessage.getExchange().setOutMessage(message);
      final ZMQ.Socket zmqSocket = (ZMQ.Socket) inMessage.get("socket");

      Exchange exchange = inMessage.getExchange();
      exchange.setOutMessage(message);

      message.setContent(
          OutputStream.class,
          new ByteArrayOutputStream() {

            @Override
            public void close() throws IOException {
              super.close();
              if (endpointConfig.getSocketType() == ZMQURIConstants.SocketType.REP) {
                getLogger().log(Level.FINE, "send out the message!");
                if (hasNoResponseContent(message)) {
                  ZMQUtils.sendMessage(zmqSocket, new byte[] {0});
                } else {
                  ZMQUtils.sendMessage(zmqSocket, toByteArray());
                }
              }
            }
          });
    }
  @Override
  public void onMessage(byte[] message, ZMQ.Socket zmqSocket) {
    getLogger().log(Level.FINE, "server received request: ", message);

    Message inMessage = new MessageImpl();
    inMessage.setContent(InputStream.class, new ByteArrayInputStream(message));
    ((MessageImpl) inMessage).setDestination(this);
    inMessage.put("socket", zmqSocket);

    incomingObserver.onMessage(inMessage);
  }
Esempio n. 14
0
  protected Message createMessage(
      Object body,
      String httpMethod,
      MultivaluedMap<String, String> headers,
      URI currentURI,
      Exchange exchange,
      Map<String, Object> invocationContext,
      boolean proxy) {
    Message m = cfg.getConduitSelector().getEndpoint().getBinding().createMessage();
    m.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
    m.put(Message.INBOUND_MESSAGE, Boolean.FALSE);

    m.put(Message.HTTP_REQUEST_METHOD, httpMethod);
    m.put(Message.PROTOCOL_HEADERS, headers);
    if (currentURI.isAbsolute() && currentURI.getScheme().startsWith(HTTP_SCHEME)) {
      m.put(Message.ENDPOINT_ADDRESS, currentURI.toString());
    } else {
      m.put(Message.ENDPOINT_ADDRESS, state.getBaseURI().toString());
    }

    Object requestURIProperty = cfg.getRequestContext().get(Message.REQUEST_URI);
    if (requestURIProperty == null) {
      m.put(Message.REQUEST_URI, currentURI.toString());
    } else {
      m.put(Message.REQUEST_URI, requestURIProperty.toString());
    }

    m.put(Message.CONTENT_TYPE, headers.getFirst(HttpHeaders.CONTENT_TYPE));

    body = checkIfBodyEmpty(body);
    setEmptyRequestPropertyIfNeeded(m, body);

    m.setContent(List.class, getContentsList(body));

    m.put(URITemplate.TEMPLATE_PARAMETERS, getState().getTemplates());

    PhaseInterceptorChain chain = setupOutInterceptorChain(cfg);
    chain.setFaultObserver(setupInFaultObserver(cfg));
    m.setInterceptorChain(chain);

    exchange = createExchange(m, exchange);
    exchange.put(Message.REST_MESSAGE, Boolean.TRUE);
    exchange.setOneWay("true".equals(headers.getFirst(Message.ONE_WAY_REQUEST)));
    exchange.put(Retryable.class, new RetryableImpl());

    // context
    setContexts(m, exchange, invocationContext, proxy);

    // setup conduit selector
    prepareConduitSelector(m, currentURI, proxy);

    return m;
  }
Esempio n. 15
0
 private boolean checkBufferingMode(Message m, List<WriterInterceptor> writers, boolean firstTry) {
   if (!firstTry) {
     return false;
   }
   WriterInterceptor last = writers.get(writers.size() - 1);
   MessageBodyWriter<Object> w = ((WriterInterceptorMBW) last).getMBW();
   Object outBuf = m.getContextualProperty(OUT_BUFFERING);
   boolean enabled = MessageUtils.isTrue(outBuf);
   boolean configurableProvider = w instanceof AbstractConfigurableProvider;
   if (!enabled && outBuf == null && configurableProvider) {
     enabled = ((AbstractConfigurableProvider) w).getEnableBuffering();
   }
   if (enabled) {
     boolean streamingOn =
         configurableProvider ? ((AbstractConfigurableProvider) w).getEnableStreaming() : false;
     if (streamingOn) {
       m.setContent(XMLStreamWriter.class, new CachingXmlEventWriter());
     } else {
       m.setContent(OutputStream.class, new CachedOutputStream());
     }
   }
   return enabled;
 }
Esempio n. 16
0
 public void close() throws IOException {
   final LogEvent event = new DefaultLogEventMapper().map(message);
   StringWriter w2 = out2;
   if (w2 == null) {
     w2 = (StringWriter) out;
   }
   String ct = (String) message.get(Message.CONTENT_TYPE);
   StringBuilder payload = new StringBuilder();
   try {
     writePayload(payload, w2, ct);
   } catch (Exception ex) {
     // ignore
   }
   event.setPayload(payload.toString());
   sender.send(event);
   message.setContent(Writer.class, out);
   super.close();
 }
Esempio n. 17
0
    public void onClose(CachedOutputStream cos) {
      LoggingMessage buffer = setupBuffer(message);

      String ct = (String) message.get(Message.CONTENT_TYPE);
      if (!isShowBinaryContent() && isBinaryContent(ct)) {
        buffer.getMessage().append(BINARY_CONTENT_MESSAGE).append('\n');
        log(logger, formatLoggingMessage(buffer));
        return;
      }
      if (!isShowMultipartContent() && isMultipartContent(ct)) {
        buffer.getMessage().append(MULTIPART_CONTENT_MESSAGE).append('\n');
        log(logger, formatLoggingMessage(buffer));
        return;
      }

      if (cos.getTempFile() == null) {
        // buffer.append("Outbound Message:\n");
        if (cos.size() >= lim) {
          buffer.getMessage().append("(message truncated to " + lim + " bytes)\n");
        }
      } else {
        buffer.getMessage().append("Outbound Message (saved to tmp file):\n");
        buffer.getMessage().append("Filename: " + cos.getTempFile().getAbsolutePath() + "\n");
        if (cos.size() >= lim) {
          buffer.getMessage().append("(message truncated to " + lim + " bytes)\n");
        }
      }
      try {
        String encoding = (String) message.get(Message.ENCODING);
        writePayload(buffer.getPayload(), cos, encoding, ct);
      } catch (Exception ex) {
        // ignore
      }

      log(logger, formatLoggingMessage(buffer));
      try {
        // empty out the cache
        cos.lockOutputStream();
        cos.resetOut(null, false);
      } catch (Exception ex) {
        // ignore
      }
      message.setContent(OutputStream.class, origStream);
    }
Esempio n. 18
0
 public void close() throws IOException {
   LoggingMessage buffer = setupBuffer(message);
   if (count >= lim) {
     buffer.getMessage().append("(message truncated to " + lim + " bytes)\n");
   }
   StringWriter w2 = out2;
   if (w2 == null) {
     w2 = (StringWriter) out;
   }
   String ct = (String) message.get(Message.CONTENT_TYPE);
   try {
     writePayload(buffer.getPayload(), w2, ct);
   } catch (Exception ex) {
     // ignore
   }
   log(logger, formatLoggingMessage(buffer));
   message.setContent(Writer.class, out);
   super.close();
 }
Esempio n. 19
0
  private void checkResponse(Method m, Response r, Message inMessage) throws Throwable {
    Throwable t = null;
    int status = r.getStatus();

    if (status >= 300) {
      Class<?>[] exTypes = m.getExceptionTypes();
      if (exTypes.length == 0) {
        exTypes = new Class[] {WebApplicationException.class};
      }
      for (Class<?> exType : exTypes) {
        ResponseExceptionMapper<?> mapper = findExceptionMapper(inMessage, exType);
        if (mapper != null) {
          t = mapper.fromResponse(r);
          if (t != null) {
            throw t;
          }
        }
      }

      if ((t == null)
          && (m.getReturnType() == Response.class)
          && (m.getExceptionTypes().length == 0)) {
        return;
      }

      t = convertToWebApplicationException(r);

      if (inMessage.getExchange().get(Message.RESPONSE_CODE) == null) {
        throw t;
      }

      Endpoint ep = inMessage.getExchange().getEndpoint();
      inMessage.getExchange().put(InterceptorProvider.class, getConfiguration());
      inMessage.setContent(Exception.class, new Fault(t));
      inMessage.getInterceptorChain().abort();
      if (ep.getInFaultObserver() != null) {
        ep.getInFaultObserver().onMessage(inMessage);
      }

      throw t;
    }
  }
Esempio n. 20
0
    public void onClose(CachedOutputStream cos) {
      final LogEvent event = new DefaultLogEventMapper().map(message);
      try {
        String encoding = (String) message.get(Message.ENCODING);
        StringBuilder payload = new StringBuilder();
        writePayload(payload, cos, encoding, event.getContentType());
        event.setPayload(payload.toString());
      } catch (Exception ex) {
        // ignore
      }

      sender.send(event);
      try {
        // empty out the cache
        cos.lockOutputStream();
        cos.resetOut(null, false);
      } catch (Exception ex) {
        // ignore
      }
      message.setContent(OutputStream.class, origStream);
    }
Esempio n. 21
0
  public void prepare(Message message) throws IOException {
    getLogger().log(Level.FINE, "JBIConduit send message");

    message.setContent(OutputStream.class, new NMRConduitOutputStream(message, nmr, target, this));
  }
  protected void setupMessage(
      Message inMessage,
      final ServletConfig config,
      final ServletContext context,
      final HttpServletRequest req,
      final HttpServletResponse resp)
      throws IOException {

    inMessage.setContent(InputStream.class, req.getInputStream());
    inMessage.put(HTTP_REQUEST, req);
    inMessage.put(HTTP_RESPONSE, resp);
    inMessage.put(HTTP_CONTEXT, context);
    inMessage.put(HTTP_CONFIG, config);

    inMessage.put(Message.HTTP_REQUEST_METHOD, req.getMethod());
    inMessage.put(Message.REQUEST_URI, req.getRequestURI());
    String contextPath = req.getContextPath();
    if (contextPath == null) {
      contextPath = "";
    }
    inMessage.put(Message.PATH_INFO, contextPath + req.getPathInfo());

    String contentType = req.getContentType();
    String enc = HttpHeaderHelper.findCharset(contentType);
    if (enc == null) {
      enc = req.getCharacterEncoding();
    }
    // work around a bug with Jetty which results in the character
    // encoding not being trimmed correctly.
    if (enc != null && enc.endsWith("\"")) {
      enc = enc.substring(0, enc.length() - 1);
    }
    if (enc != null || "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod())) {
      // allow gets/deletes/options to not specify an encoding
      String normalizedEncoding = HttpHeaderHelper.mapCharset(enc);
      if (normalizedEncoding == null) {
        String m =
            new org.apache.cxf.common.i18n.Message("INVALID_ENCODING_MSG", LOG, enc).toString();
        LOG.log(Level.WARNING, m);
        throw new IOException(m);
      }
      inMessage.put(Message.ENCODING, normalizedEncoding);
    }

    inMessage.put(Message.QUERY_STRING, req.getQueryString());
    inMessage.put(Message.CONTENT_TYPE, contentType);
    inMessage.put(Message.ACCEPT_CONTENT_TYPE, req.getHeader("Accept"));
    String basePath = getBasePath(contextPath);
    if (!StringUtils.isEmpty(basePath)) {
      inMessage.put(Message.BASE_PATH, basePath);
    }
    inMessage.put(Message.FIXED_PARAMETER_ORDER, isFixedParameterOrder());
    inMessage.put(Message.ASYNC_POST_RESPONSE_DISPATCH, Boolean.TRUE);
    inMessage.put(
        SecurityContext.class,
        new SecurityContext() {
          public Principal getUserPrincipal() {
            return req.getUserPrincipal();
          }

          public boolean isUserInRole(String role) {
            return req.isUserInRole(role);
          }
        });

    setHeaders(inMessage);

    SSLUtils.propogateSecureSession(req, inMessage);
  }
Esempio n. 23
0
  private void serializeMessage(
      ServerProviderFactory providerFactory,
      Message message,
      Response theResponse,
      OperationResourceInfo ori,
      boolean firstTry) {

    ResponseImpl response = (ResponseImpl) JAXRSUtils.copyResponseIfNeeded(theResponse);

    final Exchange exchange = message.getExchange();

    boolean headResponse =
        response.getStatus() == 200
            && firstTry
            && ori != null
            && HttpMethod.HEAD.equals(ori.getHttpMethod());
    Object entity = response.getActualEntity();
    if (headResponse && entity != null) {
      LOG.info(new org.apache.cxf.common.i18n.Message("HEAD_WITHOUT_ENTITY", BUNDLE).toString());
      entity = null;
    }

    Method invoked =
        ori == null
            ? null
            : ori.getAnnotatedMethod() != null ? ori.getAnnotatedMethod() : ori.getMethodToInvoke();

    Annotation[] annotations = null;
    Annotation[] staticAnns = ori != null ? ori.getOutAnnotations() : new Annotation[] {};
    Annotation[] responseAnns = response.getEntityAnnotations();
    if (responseAnns != null) {
      annotations = new Annotation[staticAnns.length + responseAnns.length];
      System.arraycopy(staticAnns, 0, annotations, 0, staticAnns.length);
      System.arraycopy(responseAnns, 0, annotations, staticAnns.length, responseAnns.length);
    } else {
      annotations = staticAnns;
    }

    response.setStatus(getActualStatus(response.getStatus(), entity));
    response.setEntity(entity, annotations);

    // Prepare the headers
    MultivaluedMap<String, Object> responseHeaders =
        prepareResponseHeaders(message, response, entity, firstTry);

    // Run the filters
    try {
      JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, invoked);
    } catch (Throwable ex) {
      handleWriteException(providerFactory, message, ex, firstTry);
      return;
    }

    // Write the entity
    entity = InjectionUtils.getEntity(response.getActualEntity());
    setResponseStatus(message, getActualStatus(response.getStatus(), entity));
    if (entity == null) {
      if (!headResponse) {
        responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, "0");
        if (MessageUtils.getContextualBoolean(
            message, "remove.content.type.for.empty.response", false)) {
          responseHeaders.remove(HttpHeaders.CONTENT_TYPE);
          message.remove(Message.CONTENT_TYPE);
        }
      }
      HttpUtils.convertHeaderValuesToString(responseHeaders, true);
      return;
    }

    Object ignoreWritersProp = exchange.get(JAXRSUtils.IGNORE_MESSAGE_WRITERS);
    boolean ignoreWriters =
        ignoreWritersProp == null ? false : Boolean.valueOf(ignoreWritersProp.toString());
    if (ignoreWriters) {
      writeResponseToStream(message.getContent(OutputStream.class), entity);
      return;
    }

    MediaType responseMediaType =
        getResponseMediaType(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE));

    Class<?> serviceCls = invoked != null ? ori.getClassResourceInfo().getServiceClass() : null;
    Class<?> targetType = InjectionUtils.getRawResponseClass(entity);
    Type genericType =
        InjectionUtils.getGenericResponseType(
            invoked, serviceCls, response.getActualEntity(), targetType, exchange);
    targetType = InjectionUtils.updateParamClassToTypeIfNeeded(targetType, genericType);
    annotations = response.getEntityAnnotations();

    List<WriterInterceptor> writers =
        providerFactory.createMessageBodyWriterInterceptor(
            targetType,
            genericType,
            annotations,
            responseMediaType,
            message,
            ori == null ? null : ori.getNameBindings());

    OutputStream outOriginal = message.getContent(OutputStream.class);
    if (writers == null || writers.isEmpty()) {
      writeResponseErrorMessage(
          message, outOriginal, "NO_MSG_WRITER", targetType, responseMediaType);
      return;
    }
    try {
      boolean checkWriters = false;
      if (responseMediaType.isWildcardSubtype()) {
        Produces pM =
            AnnotationUtils.getMethodAnnotation(
                ori == null ? null : ori.getAnnotatedMethod(), Produces.class);
        Produces pC = AnnotationUtils.getClassAnnotation(serviceCls, Produces.class);
        checkWriters = pM == null && pC == null;
      }
      responseMediaType = checkFinalContentType(responseMediaType, writers, checkWriters);
    } catch (Throwable ex) {
      handleWriteException(providerFactory, message, ex, firstTry);
      return;
    }
    String finalResponseContentType = JAXRSUtils.mediaTypeToString(responseMediaType);
    if (LOG.isLoggable(Level.FINE)) {
      LOG.fine("Response content type is: " + finalResponseContentType);
    }
    responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, finalResponseContentType);
    message.put(Message.CONTENT_TYPE, finalResponseContentType);

    boolean enabled = checkBufferingMode(message, writers, firstTry);
    try {

      try {
        JAXRSUtils.writeMessageBody(
            writers,
            entity,
            targetType,
            genericType,
            annotations,
            responseMediaType,
            responseHeaders,
            message);

        if (isResponseRedirected(message)) {
          return;
        }
        checkCachedStream(message, outOriginal, enabled);
      } finally {
        if (enabled) {
          OutputStream os = message.getContent(OutputStream.class);
          if (os != outOriginal && os instanceof CachedOutputStream) {
            os.close();
          }
          message.setContent(OutputStream.class, outOriginal);
          message.put(XMLStreamWriter.class.getName(), null);
        }
      }

    } catch (Throwable ex) {
      logWriteError(firstTry, targetType, responseMediaType);
      handleWriteException(providerFactory, message, ex, firstTry);
    }
  }
 /**
  * Send an outbound message, assumed to contain all the name-value mappings of the corresponding
  * input message (if any).
  *
  * @param message the message to be sent.
  */
 public void prepare(Message message) throws IOException {
   message.put(HTTP_RESPONSE, response);
   message.setContent(OutputStream.class, new WrappedOutputStream(message, response));
 }
Esempio n. 25
0
 private void switchResponse(final Message message) {
   message.setContent(List.class, new MessageContentsList(Response.ok("failed").build()));
 }
Esempio n. 26
0
  private void handleAbort(SoapMessage message, MessageContext context) {
    if (isRequestor(message)) {
      // client side outbound
      if (getInvoker(message).isOutbound()) {
        message.getInterceptorChain().abort();

        MessageObserver observer =
            (MessageObserver) message.getExchange().get(MessageObserver.class);
        if (!message.getExchange().isOneWay() && observer != null) {
          Endpoint e = message.getExchange().get(Endpoint.class);
          Message responseMsg = e.getBinding().createMessage();

          // the request message becomes the response message
          message.getExchange().setInMessage(responseMsg);
          SOAPMessage soapMessage = ((SOAPMessageContext) context).getMessage();

          if (soapMessage != null) {
            responseMsg.setContent(SOAPMessage.class, soapMessage);
            XMLStreamReader xmlReader = createXMLStreamReaderFromSOAPMessage(soapMessage);
            responseMsg.setContent(XMLStreamReader.class, xmlReader);
          }
          responseMsg.put(
              PhaseInterceptorChain.STARTING_AT_INTERCEPTOR_ID,
              SOAPHandlerInterceptor.class.getName());
          observer.onMessage(responseMsg);
        }
        // We dont call onCompletion here, as onCompletion will be called by inbound
        // LogicalHandlerInterceptor
      } else {
        // client side inbound - Normal handler message processing
        // stops, but the inbound interceptor chain still continues, dispatch the message
        // By onCompletion here, we can skip following Logical handlers
        onCompletion(message);
      }
    } else {
      if (!getInvoker(message).isOutbound()) {
        // server side inbound
        message.getInterceptorChain().abort();
        Endpoint e = message.getExchange().get(Endpoint.class);
        Message responseMsg = e.getBinding().createMessage();
        if (!message.getExchange().isOneWay()) {
          message.getExchange().setOutMessage(responseMsg);
          SOAPMessage soapMessage = ((SOAPMessageContext) context).getMessage();

          responseMsg.setContent(SOAPMessage.class, soapMessage);

          InterceptorChain chain =
              OutgoingChainInterceptor.getOutInterceptorChain(message.getExchange());
          responseMsg.setInterceptorChain(chain);
          // so the idea of starting interceptor chain from any
          // specified point does not work
          // well for outbound case, as many outbound interceptors
          // have their ending interceptors.
          // For example, we can not skip MessageSenderInterceptor.
          chain.doInterceptStartingAfter(
              responseMsg, SoapPreProtocolOutInterceptor.class.getName());
        }

      } else {
        // server side outbound - Normal handler message processing
        // stops, but still continue the outbound interceptor chain, dispatch the message
      }
    }
  }
  public void handleMessage(Message message) throws Fault {
    if (isGET(message)) {
      LOG.info("JbiMessageInInterceptor skipped in HTTP GET method");
      return;
    }
    XMLStreamReader xsr = message.getContent(XMLStreamReader.class);

    DepthXMLStreamReader reader = new DepthXMLStreamReader(xsr);

    Endpoint ep = message.getExchange().get(Endpoint.class);
    BindingInfo binding = ep.getEndpointInfo().getBinding();
    if (!(binding instanceof NMRBindingInfo)) {
      throw new IllegalStateException(
          new org.apache.cxf.common.i18n.Message("NEED_JBIBINDING", BUNDLE).toString());
    }

    if (!StaxUtils.toNextElement(reader)) {
      throw new Fault(new org.apache.cxf.common.i18n.Message("NO_OPERATION_ELEMENT", BUNDLE));
    }

    Exchange ex = message.getExchange();
    QName startQName = reader.getName();

    // handling jbi fault message
    if (startQName.getLocalPart().equals(NMRFault.NMR_FAULT_ROOT)) {
      message.getInterceptorChain().abort();

      if (ep.getInFaultObserver() != null) {
        ep.getInFaultObserver().onMessage(message);
        return;
      }
    }

    // handling xml normal inbound message
    if (!startQName.equals(NMRConstants.JBI_WRAPPER_MESSAGE)) {
      throw new Fault(new org.apache.cxf.common.i18n.Message("NO_JBI_MESSAGE_ELEMENT", BUNDLE));
    }

    try {
      BindingOperationInfo bop = ex.get(BindingOperationInfo.class);
      DataReader<XMLStreamReader> dr = getDataReader(message);
      List<Object> parameters = new ArrayList<Object>();
      reader.next();
      BindingMessageInfo messageInfo = !isRequestor(message) ? bop.getInput() : bop.getOutput();
      message.put(MessageInfo.class, messageInfo.getMessageInfo());
      for (MessagePartInfo part : messageInfo.getMessageParts()) {
        if (!StaxUtils.skipToStartOfElement(reader)) {
          throw new Fault(new org.apache.cxf.common.i18n.Message("NOT_ENOUGH_PARTS", BUNDLE));
        }
        startQName = reader.getName();
        if (!startQName.equals(NMRConstants.JBI_WRAPPER_PART)) {
          throw new Fault(new org.apache.cxf.common.i18n.Message("NO_JBI_PART_ELEMENT", BUNDLE));
        }
        if (part.isElement()) {
          reader.next();
          if (!StaxUtils.toNextElement(reader)) {
            throw new Fault(
                new org.apache.cxf.common.i18n.Message("EXPECTED_ELEMENT_IN_PART", BUNDLE));
          }
        }
        parameters.add(dr.read(part, reader));
        // skip end element
        if (part.isElement()) {
          reader.next();
        }
      }
      int ev = reader.getEventType();
      while (ev != XMLStreamConstants.END_ELEMENT
          && ev != XMLStreamConstants.START_ELEMENT
          && ev != XMLStreamConstants.END_DOCUMENT) {
        ev = reader.next();
      }
      message.setContent(List.class, parameters);
    } catch (XMLStreamException e) {
      throw new Fault(new org.apache.cxf.common.i18n.Message("STAX_READ_EXC", BUNDLE), e);
    }
  }
Esempio n. 28
0
  protected void processFaultDetail(Fault fault, Message msg) {
    Element exDetail = (Element) DOMUtils.getChild(fault.getDetail(), Node.ELEMENT_NODE);
    if (exDetail == null) {
      return;
    }
    QName qname = new QName(exDetail.getNamespaceURI(), exDetail.getLocalName());
    FaultInfo faultWanted = null;
    MessagePartInfo part = null;
    BindingOperationInfo boi = msg.getExchange().get(BindingOperationInfo.class);
    if (boi == null) {
      return;
    }
    if (boi.isUnwrapped()) {
      boi = boi.getWrappedOperation();
    }
    for (FaultInfo faultInfo : boi.getOperationInfo().getFaults()) {
      for (MessagePartInfo mpi : faultInfo.getMessageParts()) {
        if (qname.equals(mpi.getConcreteName())) {
          faultWanted = faultInfo;
          part = mpi;
          break;
        }
      }
      if (faultWanted != null) {
        break;
      }
    }
    if (faultWanted == null) {
      // did not find it using the proper qualified names, we'll try again with just the localpart
      for (FaultInfo faultInfo : boi.getOperationInfo().getFaults()) {
        for (MessagePartInfo mpi : faultInfo.getMessageParts()) {
          if (qname.getLocalPart().equals(mpi.getConcreteName().getLocalPart())) {
            faultWanted = faultInfo;
            part = mpi;
            break;
          }
        }
        if (faultWanted != null) {
          break;
        }
      }
    }
    if (faultWanted == null) {
      return;
    }
    Service s = msg.getExchange().get(Service.class);
    DataBinding dataBinding = s.getDataBinding();

    Object e = null;
    if (isDOMSupported(dataBinding)) {
      DataReader<Node> reader = this.getNodeDataReader(msg);
      reader.setProperty(DataReader.FAULT, fault);
      e = reader.read(part, exDetail);
    } else {
      DataReader<XMLStreamReader> reader = this.getDataReader(msg);
      XMLStreamReader xsr = new W3CDOMStreamReader(exDetail);
      try {
        xsr.nextTag();
      } catch (XMLStreamException e1) {
        throw new Fault(e1);
      }
      reader.setProperty(DataReader.FAULT, fault);
      e = reader.read(part, xsr);
    }

    if (!(e instanceof Exception)) {

      try {
        Class<?> exClass = faultWanted.getProperty(Class.class.getName(), Class.class);
        if (exClass == null) {
          return;
        }
        if (e == null) {
          Constructor<?> constructor = exClass.getConstructor(new Class[] {String.class});
          e = constructor.newInstance(new Object[] {fault.getMessage()});
        } else {

          try {
            Constructor<?> constructor = getConstructor(exClass, e);
            e = constructor.newInstance(new Object[] {fault.getMessage(), e});
          } catch (NoSuchMethodException e1) {
            // Use reflection to convert fault bean to exception
            e = convertFaultBean(exClass, e, fault);
          }
        }
        msg.setContent(Exception.class, e);
      } catch (Exception e1) {
        LogUtils.log(LOG, Level.INFO, "EXCEPTION_WHILE_CREATING_EXCEPTION", e1, e1.getMessage());
      }
    } else {
      if (fault.getMessage() != null) {
        Field f;
        try {
          f = Throwable.class.getDeclaredField("detailMessage");
          ReflectionUtil.setAccessible(f);
          f.set(e, fault.getMessage());
        } catch (Exception e1) {
          // ignore
        }
      }
      msg.setContent(Exception.class, e);
    }
  }
Esempio n. 29
0
  /**
   * This method is called by {@link CxfConsumer} to populate a CXF response exchange from a Camel
   * exchange.
   */
  public void populateCxfResponseFromExchange(
      Exchange camelExchange, org.apache.cxf.message.Exchange cxfExchange) {

    if (cxfExchange.isOneWay()) {
      return;
    }

    // create response context
    Map<String, Object> responseContext = new HashMap<String, Object>();

    org.apache.camel.Message response;
    if (camelExchange.getPattern().isOutCapable()) {
      if (camelExchange.hasOut()) {
        response = camelExchange.getOut();
        LOG.trace("Get the response from the out message");
      } else { // Take the in message as a fall back
        response = camelExchange.getIn();
        LOG.trace("Get the response from the in message as a fallback");
      }
    } else {
      response = camelExchange.getIn();
      LOG.trace("Get the response from the in message");
    }

    // propagate response context
    Map<String, Object> camelHeaders = response.getHeaders();
    extractInvocationContextFromCamel(
        camelExchange, camelHeaders, responseContext, Client.RESPONSE_CONTEXT);

    propagateHeadersFromCamelToCxf(camelExchange, camelHeaders, cxfExchange, responseContext);
    // create out message
    Endpoint ep = cxfExchange.get(Endpoint.class);
    Message outMessage = ep.getBinding().createMessage();
    cxfExchange.setOutMessage(outMessage);

    DataFormat dataFormat =
        camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class);

    // make sure the "requestor role" property does not get propagated as we do switch role
    responseContext.remove(Message.REQUESTOR_ROLE);

    outMessage.putAll(responseContext);

    // Do we still need to put the response context back like this
    outMessage.put(Client.RESPONSE_CONTEXT, responseContext);

    LOG.trace("Set out response context = {}", responseContext);

    // set body
    Object outBody = DefaultCxfBinding.getBodyFromCamel(response, dataFormat);

    if (outBody != null) {
      if (dataFormat == DataFormat.PAYLOAD) {
        CxfPayload<?> payload = (CxfPayload<?>) outBody;
        outMessage.setContent(
            List.class, getResponsePayloadList(cxfExchange, payload.getBodySources()));
        outMessage.put(Header.HEADER_LIST, payload.getHeaders());
      } else {
        if (responseContext.get(Header.HEADER_LIST) != null) {
          outMessage.put(Header.HEADER_LIST, responseContext.get(Header.HEADER_LIST));
        }

        MessageContentsList resList = null;
        // Create a new MessageContentsList to avoid OOM from the HolderOutInterceptor
        if (outBody instanceof List) {
          resList = new MessageContentsList((List<?>) outBody);
        } else if (outBody.getClass().isArray()) {
          resList = new MessageContentsList((Object[]) outBody);
        } else {
          resList = new MessageContentsList(outBody);
        }

        if (resList != null) {
          outMessage.setContent(List.class, resList);
          LOG.trace("Set Out CXF message content = {}", resList);
        }
      }
    } else if (!cxfExchange.isOneWay()
        && cxfExchange.getInMessage() != null
        && MessageUtils.isTrue(
            cxfExchange
                .getInMessage()
                .getContextualProperty("jaxws.provider.interpretNullAsOneway"))) {
      // treat this non-oneway call as oneway when the provider returns a null
      changeToOneway(cxfExchange);
      return;
    }

    // propagate attachments

    Set<Attachment> attachments = null;
    boolean isXop = Boolean.valueOf(camelExchange.getProperty(Message.MTOM_ENABLED, String.class));
    for (Map.Entry<String, DataHandler> entry :
        camelExchange.getOut().getAttachments().entrySet()) {
      if (attachments == null) {
        attachments = new HashSet<Attachment>();
      }
      AttachmentImpl attachment = new AttachmentImpl(entry.getKey(), entry.getValue());
      attachment.setXOP(isXop);
      attachments.add(attachment);
    }

    if (attachments != null) {
      outMessage.setAttachments(attachments);
    }

    BindingOperationInfo boi = cxfExchange.get(BindingOperationInfo.class);
    if (boi != null) {
      cxfExchange.put(BindingMessageInfo.class, boi.getOutput());
    }
  }
 protected void transformWriter(Message message, Writer writer) {
   XSLTCachedWriter wrapper = new XSLTCachedWriter(getXSLTTemplate(), writer);
   message.setContent(Writer.class, wrapper);
 }