示例#1
0
 public void writeTo(
     T obj,
     Class<?> cls,
     Type genericType,
     Annotation[] anns,
     MediaType m,
     MultivaluedMap<String, Object> headers,
     OutputStream os)
     throws IOException {
   try {
     String encoding = HttpUtils.getSetEncoding(m, headers, null);
     if (InjectionUtils.isSupportedCollectionOrArray(cls)) {
       marshalCollection(cls, obj, genericType, encoding, os, m, anns);
     } else {
       Object actualObject = checkAdapter(obj, cls, anns, true);
       Class<?> actualClass =
           obj != actualObject || cls.isInterface() ? actualObject.getClass() : cls;
       marshal(actualObject, actualClass, genericType, encoding, os, m, anns);
     }
   } catch (JAXBException e) {
     handleJAXBException(e, false);
   } catch (WebApplicationException e) {
     throw e;
   } catch (Exception e) {
     LOG.warning(ExceptionUtils.getStackTrace(e));
     throw ExceptionUtils.toInternalServerErrorException(e, null);
   }
 }
示例#2
0
  protected XMLStreamWriter getStreamWriter(Object obj, OutputStream os, MediaType mt) {
    XMLStreamWriter writer = null;
    MessageContext mc = getContext();
    if (mc != null) {
      writer = mc.getContent(XMLStreamWriter.class);
      if (writer == null) {
        XMLOutputFactory factory = (XMLOutputFactory) mc.get(XMLOutputFactory.class.getName());
        if (factory != null) {
          try {
            writer = factory.createXMLStreamWriter(os);
          } catch (XMLStreamException e) {
            throw ExceptionUtils.toInternalServerErrorException(
                new RuntimeException("Cant' create XMLStreamWriter", e), null);
          }
        }
      }
      if (writer == null && getEnableStreaming()) {
        writer = StaxUtils.createXMLStreamWriter(os);
      }
    }

    if (writer == null && os == null) {
      writer = getStreamHandlerFromCurrentMessage(XMLStreamWriter.class);
    }
    return createTransformWriterIfNeeded(writer, os, true);
  }
示例#3
0
 protected Object unmarshalFromInputStream(
     Unmarshaller unmarshaller, InputStream is, Annotation[] anns, MediaType mt)
     throws JAXBException {
   // Try to create the read before unmarshalling the stream
   XMLStreamReader xmlReader = null;
   try {
     if (is == null) {
       Reader reader = getStreamHandlerFromCurrentMessage(Reader.class);
       if (reader == null) {
         LOG.severe("No InputStream, Reader, or XMLStreamReader is available");
         throw ExceptionUtils.toInternalServerErrorException(null, null);
       }
       xmlReader = StaxUtils.createXMLStreamReader(reader);
     } else {
       xmlReader = StaxUtils.createXMLStreamReader(is);
     }
     configureReaderRestrictions(xmlReader);
     return unmarshaller.unmarshal(xmlReader);
   } finally {
     try {
       StaxUtils.close(xmlReader);
     } catch (XMLStreamException e) {
       // Ignore
     }
   }
 }
示例#4
0
  protected XMLStreamReader getStreamReader(InputStream is, Class<?> type, MediaType mt) {
    MessageContext mc = getContext();
    XMLStreamReader reader = mc != null ? mc.getContent(XMLStreamReader.class) : null;
    if (reader == null && mc != null) {
      XMLInputFactory factory = (XMLInputFactory) mc.get(XMLInputFactory.class.getName());
      if (factory != null) {
        try {
          reader = factory.createXMLStreamReader(is);
        } catch (XMLStreamException e) {
          throw ExceptionUtils.toInternalServerErrorException(
              new RuntimeException("Can not create XMLStreamReader", e), null);
        }
      }
    }

    if (reader == null && is == null) {
      reader = getStreamHandlerFromCurrentMessage(XMLStreamReader.class);
    }

    reader = createTransformReaderIfNeeded(reader, is);
    reader = createDepthReaderIfNeeded(reader, is);
    if (InjectionUtils.isSupportedCollectionOrArray(type)) {
      return new JAXBCollectionWrapperReader(TransformUtils.createNewReaderIfNeeded(reader, is));
    } else {
      return reader;
    }
  }
示例#5
0
 protected WebApplicationException convertToWebApplicationException(Response r) {
   try {
     Class<?> exceptionClass =
         ExceptionUtils.getWebApplicationExceptionClass(r, WebApplicationException.class);
     Constructor<?> ctr = exceptionClass.getConstructor(Response.class);
     return (WebApplicationException) ctr.newInstance(r);
   } catch (Throwable ex2) {
     return new WebApplicationException(r);
   }
 }
示例#6
0
 protected void marshalToOutputStream(
     Marshaller ms, Object obj, OutputStream os, Annotation[] anns, MediaType mt)
     throws Exception {
   if (os == null) {
     Writer writer = getStreamHandlerFromCurrentMessage(Writer.class);
     if (writer == null) {
       LOG.severe("No OutputStream, Writer, or XMLStreamWriter is available");
       throw ExceptionUtils.toInternalServerErrorException(null, null);
     }
     ms.marshal(obj, writer);
     writer.flush();
   } else {
     ms.marshal(obj, os);
   }
 }
 @Override
 protected Object unmarshalFromReader(
     Unmarshaller unmarshaller, XMLStreamReader reader, Annotation[] anns, MediaType mt)
     throws JAXBException {
   CachedOutputStream out = new CachedOutputStream();
   try {
     XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
     StaxUtils.copy(new StaxSource(reader), writer);
     writer.writeEndDocument();
     writer.flush();
     writer.close();
     return unmarshalFromInputStream(unmarshaller, out.getInputStream(), anns, mt);
   } catch (Exception ex) {
     throw ExceptionUtils.toBadRequestException(ex, null);
   }
 }
 private void checkSecurityContextEnd(
     ContainerRequestContext rc, MultivaluedMap<String, String> requestParams) {
   String codeParam = requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE);
   SecurityContext sc = rc.getSecurityContext();
   if (sc == null || sc.getUserPrincipal() == null) {
     if (codeParam == null
         && requestParams.containsKey(OAuthConstants.ERROR_KEY)
         && !faultAccessDeniedResponses) {
       if (!applicationCanHandleAccessDenied) {
         String error = requestParams.getFirst(OAuthConstants.ERROR_KEY);
         rc.abortWith(Response.ok(new AccessDeniedResponse(error)).build());
       }
     } else {
       throw ExceptionUtils.toNotAuthorizedException(null, null);
     }
   }
 }
  protected Templates createTemplates(
      Templates templates, Map<String, Object> configuredParams, Map<String, String> outProps) {
    if (templates == null) {
      if (supportJaxbOnly) {
        return null;
      } else {
        LOG.severe("No template is available");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
      }
    }

    TemplatesImpl templ = new TemplatesImpl(templates, uriResolver);
    MessageContext mc = getContext();
    if (mc != null) {
      UriInfo ui = mc.getUriInfo();
      MultivaluedMap<String, String> params = ui.getPathParameters();
      for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        String value = entry.getValue().get(0);
        int ind = value.indexOf(";");
        if (ind > 0) {
          value = value.substring(0, ind);
        }
        templ.setTransformerParameter(entry.getKey(), value);
      }

      List<PathSegment> segments = ui.getPathSegments();
      if (segments.size() > 0) {
        setTransformParameters(templ, segments.get(segments.size() - 1).getMatrixParameters());
      }
      setTransformParameters(templ, ui.getQueryParameters());
      templ.setTransformerParameter(ABSOLUTE_PATH_PARAMETER, ui.getAbsolutePath().toString());
      templ.setTransformerParameter(RELATIVE_PATH_PARAMETER, ui.getPath());
      templ.setTransformerParameter(BASE_PATH_PARAMETER, ui.getBaseUri().toString());
      if (configuredParams != null) {
        for (Map.Entry<String, Object> entry : configuredParams.entrySet()) {
          templ.setTransformerParameter(entry.getKey(), entry.getValue());
        }
      }
    }
    if (outProps != null) {
      templ.setOutProperties(outProps);
    }

    return templ;
  }
  @Override
  protected Object unmarshalFromInputStream(
      Unmarshaller unmarshaller, InputStream is, Annotation[] anns, MediaType mt)
      throws JAXBException {
    try {

      Templates t = createTemplates(getInTemplates(anns, mt), inParamsMap, inProperties);
      if (t == null && supportJaxbOnly) {
        return super.unmarshalFromInputStream(unmarshaller, is, anns, mt);
      }

      if (unmarshaller.getClass().getName().contains("eclipse")) {
        // eclipse MOXy doesn't work properly with the XMLFilter/Reader thing
        // so we need to bounce through a DOM
        Source reader = new StaxSource(StaxUtils.createXMLStreamReader(is));
        DOMResult dom = new DOMResult();
        t.newTransformer().transform(reader, dom);
        return unmarshaller.unmarshal(dom.getNode());
      }
      XMLFilter filter = null;
      try {
        filter = factory.newXMLFilter(t);
      } catch (TransformerConfigurationException ex) {
        TemplatesImpl ti = (TemplatesImpl) t;
        filter = factory.newXMLFilter(ti.getTemplates());
        trySettingProperties(filter, ti);
      }
      XMLReader reader = new StaxSource(StaxUtils.createXMLStreamReader(is));
      filter.setParent(reader);
      SAXSource source = new SAXSource();
      source.setXMLReader(filter);
      if (systemId != null) {
        source.setSystemId(systemId);
      }
      return unmarshaller.unmarshal(source);
    } catch (TransformerException ex) {
      LOG.warning("Transformation exception : " + ex.getMessage());
      throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
  }
示例#11
0
 private MediaType checkFinalContentType(
     MediaType mt, List<WriterInterceptor> writers, boolean checkWriters) {
   if (checkWriters) {
     int mbwIndex = writers.size() == 1 ? 0 : writers.size() - 1;
     MessageBodyWriter<Object> writer = ((WriterInterceptorMBW) writers.get(mbwIndex)).getMBW();
     Produces pm = writer.getClass().getAnnotation(Produces.class);
     if (pm != null) {
       List<MediaType> sorted =
           JAXRSUtils.sortMediaTypes(
               JAXRSUtils.getMediaTypes(pm.value()), JAXRSUtils.MEDIA_TYPE_QS_PARAM);
       mt = JAXRSUtils.intersectMimeTypes(sorted, mt).get(0);
     }
   }
   if (mt.isWildcardType() || mt.isWildcardSubtype()) {
     if ("application".equals(mt.getType()) || mt.isWildcardType()) {
       mt = MediaType.APPLICATION_OCTET_STREAM_TYPE;
     } else {
       throw ExceptionUtils.toNotAcceptableException(null, null);
     }
   }
   return mt;
 }
 protected void checkSecurityContextStart(ContainerRequestContext rc) {
   SecurityContext sc = rc.getSecurityContext();
   if (sc == null || sc.getUserPrincipal() == null) {
     throw ExceptionUtils.toNotAuthorizedException(null, null);
   }
 }
示例#13
0
  public T readFrom(
      Class<T> type,
      Type genericType,
      Annotation[] anns,
      MediaType mt,
      MultivaluedMap<String, String> headers,
      InputStream is)
      throws IOException {
    if (isPayloadEmpty(headers)) {
      if (AnnotationUtils.getAnnotation(anns, Nullable.class) != null) {
        return null;
      } else {
        reportEmptyContentLength();
      }
    }

    XMLStreamReader reader = null;
    Unmarshaller unmarshaller = null;
    try {

      boolean isCollection = InjectionUtils.isSupportedCollectionOrArray(type);
      Class<?> theGenericType = isCollection ? InjectionUtils.getActualType(genericType) : type;
      Class<?> theType = getActualType(theGenericType, genericType, anns);

      unmarshaller = createUnmarshaller(theType, genericType, isCollection);
      addAttachmentUnmarshaller(unmarshaller);
      Object response = null;
      if (JAXBElement.class.isAssignableFrom(type)
          || !isCollection
              && (unmarshalAsJaxbElement
                  || jaxbElementClassMap != null
                      && jaxbElementClassMap.containsKey(theType.getName()))) {
        reader = getStreamReader(is, type, mt);
        reader = TransformUtils.createNewReaderIfNeeded(reader, is);
        if (JAXBElement.class.isAssignableFrom(type) && type == theType) {
          response = unmarshaller.unmarshal(reader);
        } else {
          response = unmarshaller.unmarshal(reader, theType);
        }
      } else {
        response = doUnmarshal(unmarshaller, type, is, anns, mt);
      }
      if (response instanceof JAXBElement && !JAXBElement.class.isAssignableFrom(type)) {
        response = ((JAXBElement<?>) response).getValue();
      }
      if (isCollection) {
        response =
            ((CollectionWrapper) response)
                .getCollectionOrArray(
                    unmarshaller,
                    theType,
                    type,
                    genericType,
                    org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(theGenericType, anns));
      } else {
        response = checkAdapter(response, type, anns, false);
      }
      return type.cast(response);

    } catch (JAXBException e) {
      handleJAXBException(e, true);
    } catch (DepthExceededStaxException e) {
      throw ExceptionUtils.toWebApplicationException(null, JAXRSUtils.toResponse(413));
    } catch (WebApplicationException e) {
      throw e;
    } catch (Exception e) {
      LOG.warning(ExceptionUtils.getStackTrace(e));
      throw ExceptionUtils.toBadRequestException(e, null);
    } finally {
      try {
        StaxUtils.close(reader);
      } catch (XMLStreamException e) {
        // Ignore
      }
      JAXBUtils.closeUnmarshaller(unmarshaller);
    }
    // unreachable
    return null;
  }