use of org.apache.http.entity.mime.FormBodyPart in project jackrabbit by apache.
the class Utils method addPart.
/**
*
* @param paramName
* @param value
* @param resolver
* @throws RepositoryException
*/
static void addPart(String paramName, QValue value, NamePathResolver resolver, List<FormBodyPart> parts, List<QValue> binaries) throws RepositoryException {
FormBodyPartBuilder builder = FormBodyPartBuilder.create().setName(paramName);
ContentType ctype = ContentType.create(JcrValueType.contentTypeFromType(value.getType()), DEFAULT_CHARSET);
FormBodyPart part;
switch(value.getType()) {
case PropertyType.BINARY:
binaries.add(value);
part = builder.setBody(new InputStreamBody(value.getStream(), ctype)).build();
break;
case PropertyType.NAME:
part = builder.setBody(new StringBody(resolver.getJCRName(value.getName()), ctype)).build();
break;
case PropertyType.PATH:
part = builder.setBody(new StringBody(resolver.getJCRPath(value.getPath()), ctype)).build();
break;
default:
part = builder.setBody(new StringBody(value.getString(), ctype)).build();
}
parts.add(part);
}
use of org.apache.http.entity.mime.FormBodyPart in project jmeter by apache.
the class HTTPHC4Impl method sendPostData.
// TODO needs cleaning up
/**
*
* @param post {@link HttpPost}
* @return String posted body if computable
* @throws IOException if sending the data fails due to I/O
*/
protected String sendPostData(HttpPost post) throws IOException {
// Buffer to hold the post body, except file content
StringBuilder postedBody = new StringBuilder(1000);
HTTPFileArg[] files = getHTTPFiles();
final String contentEncoding = getContentEncodingOrNull();
final boolean haveContentEncoding = contentEncoding != null;
// application/x-www-form-urlencoded post request
if (getUseMultipartForPost()) {
// If a content encoding is specified, we use that as the
// encoding of any parameter values
Charset charset = null;
if (haveContentEncoding) {
charset = Charset.forName(contentEncoding);
} else {
charset = MIME.DEFAULT_CHARSET;
}
if (log.isDebugEnabled()) {
log.debug("Building multipart with:getDoBrowserCompatibleMultipart(): {}, with charset:{}, haveContentEncoding:{}", getDoBrowserCompatibleMultipart(), charset, haveContentEncoding);
}
// Write the request to our own stream
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);
if (getDoBrowserCompatibleMultipart()) {
multipartEntityBuilder.setLaxMode();
} else {
multipartEntityBuilder.setStrictMode();
}
// Add any parameters
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
String parameterName = arg.getName();
if (arg.isSkippable(parameterName)) {
continue;
}
StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset));
FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
multipartEntityBuilder.addPart(formPart);
}
// Add any files
// Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
for (int i = 0; i < files.length; i++) {
HTTPFileArg file = files[i];
File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType());
multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
}
HttpEntity entity = multipartEntityBuilder.build();
post.setEntity(entity);
if (entity.isRepeatable()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (ViewableFileBody fileBody : fileBodies) {
fileBody.hideFileData = true;
}
entity.writeTo(bos);
for (ViewableFileBody fileBody : fileBodies) {
fileBody.hideFileData = false;
}
bos.flush();
// We get the posted bytes using the encoding used to create it
postedBody.append(bos.toString(// $NON-NLS-1$ this is the default used by HttpClient
contentEncoding == null ? // $NON-NLS-1$ this is the default used by HttpClient
"US-ASCII" : contentEncoding));
bos.close();
} else {
// $NON-NLS-1$
postedBody.append("<Multipart was not repeatable, cannot view what was sent>");
}
// // Set the content type TODO - needed?
// String multiPartContentType = multiPart.getContentType().getValue();
// post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType);
} else {
// not multipart
// Check if the header manager had a content type header
// This allows the user to specify his own content-type for a POST request
Header contentTypeHeader = post.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0;
// TODO: needs a multiple file upload scenerio
if (!hasArguments() && getSendFileAsPostBody()) {
// If getSendFileAsPostBody returned true, it's sure that file is not null
HTTPFileArg file = files[0];
if (!hasContentTypeHeader) {
// Allow the mimetype of the file to control the content type
if (file.getMimeType() != null && file.getMimeType().length() > 0) {
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
} else {
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
// TODO is null correct?
FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);
post.setEntity(fileRequestEntity);
// We just add placeholder text for file content
postedBody.append("<actual file content, not shown here>");
} else {
// the post body will be encoded in the specified content encoding
if (haveContentEncoding) {
post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding);
}
// just send all the values as the post body
if (getSendParameterValuesAsPostBody()) {
// TODO: needs a multiple file upload scenerio
if (!hasContentTypeHeader) {
HTTPFileArg file = files.length > 0 ? files[0] : null;
if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
} else {
// TODO - is this the correct default?
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
// Just append all the parameter values, and use that as the post body
StringBuilder postBody = new StringBuilder();
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
// Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
if (haveContentEncoding) {
postBody.append(arg.getEncodedValue(contentEncoding));
} else {
postBody.append(arg.getEncodedValue());
}
}
// Let StringEntity perform the encoding
StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
post.setEntity(requestEntity);
postedBody.append(postBody.toString());
} else {
// Set the content type
if (!hasContentTypeHeader) {
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
// Add the parameters
PropertyIterator args = getArguments().iterator();
List<NameValuePair> nvps = new ArrayList<>();
String urlContentEncoding = contentEncoding;
if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
// Use the default encoding for urls
urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
}
while (args.hasNext()) {
HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
// The HTTPClient always urlencodes both name and value,
// so if the argument is already encoded, we have to decode
// it before adding it to the post request
String parameterName = arg.getName();
if (arg.isSkippable(parameterName)) {
continue;
}
String parameterValue = arg.getValue();
if (!arg.isAlwaysEncoded()) {
// The value is already encoded by the user
// Must decode the value now, so that when the
// httpclient encodes it, we end up with the same value
// as the user had entered.
parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
}
// Add the parameter, httpclient will urlencode it
nvps.add(new BasicNameValuePair(parameterName, parameterValue));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding);
post.setEntity(entity);
if (entity.isRepeatable()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
post.getEntity().writeTo(bos);
bos.flush();
// We get the posted bytes using the encoding used to create it
postedBody.append(bos.toString(contentEncoding != null ? contentEncoding : SampleResult.DEFAULT_HTTP_ENCODING));
bos.close();
} else {
postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
}
}
}
}
return postedBody.toString();
}
use of org.apache.http.entity.mime.FormBodyPart in project lucene-solr by apache.
the class HttpSolrClient method createMethod.
protected HttpRequestBase createMethod(final SolrRequest request, String collection) throws IOException, SolrServerException {
SolrParams params = request.getParams();
Collection<ContentStream> streams = requestWriter.getContentStreams(request);
String path = requestWriter.getPath(request);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = request.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
if (parser != null) {
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
}
if (invariantParams != null) {
wparams.add(invariantParams);
}
String basePath = baseUrl;
if (collection != null)
basePath += "/" + collection;
if (request instanceof V2Request) {
if (System.getProperty("solr.v2RealPath") == null) {
basePath = baseUrl.replace("/solr", "/v2");
} else {
basePath = baseUrl + "/____v2";
}
}
if (SolrRequest.METHOD.GET == request.getMethod()) {
if (streams != null) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
}
return new HttpGet(basePath + path + wparams.toQueryString());
}
if (SolrRequest.METHOD.DELETE == request.getMethod()) {
return new HttpDelete(basePath + path + wparams.toQueryString());
}
if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) {
String url = basePath + path;
boolean hasNullStreamName = false;
if (streams != null) {
for (ContentStream cs : streams) {
if (cs.getName() == null) {
hasNullStreamName = true;
break;
}
}
}
boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod()) || (streams != null && streams.size() > 1)) && !hasNullStreamName;
LinkedList<NameValuePair> postOrPutParams = new LinkedList<>();
if (streams == null || isMultipart) {
// send server list and request list as query string params
ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams);
queryParams.add(calculateQueryParams(request.getQueryParams(), wparams));
String fullQueryUrl = url + queryParams.toQueryString();
HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
if (!isMultipart) {
postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
}
List<FormBodyPart> parts = new LinkedList<>();
Iterator<String> iter = wparams.getParameterNamesIterator();
while (iter.hasNext()) {
String p = iter.next();
String[] vals = wparams.getParams(p);
if (vals != null) {
for (String v : vals) {
if (isMultipart) {
parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
} else {
postOrPutParams.add(new BasicNameValuePair(p, v));
}
}
}
}
// TODO: remove deprecated - first simple attempt failed, see {@link MultipartEntityBuilder}
if (isMultipart && streams != null) {
for (ContentStream content : streams) {
String contentType = content.getContentType();
if (contentType == null) {
// default
contentType = BinaryResponseParser.BINARY_CONTENT_TYPE;
}
String name = content.getName();
if (name == null) {
name = "";
}
parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName())));
}
}
if (parts.size() > 0) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
for (FormBodyPart p : parts) {
entity.addPart(p);
}
postOrPut.setEntity(entity);
} else {
//not using multipart
postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8));
}
return postOrPut;
} else // It is has one stream, it is the post body, put the params in the URL
{
String fullQueryUrl = url + wparams.toQueryString();
HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
// Single stream as body
// Using a loop just to get the first one
final ContentStream[] contentStream = new ContentStream[1];
for (ContentStream content : streams) {
contentStream[0] = content;
break;
}
if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
Long size = contentStream[0].getSize();
postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
} else {
Long size = contentStream[0].getSize();
postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
}
return postOrPut;
}
}
throw new SolrServerException("Unsupported method: " + request.getMethod());
}
Aggregations