下面列出了org.apache.http.client.entity.GzipDecompressingEntity#org.apache.http.client.entity.EntityBuilder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public CompletableFuture<Boolean> createUser(User user) {
try {
byte[] bytes = objectMapper.writeValueAsBytes(user);
HttpPost request = new HttpPost(URL_CREATE_USER);
HttpEntity entity = EntityBuilder.create().setBinary(bytes).build();
request.setEntity(entity);
CloseableHttpResponse response = client.execute(request);
String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
return CompletableFuture.completedFuture("true".equals(result));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Benchmark
public void test(Blackhole bh) {
String body = "{\"name\":\"ppdai\"}";
String url = "http://localhost:" + port + "/raptor/com.ppdai.framework.raptor.proto.Simple/sayHello";
HttpUriRequest request = RequestBuilder.post(url)
.addHeader("connection", "Keep-Alive")
.setEntity(EntityBuilder.create().setText(body).setContentType(ContentType.APPLICATION_JSON).build())
.build();
String responseBody;
try (CloseableHttpResponse response = httpClient.execute(request)) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(100);
response.getEntity().writeTo(bos);
responseBody = new String(bos.toByteArray(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("error", e);
}
bh.consume(responseBody);
}
@Benchmark
public void test(Blackhole bh) {
String body = "{\"name\":\"ppdai\"}";
String url = "http://localhost:" + port + "/raptor/com.ppdai.framework.raptor.proto.Simple/sayHello";
HttpUriRequest request = RequestBuilder.post(url)
.addHeader("connection", "Keep-Alive")
.setEntity(EntityBuilder.create().setText(body).setContentType(ContentType.APPLICATION_JSON).build())
.build();
String responseBody;
try (CloseableHttpResponse response = httpClient.execute(request)) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(100);
response.getEntity().writeTo(bos);
responseBody = new String(bos.toByteArray(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("error", e);
}
bh.consume(responseBody);
}
public void updateTransport(Transport transport) throws IOException, URISyntaxException, ODataException, UnexpectedHttpResponseException
{
Edm edm = getEntityDataModel();
try (CloseableHttpClient client = clientFactory.createClient()) {
HttpPut put = requestBuilder.updateTransport(transport.getTransportID());
put.setHeader("x-csrf-token", getCSRFToken());
EdmEntityContainer entityContainer = edm.getDefaultEntityContainer();
EdmEntitySet entitySet = entityContainer.getEntitySet(TransportRequestBuilder.getEntityKey());
URI rootUri = new URI(endpoint.toASCIIString() + "/");
EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(rootUri).build();
ODataResponse response = null;
try {
response = EntityProvider.writeEntry(put.getHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue(), entitySet,transport.getValueMap(), properties);
put.setEntity(EntityBuilder.create().setStream(response.getEntityAsStream()).build());
try (CloseableHttpResponse httpResponse = client.execute(put)) {
hasStatusOrFail(httpResponse, SC_OK, HttpStatus.SC_NO_CONTENT);
}
} finally {
if(response != null) response.close();
}
}
}
public Transport createTransport(Map<String, Object> transport) throws IOException, URISyntaxException, ODataException, UnexpectedHttpResponseException
{
try (CloseableHttpClient client = clientFactory.createClient()) {
HttpPost post = requestBuilder.createTransport();
post.setHeader("x-csrf-token", getCSRFToken());
EdmEntityContainer entityContainer = getEntityDataModel().getDefaultEntityContainer();
EdmEntitySet entitySet = entityContainer.getEntitySet(TransportRequestBuilder.getEntityKey());
URI rootUri = new URI(endpoint.toASCIIString() + "/");
EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(rootUri).build();
ODataResponse marshaller = null;
try {
marshaller = EntityProvider.writeEntry(post.getHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue(), entitySet, transport, properties);
post.setEntity(EntityBuilder.create().setStream(marshaller.getEntityAsStream()).build());
try(CloseableHttpResponse httpResponse = client.execute(post)) {
hasStatusOrFail(httpResponse, SC_CREATED);
return getTransport(httpResponse);
}
} finally {
if(marshaller != null) marshaller.close();
}
}
}
@Override
public boolean createUser(User user) {
try {
byte[] bytes = objectMapper.writeValueAsBytes(user);
HttpPost request = new HttpPost(URL_CREATE_USER);
HttpEntity entity = EntityBuilder.create().setBinary(bytes).build();
request.setEntity(entity);
CloseableHttpResponse response = client.execute(request);
String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
return "true".equals(result);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public boolean createUser(User user) {
try {
byte[] bytes = objectMapper.writeValueAsBytes(user);
HttpPost request = new HttpPost(URL_CREATE_USER);
HttpEntity entity = EntityBuilder.create().setBinary(bytes).build();
request.setEntity(entity);
CloseableHttpResponse response = client.execute(request);
String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
return "true".equals(result);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 采用Post方式发送请求,获取响应数据
*
* @param url url地址
* @param param 参数值键值对的字符串
* @return
*/
public static String httpPost(String url, String param) {
CloseableHttpClient client = HttpClientBuilder.create().build();
try {
HttpPost post = new HttpPost(url);
EntityBuilder builder = EntityBuilder.create();
builder.setContentType(ContentType.APPLICATION_JSON);
builder.setText(param);
post.setEntity(builder.build());
CloseableHttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
logger.info("状态:"+statusCode+"数据:"+data);
return data;
} catch(Exception e){
throw new RuntimeException(e.getMessage());
} finally {
try{
client.close();
}catch(Exception ex){ }
}
}
public static boolean enableWfs() throws ClientProtocolException, IOException {
final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
final CloseableHttpClient httpclient = clientAndContext.getLeft();
final HttpClientContext context = clientAndContext.getRight();
try {
final HttpPut command =
new HttpPut(
ServicesTestEnvironment.GEOSERVER_REST_PATH
+ "/services/wfs/workspaces/"
+ ServicesTestEnvironment.TEST_WORKSPACE
+ "/settings");
command.setHeader("Content-type", "text/xml");
command.setEntity(
EntityBuilder.create().setFile(
new File("src/test/resources/wfs-requests/wfs.xml")).setContentType(
ContentType.TEXT_XML).build());
final HttpResponse r = httpclient.execute(command, context);
return r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
} finally {
httpclient.close();
}
}
public static boolean enableWms() throws ClientProtocolException, IOException {
final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
final CloseableHttpClient httpclient = clientAndContext.getLeft();
final HttpClientContext context = clientAndContext.getRight();
try {
final HttpPut command =
new HttpPut(
ServicesTestEnvironment.GEOSERVER_REST_PATH
+ "/services/wms/workspaces/"
+ ServicesTestEnvironment.TEST_WORKSPACE
+ "/settings");
command.setHeader("Content-type", "text/xml");
command.setEntity(
EntityBuilder.create().setFile(
new File("src/test/resources/wfs-requests/wms.xml")).setContentType(
ContentType.TEXT_XML).build());
final HttpResponse r = httpclient.execute(command, context);
return r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
} finally {
httpclient.close();
}
}
public boolean createLayers() throws ClientProtocolException, IOException {
final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
final CloseableHttpClient httpclient = clientAndContext.getLeft();
final HttpClientContext context = clientAndContext.getRight();
try {
final HttpPost command =
new HttpPost(
ServicesTestEnvironment.GEOSERVER_REST_PATH
+ "/workspaces/"
+ ServicesTestEnvironment.TEST_WORKSPACE
+ "/datastores/"
+ dataStoreOptions.getGeoWaveNamespace()
+ "/featuretypes");
command.setHeader("Content-type", "text/xml");
command.setEntity(
EntityBuilder.create().setText(geostuff_layer).setContentType(
ContentType.TEXT_XML).build());
final HttpResponse r = httpclient.execute(command, context);
return r.getStatusLine().getStatusCode() == Status.CREATED.getStatusCode();
} finally {
httpclient.close();
}
}
public boolean queryPoint() throws Exception {
final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
final CloseableHttpClient httpclient = clientAndContext.getLeft();
final HttpClientContext context = clientAndContext.getRight();
try {
final HttpPost command = createWFSTransaction(httpclient, "1.1.0");
command.setEntity(
EntityBuilder.create().setText(query).setContentType(ContentType.TEXT_XML).build());
final HttpResponse r = httpclient.execute(command, context);
final boolean result = r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
if (result) {
final String content = getContent(r);
System.out.println(content);
final String patternX = "34.6815818";
final String patternY = "35.1828408";
// name space check as well
return content.contains(patternX)
&& content.contains(patternY)
&& content.contains(ServicesTestEnvironment.TEST_WORKSPACE + ":geometry");
}
return false;
} finally {
httpclient.close();
}
}
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
final HttpPut updatePageRequest = new HttpPut(
String.format(getURLBase() + PORTAL_UPDATE_PAGE_API, pageToUpdate.getId()));
updatePageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
final EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setContentType(ContentType.APPLICATION_JSON);
if(pageToUpdate.getProcessDefinitionId() != null) {
entityBuilder.setText(String.format("{\"pageZip\" : \"%s\", \"processDefinitionId\" : \"%s\" }", uploadedFileToken,pageToUpdate.getProcessDefinitionId()));
}else {
entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
}
updatePageRequest.setEntity(entityBuilder.build());
final HttpResponse response = httpClient.execute(updatePageRequest);
final int status = response.getStatusLine().getStatusCode();
String responseContent = contentAsString(response);
if (status != HttpURLConnection.HTTP_OK) {
throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
}
return responseContent;
}
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
final HttpPost addPageRequest = new HttpPost(getURLBase() + PORTAL_ADD_PAGE_API);
addPageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
final EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setContentType(ContentType.APPLICATION_JSON);
entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
addPageRequest.setEntity(entityBuilder.build());
final HttpResponse response = httpClient.execute(addPageRequest);
final int status = response.getStatusLine().getStatusCode();
String responseContent = contentAsString(response);
if (status != HttpURLConnection.HTTP_OK) {
throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
}
return responseContent;
}
@Test
public void testHttpPost() throws Exception {
URI postUri = new URIBuilder()
.setScheme("https")
.setHost(DOMAIN.split("//")[1])
.setPath("/datasync/id/" + UNITTEST_DATASET_ID)
.build();
InputStream is = new FileInputStream(new File("src/test/resources/example_patch.sdiff"));
byte[] data = IOUtils.toByteArray(is);
HttpEntity entity = EntityBuilder.create().setBinary(data).build();
try(CloseableHttpResponse response = http.post(postUri, entity);
InputStream body = response.getEntity().getContent()) {
// uncomment the test below, when di2 is running in prod
/*
TestCase.assertEquals(201, response.getStatusLine().getStatusCode());
String blobId = mapper.readValue(response.getEntity().getContent(), BlobId.class).blobId;
TestCase.assertNotNull(blobId);
*/
}
}
@Test
public void simplePost() throws Exception {
stubFor(post(urlEqualTo("/foo")).willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody("bar")));
try (HttpHandler handler = new HttpHandler(url, options)) {
HttpEntity entity = EntityBuilder.create().setText("baz").build();
HttpResponse response = handler.post("foo", entity);
try (Reader reader = new InputStreamReader(response.getEntity().getContent())) {
assertThat(CharStreams.toString(reader), is("bar"));
}
}
verify(postRequestedFor(urlEqualTo("/foo")).withRequestBody(equalTo("baz")));
}
/**
* parameters:
* name = value
* description=value
*
* @param project
* @param session
* @throws AppJointErrorException
*/
@Override
public Project createProject(Project project, Session session) throws AppJointErrorException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("action", "create"));
params.add(new BasicNameValuePair("name", project.getName()));
params.add(new BasicNameValuePair("description", project.getDescription()));
HttpPost httpPost = new HttpPost(projectUrl);
httpPost.addHeader(HTTP.CONTENT_ENCODING, HTTP.IDENTITY_CODING);
CookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(session.getCookies()[0]);
HttpEntity entity = EntityBuilder.create()
.setContentType(ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8))
.setParameters(params).build();
httpPost.setEntity(entity);
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
response = httpClient.execute(httpPost);
HttpEntity ent = response.getEntity();
String entStr = IOUtils.toString(ent.getContent(), "utf-8");
logger.error("新建工程 {}, azkaban 返回的信息是 {}", project.getName(), entStr);
String message = AzkabanUtils.handleAzkabanEntity(entStr);
if (!"success".equals(message)) {
throw new AppJointErrorException(90008, "新建工程失败, 原因:" + message);
}
} catch (Exception e) {
logger.error("创建工程失败:", e);
throw new AppJointErrorException(90009, e.getMessage(), e);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(httpClient);
}
return null;
}
/** Uploads the next byte chunk of the media item. */
private HttpResponse uploadNextChunk(String uploadUrl, long receivedByteCount)
throws IOException {
// Reads data from input stream
byte[] dataChunk = new byte[optimalChunkSize];
int readByteCount = request.readData(dataChunk);
// Avoid uploading the whole chunk when only a part of it contains data
if (readByteCount < optimalChunkSize) {
dataChunk = trimByteArray(dataChunk, readByteCount);
}
HttpPost httpPost = createAuthenticatedPostRequest(uploadUrl);
httpPost.addHeader(UPLOAD_PROTOCOL_HEADER, UPLOAD_PROTOCOL_VALUE);
if (receivedByteCount + readByteCount == request.getFileSize()) {
httpPost.addHeader(
UPLOAD_COMMAND_HEADER, String.join(",", UploadCommands.UPLOAD, UploadCommands.FINALIZE));
} else {
httpPost.addHeader(UPLOAD_COMMAND_HEADER, UploadCommands.UPLOAD);
}
httpPost.addHeader(UPLOAD_OFFSET_HEADER, String.valueOf(receivedByteCount));
httpPost.addHeader(UPLOAD_SIZE_HEADER, String.valueOf(readByteCount));
httpPost.setEntity(EntityBuilder.create().setBinary(dataChunk).build());
CloseableHttpClient httpClient =
HttpClientBuilder.create()
.useSystemProperties()
.setDefaultRequestConfig(getRequestConfig())
.build();
return httpClient.execute(httpPost);
}
public final ParamsSession addParams(Map paramsMap) throws UnsupportedEncodingException {
Objects.requireNonNull(paramsMap);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Iterator<Map.Entry<String, String>> iterator = paramsMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
EntityBuilder entityBuilder= (EntityBuilder) this.getProviderService().provider();
entityBuilder.setParameters(nameValuePairs);
return this;
}
private <T extends HttpEntityEnclosingRequestBase> void addJsonBody(Object jsonObject, T method) {
method.setEntity(
EntityBuilder.create()
.setText(GSON.toJson(jsonObject))
.setContentType(ContentType.APPLICATION_JSON)
.build()
);
}
public String httpPostRequest(String uriString, String extractedText) throws IOException {
URI uri = URI.create(uriString);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "text/plain");
HttpEntity reqEntity = EntityBuilder.create().setText(URLEncoder.encode(extractedText, "UTF-8")).build();
httpPost.setEntity(reqEntity);
String responseBody = httpClient.execute(httpPost, this.responseHandler);
return responseBody;
}
/**
* This is the usual http request builder most widely used using Apache Http Client. In case you want to build
* or prepare the requests differently, you can override this method.
*
* Please see the following request builder to handle file uploads.
* - BasicHttpClient#createFileUploadRequestBuilder(java.lang.String, java.lang.String, java.lang.String)
*
* You can override this method via @UseHttpClient(YourCustomHttpClient.class)
*
* @param httpUrl
* @param methodName
* @param reqBodyAsString
* @return
*/
public RequestBuilder createDefaultRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) {
RequestBuilder requestBuilder = RequestBuilder
.create(methodName)
.setUri(httpUrl);
if (reqBodyAsString != null) {
HttpEntity httpEntity = EntityBuilder.create()
.setContentType(APPLICATION_JSON)
.setText(reqBodyAsString)
.build();
requestBuilder.setEntity(httpEntity);
}
return requestBuilder;
}
public boolean createPoint() throws Exception {
final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
final CloseableHttpClient httpclient = clientAndContext.getLeft();
final HttpClientContext context = clientAndContext.getRight();
try {
final HttpPost command = createWFSTransaction(httpclient, "1.1.0");
command.setEntity(
EntityBuilder.create().setText(insert).setContentType(ContentType.TEXT_XML).build());
final HttpResponse r = httpclient.execute(command, context);
return r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
} finally {
httpclient.close();
}
}
public String lockPoint() throws Exception {
final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
final CloseableHttpClient httpclient = clientAndContext.getLeft();
final HttpClientContext context = clientAndContext.getRight();
try {
final HttpPost command = createWFSTransaction(httpclient, "1.1.0");
command.setEntity(
EntityBuilder.create().setText(lock).setContentType(ContentType.TEXT_XML).build());
final HttpResponse r = httpclient.execute(command, context);
final boolean result = r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
if (result) {
final String content = getContent(r);
final String pattern = "lockId=\"([^\"]+)\"";
// Create a Pattern object
final Pattern compiledPattern = Pattern.compile(pattern);
final Matcher matcher = compiledPattern.matcher(content);
if (matcher.find()) {
return matcher.group(1);
}
return content;
}
return null;
} finally {
httpclient.close();
}
}
/**
* Chunks up the signature patch file into ~4MB chunks and posts these to delta-importer-2
* @param patchStream an inputStream to the patch
* @param datasetId the 4x4 of the dataset being patched
* @return the list of blobIds corresponding to each successful post
*/
private List<String> postPatchBlobs(InputStream patchStream, String datasetId, int chunkSize) throws
IOException, URISyntaxException, HttpException {
updateStatus("Chunking and posting the diff", 0, false, "");
System.out.println("Creating the diff...");
URI postingPath = baseUri.setPath(datasyncPath + "/" + datasetId).build();
List<String> blobIds = new LinkedList<>();
byte[] bytes = new byte[chunkSize];
StatusLine statusLine;
int status;
int bytesRead;
while ((bytesRead = Utils.readChunk(patchStream, bytes, 0, bytes.length)) != -1) {
System.out.println("\tUploading " + bytesRead + " bytes of the diff");
byte[] chunk = bytesRead == bytes.length ? bytes : Arrays.copyOf(bytes, bytesRead);
HttpEntity entity = EntityBuilder.create().setBinary(chunk).build();
int retries = 0;
do {
try(CloseableHttpResponse response = http.post(postingPath, entity)) {
statusLine = response.getStatusLine();
status = statusLine.getStatusCode();
if (status != HttpStatus.SC_CREATED) {
retries += 1;
} else {
String blobId = mapper.readValue(response.getEntity().getContent(), BlobId.class).blobId;
blobIds.add(blobId);
}
}
} while (status != HttpStatus.SC_CREATED && retries < httpRetries);
//We hit the max number of retries without success and should throw an exception accordingly.
if (retries >= httpRetries) throw new HttpException(statusLine.toString());
updateStatus("Uploading file", 0, false, bytesRead + " bytes");
System.out.println("\tUploaded " + bytesRead + " bytes");
}
return blobIds;
}
/**
* Send a moveTo call to a remote machine
*
* @param place the four-tuple of the place we are heading to
* @param agent the MobileAgent that is moving
* @return status of operation including body if successful
*/
public EmissaryResponse outboundMoveTo(final String place, final IMobileAgent agent) {
String url = null;
// Move to actions can be load-balanced out to
// a virtual IP address:port if so configured
if (VIRTUAL_MOVETO_ADDR != null) {
url = VIRTUAL_MOVETO_PROTOCOL + "://" + VIRTUAL_MOVETO_ADDR + "/";
} else {
url = KeyManipulator.getServiceHostURL(place);
}
url += CONTEXT + "/MoveTo.action";
final HttpPost method = new HttpPost(url);
method.setHeader("Content-type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair(PLACE_NAME, place));
nvps.add(new BasicNameValuePair(MOVE_ERROR_COUNT, Integer.toString(agent.getMoveErrorCount())));
final DirectoryEntry[] iq = agent.getItineraryQueueItems();
for (int j = 0; j < iq.length; j++) {
nvps.add(new BasicNameValuePair(ITINERARY_ITEM, iq[j].getKey()));
}
try {
// This is an 8859_1 String
final String agentData = PayloadUtil.serializeToString(agent.getPayloadForTransport());
nvps.add(new BasicNameValuePair(AGENT_SERIAL, agentData));
} catch (IOException iox) {
// TODO This will probably need looked at when redoing the moveTo
logger.error("Cannot serialize agent data", iox);
BasicHttpResponse response =
new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Cannot serialize agent data");
response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build());
return new EmissaryResponse(response);
}
method.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName("8859_1")));
// Add a cookie to the outbound header if we are posting
// to the virtual IP for load balancing
if (VIRTUAL_MOVETO_ADDR != null) {
final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, KeyManipulator.getServiceClassname(place));
cookie.setDomain(VIRTUAL_MOVETO_ADDR.substring(0, VIRTUAL_MOVETO_ADDR.indexOf(":")));
cookie.setPath(COOKIE_PATH);
return send(method, cookie);
}
return send(method);
}
/**
* Handle the packaging and sending of an addPlaces call to a remote directory. Sends multiple keys on the same place
* with the same cost/quality and description if the description, cost and quality lists are only size 1. Uses a
* distinct description/cost/quality for each key when there are enough values
*
* @param parentDirectory the url portion of the parent directory location
* @param entryList the list of directory entries to add
* @param propagating true if going downstream
* @return status of operation
*/
public EmissaryResponse outboundAddPlaces(final String parentDirectory, final List<DirectoryEntry> entryList, final boolean propagating) {
if (disableAddPlaces) {
BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "Not accepting remote add places");
response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build());
return new EmissaryResponse(response);
} else {
final String parentDirectoryUrl = KeyManipulator.getServiceHostURL(parentDirectory);
final HttpPost method = new HttpPost(parentDirectoryUrl + CONTEXT + "/RegisterPlace.action");
final String parentLoc = KeyManipulator.getServiceLocation(parentDirectory);
// Separate it out into lists
final List<String> keyList = new ArrayList<String>();
final List<String> descList = new ArrayList<String>();
final List<Integer> costList = new ArrayList<Integer>();
final List<Integer> qualityList = new ArrayList<Integer>();
for (final DirectoryEntry d : entryList) {
keyList.add(d.getKey());
descList.add(d.getDescription());
costList.add(Integer.valueOf(d.getCost()));
qualityList.add(Integer.valueOf(d.getQuality()));
}
final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair(TARGET_DIRECTORY, parentLoc));
for (int count = 0; count < keyList.size(); count++) {
nvps.add(new BasicNameValuePair(ADD_KEY + count, keyList.get(count)));
// possibly use the single desc/cost/qual for each key
if (descList.size() > count) {
String desc = descList.get(count);
if (desc == null) {
desc = "No description provided";
}
nvps.add(new BasicNameValuePair(ADD_DESCRIPTION + count, desc));
}
if (costList.size() > count) {
nvps.add(new BasicNameValuePair(ADD_COST + count, costList.get(count).toString()));
}
if (qualityList.size() > count) {
nvps.add(new BasicNameValuePair(ADD_QUALITY + count, qualityList.get(count).toString()));
}
}
nvps.add(new BasicNameValuePair(ADD_PROPAGATION_FLAG, Boolean.toString(propagating)));
method.setEntity(new UrlEncodedFormEntity(nvps, Charset.defaultCharset()));
return send(method);
}
}
public EntityBuilder provider() {
this.entityBuilder= EntityBuilder.create();
return entityBuilder;
}
public ParamsSession(HttpEntityProviderService<EntityBuilder> providerService) {
super(providerService);
}
public static String postDocument(String baseUrl, String receiverAddress, String externalId, UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout){
String ret = null;
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder.setConnectTimeout(timeout);
requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
try (CloseableHttpClient httpClient = builder.build()) {
HttpPost httppost = new HttpPost(baseUrl+"submissions/"+receiverAddress+"/"+externalId);
//------------------------------------------------------------
EntityBuilder eBuilder = EntityBuilder.create();
eBuilder.setBinary(submission.getContent());
httppost.setEntity(eBuilder.build());
//------------------------------------------------------------
if(StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
addAuthorization(httppost, urkundUsername, urkundPassword);
}
//------------------------------------------------------------
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-Type", submission.getMimeType());
httppost.addHeader("Accept-Language", submission.getLanguage());
httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
httppost.addHeader("x-urkund-subject", submission.getSubject());
httppost.addHeader("x-urkund-message", submission.getMessage());
//------------------------------------------------------------
HttpResponse response = httpClient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
ret = EntityUtils.toString(resEntity);
EntityUtils.consume(resEntity);
}
} catch (IOException e) {
log.error("ERROR uploading File : ", e);
}
return ret;
}