use of org.apache.cxf.jaxrs.ext.multipart.Multipart in project cxf by apache.
the class MultipartProvider method readFrom.
public Object readFrom(Class<Object> c, Type t, Annotation[] anns, MediaType mt, MultivaluedMap<String, String> headers, InputStream is) throws IOException, WebApplicationException {
checkContentLength();
List<Attachment> infos = AttachmentUtils.getAttachments(mc, attachmentDir, attachmentThreshold, attachmentMaxSize);
boolean collectionExpected = Collection.class.isAssignableFrom(c);
if (collectionExpected && AnnotationUtils.getAnnotation(anns, Multipart.class) == null) {
return getAttachmentCollection(t, infos, anns);
}
if (c.isAssignableFrom(Map.class)) {
Map<String, Object> map = new LinkedHashMap<String, Object>(infos.size());
Class<?> actual = getActualType(t, 1);
for (Attachment a : infos) {
map.put(a.getContentType().toString(), fromAttachment(a, actual, actual, anns));
}
return map;
}
if (MultipartBody.class.isAssignableFrom(c)) {
return new MultipartBody(infos);
}
Multipart id = AnnotationUtils.getAnnotation(anns, Multipart.class);
Attachment multipart = AttachmentUtils.getMultipart(id, mt, infos);
if (multipart != null) {
if (collectionExpected && !mediaTypeSupported(multipart.getContentType()) && !PropertyUtils.isTrue(mc.getContextualProperty(SINGLE_PART_IS_COLLECTION))) {
List<Attachment> allMultiparts = AttachmentUtils.getMatchingAttachments(id, infos);
return getAttachmentCollection(t, allMultiparts, anns);
}
return fromAttachment(multipart, c, t, anns);
}
if (id != null && !id.required()) {
/*
* Return default value for a missing optional part
*/
Object defaultValue = null;
if (c.isPrimitive()) {
defaultValue = PrimitiveUtils.read((Class<?>) c == boolean.class ? "false" : "0", c);
}
return defaultValue;
}
throw ExceptionUtils.toBadRequestException(null, null);
}
use of org.apache.cxf.jaxrs.ext.multipart.Multipart in project cxf by apache.
the class MultipartStore method addBookXop.
@POST
@Path("/xop")
@Consumes("multipart/related")
@Produces("multipart/related;type=text/xml")
@Multipart("xop")
public XopType addBookXop(@Multipart XopType type) throws Exception {
if (!"xopName".equals(type.getName())) {
throw new RuntimeException("Wrong name property");
}
String bookXsd = IOUtils.readStringFromStream(type.getAttachinfo().getInputStream());
String bookXsd2 = IOUtils.readStringFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
if (!bookXsd.equals(bookXsd2)) {
throw new RuntimeException("Wrong attachinfo property");
}
String bookXsdRef = IOUtils.readStringFromStream(type.getAttachInfoRef().getInputStream());
if (!bookXsdRef.equals(bookXsd2)) {
throw new RuntimeException("Wrong attachinforef property");
}
if (!Boolean.getBoolean("java.awt.headless") && type.getImage() == null) {
throw new RuntimeException("Wrong image property");
}
context.put(org.apache.cxf.message.Message.MTOM_ENABLED, "true");
XopType xop = new XopType();
xop.setName("xopName");
InputStream is = getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd");
byte[] data = IOUtils.readBytesFromStream(is);
xop.setAttachinfo(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
xop.setAttachInfoRef(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
xop.setAttachinfo2(bookXsd.getBytes());
xop.setImage(ImageIO.read(getClass().getResource("/org/apache/cxf/systest/jaxrs/resources/java.jpg")));
return xop;
}
use of org.apache.cxf.jaxrs.ext.multipart.Multipart in project cxf by apache.
the class JAXRSContainerTest method testQueryMultipartParam.
@Test
public void testQueryMultipartParam() {
try {
JAXRSContainer container = new JAXRSContainer(null);
ToolContext context = new ToolContext();
context.put(WadlToolConstants.CFG_OUTPUTDIR, output.getCanonicalPath());
context.put(WadlToolConstants.CFG_WADLURL, getLocation("/wadl/testQueryMultipartParam.wadl"));
context.put(WadlToolConstants.CFG_COMPILE, "true");
container.setContext(context);
container.execute();
assertNotNull(output.list());
List<File> files = FileUtils.getFilesRecurse(output, ".+\\." + "class" + "$");
assertEquals(2, files.size());
assertTrue(checkContains(files, "application.Test1.class"));
assertTrue(checkContains(files, "application.Test2.class"));
@SuppressWarnings("resource") ClassLoader loader = new URLClassLoader(new URL[] { output.toURI().toURL() });
Class<?> test1 = loader.loadClass("application.Test1");
Method[] test1Methods = test1.getDeclaredMethods();
assertEquals(1, test1Methods.length);
assertEquals(2, test1Methods[0].getAnnotations().length);
assertNotNull(test1Methods[0].getAnnotation(PUT.class));
Consumes consumes1 = test1Methods[0].getAnnotation(Consumes.class);
assertNotNull(consumes1);
assertEquals(1, consumes1.value().length);
assertEquals("multipart/mixed", consumes1.value()[0]);
assertEquals("put", test1Methods[0].getName());
Class<?>[] paramTypes = test1Methods[0].getParameterTypes();
assertEquals(3, paramTypes.length);
Annotation[][] paramAnns = test1Methods[0].getParameterAnnotations();
assertEquals(Boolean.class, paramTypes[0]);
assertEquals(1, paramAnns[0].length);
QueryParam test1QueryParam1 = (QueryParam) paramAnns[0][0];
assertEquals("standalone", test1QueryParam1.value());
assertEquals(String.class, paramTypes[1]);
assertEquals(1, paramAnns[1].length);
Multipart test1MultipartParam1 = (Multipart) paramAnns[1][0];
assertEquals("action", test1MultipartParam1.value());
assertTrue(test1MultipartParam1.required());
assertEquals(String.class, paramTypes[2]);
assertEquals(1, paramAnns[2].length);
Multipart test1MultipartParam2 = (Multipart) paramAnns[2][0];
assertEquals("sources", test1MultipartParam2.value());
assertFalse(test1MultipartParam2.required());
Class<?> test2 = loader.loadClass("application.Test2");
Method[] test2Methods = test2.getDeclaredMethods();
assertEquals(1, test2Methods.length);
assertEquals(2, test2Methods[0].getAnnotations().length);
assertNotNull(test2Methods[0].getAnnotation(PUT.class));
Consumes consumes2 = test2Methods[0].getAnnotation(Consumes.class);
assertNotNull(consumes2);
assertEquals(1, consumes2.value().length);
assertEquals("application/json", consumes2.value()[0]);
assertEquals("put", test2Methods[0].getName());
Class<?>[] paramTypes2 = test2Methods[0].getParameterTypes();
assertEquals(2, paramTypes2.length);
Annotation[][] paramAnns2 = test2Methods[0].getParameterAnnotations();
assertEquals(boolean.class, paramTypes2[0]);
assertEquals(1, paramAnns2[0].length);
QueryParam test2QueryParam1 = (QueryParam) paramAnns2[0][0];
assertEquals("snapshot", test2QueryParam1.value());
assertEquals(String.class, paramTypes2[1]);
assertEquals(0, paramAnns2[1].length);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
use of org.apache.cxf.jaxrs.ext.multipart.Multipart in project cxf by apache.
the class SourceGenerator method writeRequestTypes.
// CHECKSTYLE:OFF
private void writeRequestTypes(Element requestEl, String classPackage, Element repElement, List<Element> inParamEls, boolean jaxpRequired, StringBuilder sbCode, StringBuilder sbMethodDocs, Set<String> imports, ContextInfo info, boolean suspendedAsync) {
// CHECKSTYLE:ON
boolean form = false;
boolean multipart = false;
boolean formOrMultipartParamsAvailable = false;
String requestMediaType = null;
int currentSize = 0;
if (requestEl != null) {
inParamEls.addAll(getWadlElements(requestEl, "param"));
currentSize = inParamEls.size();
List<Element> repElements = getWadlElements(requestEl, "representation");
form = addFormParameters(inParamEls, requestEl, repElements);
if (form) {
formOrMultipartParamsAvailable = currentSize < inParamEls.size();
requestMediaType = repElements.get(0).getAttribute("mediaType");
multipart = requestMediaType.startsWith("multipart/");
}
}
boolean writeAnnotations = writeAnnotations(info.isInterfaceGenerated());
for (int i = 0; i < inParamEls.size(); i++) {
Element paramEl = inParamEls.get(i);
Class<?> paramAnn = getParamAnnotation(paramEl.getAttribute("style"));
if (i >= currentSize && paramAnn == QueryParam.class && formOrMultipartParamsAvailable) {
paramAnn = !multipart ? FormParam.class : Multipart.class;
}
String name = paramEl.getAttribute("name");
boolean enumCreated = false;
if (generateEnums) {
List<Element> options = DOMUtils.findAllElementsByTagNameNS(paramEl, getWadlNamespace(), "option");
if (!options.isEmpty()) {
generateEnumClass(getTypicalClassName(name), options, info.getSrcDir(), classPackage);
enumCreated = true;
}
}
if (writeAnnotations) {
String required = paramEl.getAttribute("required");
if (Multipart.class.equals(paramAnn) && "false".equals(required)) {
writeAnnotation(sbCode, imports, paramAnn, null, false, false);
sbCode.append("(value = \"").append(name).append("\", required = false").append(')');
} else {
writeAnnotation(sbCode, imports, paramAnn, name, false, false);
}
sbCode.append(" ");
String defaultVal = paramEl.getAttribute("default");
if (defaultVal.length() > 0) {
writeAnnotation(sbCode, imports, DefaultValue.class, defaultVal, false, false);
sbCode.append(" ");
}
}
boolean isRepeating = isRepeatingParam(paramEl);
String type = enumCreated ? getTypicalClassName(name) : getPrimitiveType(paramEl, info, imports);
if (OPTIONAL_PARAMS.contains(paramAnn) && (isRepeating || !Boolean.valueOf(paramEl.getAttribute("required"))) && AUTOBOXED_PRIMITIVES_MAP.containsKey(type)) {
type = AUTOBOXED_PRIMITIVES_MAP.get(type);
}
type = addListIfRepeating(type, isRepeating, imports);
String paramName;
if (JavaUtils.isJavaKeyword(name)) {
paramName = name.concat("_arg");
} else {
paramName = name.replaceAll("[:\\.\\-]", "_");
}
String javaParamName = firstCharToLowerCase(paramName);
sbCode.append(type).append(" ").append(javaParamName);
if (i + 1 < inParamEls.size()) {
sbCode.append(", ");
if (i + 1 >= 4 && ((i + 1) % 4) == 0) {
sbCode.append(getLineSep()).append(TAB).append(TAB).append(TAB).append(TAB);
}
}
if (sbMethodDocs != null) {
writeMethodParamDocs(paramEl, javaParamName, sbMethodDocs);
}
}
String elementParamType = null;
String elementParamName = null;
boolean writeBeanValidation = false;
if (!form) {
if (!jaxpRequired) {
elementParamType = getElementRefName(repElement, info, imports, false);
if (elementParamType != null) {
if (writeAnnotations && supportBeanValidation && isRepWithElementAvailable(Collections.singletonList(repElement), info.getGrammarInfo())) {
writeBeanValidation = true;
}
int lastIndex = elementParamType.lastIndexOf('.');
if (lastIndex != -1) {
elementParamType = elementParamType.substring(lastIndex + 1);
}
elementParamName = elementParamType.toLowerCase();
} else if (repElement != null) {
Element param = DOMUtils.getFirstChildWithName(repElement, getWadlNamespace(), "param");
if (param != null) {
elementParamType = getPrimitiveType(param, info, imports);
elementParamName = param.getAttribute("name");
}
}
} else {
addImport(imports, Source.class.getName());
elementParamType = Source.class.getSimpleName();
elementParamName = "source";
}
} else if (!formOrMultipartParamsAvailable) {
if (requestMediaType != null && mediaTypesMap.containsKey(requestMediaType)) {
elementParamType = addImportsAndGetSimpleName(imports, mediaTypesMap.get(requestMediaType));
} else {
String fullClassName = !multipart ? MultivaluedMap.class.getName() : MultipartBody.class.getName();
elementParamType = addImportsAndGetSimpleName(imports, fullClassName);
}
elementParamName = !multipart ? "map" : "body";
}
if (elementParamType != null) {
if (!inParamEls.isEmpty()) {
sbCode.append(", ");
}
if (writeBeanValidation) {
addImport(imports, BEAN_VALID_FULL_NAME);
sbCode.append("@").append(BEAN_VALID_SIMPLE_NAME).append(" ");
}
sbCode.append(elementParamType).append(" ").append(elementParamName);
}
if (sbMethodDocs != null && repElement != null) {
writeMethodParamDocs(repElement, elementParamName, sbMethodDocs);
}
if (suspendedAsync) {
if (!inParamEls.isEmpty() || elementParamType != null) {
sbCode.append(", ");
}
if (writeAnnotations) {
addImport(imports, Suspended.class.getName());
sbCode.append("@").append(Suspended.class.getSimpleName()).append(" ");
}
addImport(imports, AsyncResponse.class.getName());
sbCode.append(AsyncResponse.class.getSimpleName()).append(" ").append("async");
}
}
use of org.apache.cxf.jaxrs.ext.multipart.Multipart in project cxf by apache.
the class ClientProxyImpl method handleMultipart.
private List<Attachment> handleMultipart(MultivaluedMap<ParameterType, Parameter> map, OperationResourceInfo ori, Object[] params) {
List<Attachment> atts = new LinkedList<Attachment>();
List<Parameter> fm = getParameters(map, ParameterType.REQUEST_BODY);
for (Parameter p : fm) {
Multipart part = getMultipart(ori, p.getIndex());
if (part != null) {
Object partObject = params[p.getIndex()];
if (partObject != null) {
atts.add(new Attachment(part.value(), part.type(), partObject));
}
}
}
return atts;
}
Aggregations