|
| 1 | +package org.devlive.lightcall.handler; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | +import okhttp3.MediaType; |
| 6 | +import okhttp3.MultipartBody; |
| 7 | +import okhttp3.RequestBody; |
| 8 | +import org.devlive.lightcall.RequestContext; |
| 9 | +import org.devlive.lightcall.RequestException; |
| 10 | +import org.devlive.lightcall.annotation.Part; |
| 11 | + |
| 12 | +import java.io.File; |
| 13 | +import java.lang.reflect.Parameter; |
| 14 | + |
| 15 | +@Slf4j |
| 16 | +public class PartHandler |
| 17 | + implements ParameterHandler |
| 18 | +{ |
| 19 | + private final RequestContext context; |
| 20 | + |
| 21 | + private PartHandler(RequestContext context) |
| 22 | + { |
| 23 | + this.context = context; |
| 24 | + } |
| 25 | + |
| 26 | + public static PartHandler create(RequestContext context) |
| 27 | + { |
| 28 | + if (context == null) { |
| 29 | + throw new NullPointerException("RequestContext cannot be null"); |
| 30 | + } |
| 31 | + |
| 32 | + log.debug("Creating PartHandler"); |
| 33 | + return new PartHandler(context); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public boolean canHandle(Parameter parameter) |
| 38 | + { |
| 39 | + return parameter.isAnnotationPresent(Part.class); |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public String handle(Parameter parameter, Object arg, String path) |
| 44 | + { |
| 45 | + if (arg == null) { |
| 46 | + throw new IllegalArgumentException("Part file cannot be null"); |
| 47 | + } |
| 48 | + |
| 49 | + if (!(arg instanceof File)) { |
| 50 | + throw new IllegalArgumentException("Parameter annotated with @Part must be a File"); |
| 51 | + } |
| 52 | + |
| 53 | + Part partAnnotation = parameter.getAnnotation(Part.class); |
| 54 | + File file = (File) arg; |
| 55 | + |
| 56 | + MultipartBody.Builder multipartBuilder = new MultipartBody.Builder() |
| 57 | + .setType(MultipartBody.FORM); |
| 58 | + |
| 59 | + RequestBody fileBody = RequestBody.create( |
| 60 | + file, |
| 61 | + MediaType.parse("application/octet-stream") |
| 62 | + ); |
| 63 | + |
| 64 | + multipartBuilder.addFormDataPart( |
| 65 | + partAnnotation.value(), |
| 66 | + file.getName(), |
| 67 | + fileBody |
| 68 | + ); |
| 69 | + |
| 70 | + try { |
| 71 | + context.setBody(multipartBuilder.build(), MultipartBody.FORM); |
| 72 | + } |
| 73 | + catch (JsonProcessingException e) { |
| 74 | + throw new RequestException("Failed to set form part", e); |
| 75 | + } |
| 76 | + |
| 77 | + log.debug("Added file part {}: {}", partAnnotation.value(), file.getName()); |
| 78 | + |
| 79 | + return path; |
| 80 | + } |
| 81 | +} |
0 commit comments