co.easimart.EasimartRESTFileCommand Maven / Gradle / Ivy
package co.easimart;
/**
* REST network command for creating & uploading {@link EasimartFile}s.
*/
import co.easimart.http.EasimartHttpBody;
import co.easimart.http.EasimartHttpRequest;
import java.io.File;
/** package */ class EasimartRESTFileCommand extends EasimartRESTCommand {
public static class Builder extends Init {
private byte[] data = null;
private String contentType = null;
private File file;
public Builder() {
// We only ever use EasimartRESTFileCommand for file uploads, so default to POST.
method(EasimartHttpRequest.Method.POST);
}
public Builder fileName(String fileName) {
return httpPath(String.format("files/%s", fileName));
}
public Builder data(byte[] data) {
this.data = data;
return this;
}
public Builder contentType(String contentType) {
this.contentType = contentType;
return this;
}
public Builder file(File file) {
this.file = file;
return this;
}
@Override
/* package */ Builder self() {
return this;
}
public EasimartRESTFileCommand build() {
return new EasimartRESTFileCommand(this);
}
}
private final byte[] data;
private final String contentType;
private final File file;
public EasimartRESTFileCommand(Builder builder) {
super(builder);
if (builder.file != null && builder.data != null) {
throw new IllegalArgumentException("File and data can not be set at the same time");
}
this.data = builder.data;
this.contentType = builder.contentType;
this.file = builder.file;
}
@Override
protected EasimartHttpBody newBody(final ProgressCallback progressCallback) {
// TODO(mengyan): Delete EasimartByteArrayHttpBody when we change input byte array to staged file
// in EasimartFileController
if (progressCallback == null) {
return data != null ?
new EasimartByteArrayHttpBody(data, contentType) : new EasimartFileHttpBody(file, contentType);
}
return data != null ?
new EasimartCountingByteArrayHttpBody(data, contentType, progressCallback) :
new EasimartCountingFileHttpBody(file, contentType, progressCallback);
}
}