package org.glassfish.jersey.media.multipart.internal;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.ConstrainedTo;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.RuntimeType;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.ContextResolver;
import jakarta.ws.rs.ext.MessageBodyReader;
import jakarta.ws.rs.ext.Providers;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import jakarta.inject.Singleton;
import org.glassfish.jersey.media.multipart.BodyPart;
import org.glassfish.jersey.media.multipart.BodyPartEntity;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartProperties;
import org.glassfish.jersey.message.MessageBodyWorkers;
import org.glassfish.jersey.message.internal.MediaTypes;
import org.jvnet.mimepull.Header;
import org.jvnet.mimepull.MIMEConfig;
import org.jvnet.mimepull.MIMEMessage;
import org.jvnet.mimepull.MIMEParsingException;
import org.jvnet.mimepull.MIMEPart;
@Consumes("multipart/*")
@Singleton
@ConstrainedTo(RuntimeType.CLIENT)
public class MultiPartReaderClientSide implements MessageBodyReader<MultiPart> {
private static final Logger LOGGER = Logger.getLogger(MultiPartReaderClientSide.class.getName());
@Inject
private Provider<MessageBodyWorkers> messageBodyWorkers;
private final MIMEConfig mimeConfig;
public MultiPartReaderClientSide(@Context final Providers providers) {
final ContextResolver<MultiPartProperties> contextResolver =
providers.getContextResolver(MultiPartProperties.class, MediaType.WILDCARD_TYPE);
MultiPartProperties properties = null;
if (contextResolver != null) {
properties = contextResolver.getContext(this.getClass());
}
if (properties == null) {
properties = new MultiPartProperties();
}
mimeConfig = createMimeConfig(properties);
}
private MIMEConfig createMimeConfig(final MultiPartProperties properties) {
final MIMEConfig mimeConfig = new MIMEConfig();
mimeConfig.setMemoryThreshold(properties.getBufferThreshold());
final String tempDir = properties.getTempDir();
if (tempDir != null) {
mimeConfig.setDir(tempDir);
}
if (properties.getBufferThreshold() != MultiPartProperties.BUFFER_THRESHOLD_MEMORY_ONLY) {
try {
File.createTempFile("MIME", null, tempDir != null ? new File(tempDir) : null).delete();
} catch (final IOException ioe) {
LOGGER.log(Level.WARNING, LocalizationMessages.TEMP_FILE_CANNOT_BE_CREATED(properties.getBufferThreshold()), ioe);
}
}
return mimeConfig;
}
public boolean isReadable(final Class<?> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType) {
return MultiPart.class.isAssignableFrom(type);
}
public MultiPart readFrom(final Class<MultiPart> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType,
final MultivaluedMap<String, String> headers,
final InputStream stream) throws IOException, WebApplicationException {
try {
return readMultiPart(type, genericType, annotations, mediaType, headers, stream);
} catch (final MIMEParsingException mpe) {
if (mpe.getCause() instanceof IOException) {
throw (IOException) mpe.getCause();
} else {
throw new BadRequestException(mpe);
}
}
}
protected MultiPart readMultiPart(final Class<MultiPart> type,
final Type genericType,
final Annotation[] annotations,
MediaType mediaType,
final MultivaluedMap<String, String> headers,
final InputStream stream) throws IOException, MIMEParsingException {
mediaType = unquoteMediaTypeParameters(mediaType, "boundary");
final MIMEMessage mimeMessage = new MIMEMessage(stream,
mediaType.getParameters().get("boundary"),
mimeConfig);
final boolean formData = MediaTypes.typeEqual(mediaType, MediaType.MULTIPART_FORM_DATA_TYPE);
final MultiPart multiPart = formData ? new FormDataMultiPart() : new MultiPart();
final MessageBodyWorkers workers = messageBodyWorkers.get();
multiPart.setMessageBodyWorkers(workers);
final MultivaluedMap<String, String> multiPartHeaders = multiPart.getHeaders();
for (final Map.Entry<String, List<String>> entry : headers.entrySet()) {
final List<String> values = entry.getValue();
for (final String value : values) {
multiPartHeaders.add(entry.getKey(), value);
}
}
final boolean fileNameFix;
if (!formData) {
multiPart.setMediaType(mediaType);
fileNameFix = false;
} else {
final String userAgent = headers.getFirst(HttpHeaders.USER_AGENT);
fileNameFix = userAgent != null && userAgent.contains(" MSIE ");
}
for (final MIMEPart mimePart : getMimeParts(mimeMessage)) {
final BodyPart bodyPart = formData ? new FormDataBodyPart(fileNameFix) : new BodyPart();
bodyPart.setMessageBodyWorkers(workers);
for (final Header header : mimePart.getAllHeaders()) {
bodyPart.getHeaders().add(header.getName(), header.getValue());
}
try {
final String contentType = bodyPart.getHeaders().getFirst("Content-Type");
if (contentType != null) {
bodyPart.setMediaType(MediaType.valueOf(contentType));
}
bodyPart.getContentDisposition();
} catch (final IllegalArgumentException ex) {
throw new BadRequestException(ex);
}
bodyPart.setEntity(new BodyPartEntity(mimePart));
multiPart.getBodyParts().add(bodyPart);
}
return multiPart;
}
private List<MIMEPart> getMimeParts(final MIMEMessage message) {
try {
return message.getAttachments();
} catch (final MIMEParsingException obtainPartsError) {
LOGGER.log(Level.FINE, LocalizationMessages.PARSING_ERROR(), obtainPartsError);
message.close();
throw obtainPartsError;
}
}
private static MediaType unquoteMediaTypeParameters(final MediaType mediaType, final String... parameters) {
if (parameters == null || parameters.length == 0) {
return mediaType;
}
final Map<String, String> unquotedParams = new HashMap<>(mediaType.getParameters());
for (final String parameter : parameters) {
String value = mediaType.getParameters().get(parameter);
if (value != null && value.startsWith("\"")) {
value = value.substring(1, value.length() - 1);
unquotedParams.put(parameter, value);
}
}
return new MediaType(mediaType.getType(), mediaType.getSubtype(), unquotedParams);
}
}