1 package com.kodexa.client.store; 2 3 import com.kodexa.client.KodexaException; 4 import com.kodexa.client.registry.SourceRegistry; 5 import com.kodexa.client.remote.AbstractKodexaConnection; 6 import com.kodexa.client.remote.CloudExecution; 7 import com.kodexa.client.remote.KodexaPlatform; 8 import lombok.SneakyThrows; 9 import lombok.extern.slf4j.Slf4j; 10 import org.apache.commons.io.IOUtils; 11 import org.apache.http.HttpResponse; 12 import org.apache.http.client.methods.HttpPost; 13 import org.apache.http.client.utils.URLEncodedUtils; 14 import org.apache.http.entity.ContentType; 15 import org.apache.http.entity.mime.HttpMultipartMode; 16 import org.apache.http.entity.mime.MultipartEntityBuilder; 17 import org.apache.http.entity.mime.content.ByteArrayBody; 18 import org.apache.http.entity.mime.content.StringBody; 19 import org.apache.http.impl.client.CloseableHttpClient; 20 import org.apache.http.impl.client.HttpClientBuilder; 21 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.net.URI; 25 import java.net.URLEncoder; 26 import java.nio.charset.StandardCharsets; 27 import java.nio.file.FileAlreadyExistsException; 28 29 @Slf4j 30 public class RemoteDocumentStore extends AbstractKodexaConnection { 31 32 private final String ref; 33 34 public RemoteDocumentStore(String ref) { 35 this.ref = ref; 36 } 37 38 @SneakyThrows 39 public void putNative(String path, InputStream content) throws FileAlreadyExistsException { 40 try (CloseableHttpClient client = HttpClientBuilder.create() 41 .setDefaultRequestConfig(getRequestConfig()) 42 .build()) { 43 44 URI uri = URI.create(KodexaPlatform.getUrl() + "/api/stores/" + this.ref.replace(":", "/") + "/fs/"); 45 URI fullUri = new URI(uri.getScheme(), uri.getHost(), uri.getPath() + path, null); 46 log.info("Connecting to [" + fullUri + "]"); 47 HttpPost post = new HttpPost(fullUri); 48 post.addHeader("x-access-token", KodexaPlatform.getAccessToken()); 49 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 50 ByteArrayBody fileBody = new ByteArrayBody(IOUtils.toByteArray(content), path); 51 builder.addPart("file", fileBody); 52 post.setEntity(builder.build()); 53 HttpResponse response = client.execute(post); 54 if (response.getStatusLine().getStatusCode() != 200) { 55 if (response.getStatusLine().getStatusCode() == 400) { 56 throw new FileAlreadyExistsException("There is already a document family at path [" + path + "]"); 57 } else { 58 throw new KodexaException("Unable to create a session, check your access token and URL [" + response.getStatusLine().getStatusCode() + "]"); 59 } 60 } 61 log.info("Upload complete"); 62 } 63 } 64 }