use of javax.ws.rs.core.MultivaluedMap in project pentaho-kettle by pentaho.
the class Rest method callRest.
protected Object[] callRest(Object[] rowData) throws KettleException {
// get dynamic url ?
if (meta.isUrlInField()) {
data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField);
}
// get dynamic method?
if (meta.isDynamicMethod()) {
data.method = data.inputRowMeta.getString(rowData, data.indexOfMethod);
if (Utils.isEmpty(data.method)) {
throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.MethodMissing"));
}
}
WebResource webResource = null;
Client client = null;
Object[] newRow = null;
if (rowData != null) {
newRow = rowData.clone();
}
try {
if (isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "Rest.Log.ConnectingToURL", data.realUrl));
}
// Register a custom StringMessageBodyWriter to solve PDI-17423
MessageBodyWriter<String> stringMessageBodyWriter = new StringMessageBodyWriter();
data.config.getSingletons().add(stringMessageBodyWriter);
// create an instance of the com.sun.jersey.api.client.Client class
client = ApacheHttpClient4.create(data.config);
if (data.basicAuthentication != null) {
client.addFilter(data.basicAuthentication);
}
// create a WebResource object, which encapsulates a web resource for the client
webResource = client.resource(data.realUrl);
// used for calculating the responseTime
long startTime = System.currentTimeMillis();
if (data.useMatrixParams) {
// Add matrix parameters
UriBuilder builder = webResource.getUriBuilder();
for (int i = 0; i < data.nrMatrixParams; i++) {
String value = data.inputRowMeta.getString(rowData, data.indexOfMatrixParamFields[i]);
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "Rest.Log.matrixParameterValue", data.matrixParamNames[i], value));
}
builder = builder.matrixParam(data.matrixParamNames[i], UriComponent.encode(value, UriComponent.Type.QUERY_PARAM));
}
webResource = client.resource(builder.build());
}
if (data.useParams) {
// Add query parameters
for (int i = 0; i < data.nrParams; i++) {
String value = data.inputRowMeta.getString(rowData, data.indexOfParamFields[i]);
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "Rest.Log.queryParameterValue", data.paramNames[i], value));
}
webResource = webResource.queryParams(createMultivalueMap(data.paramNames[i], value));
}
}
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "Rest.Log.ConnectingToURL", webResource.getURI()));
}
WebResource.Builder builder = webResource.getRequestBuilder();
// media type override, if not null
String contentType = null;
if (data.useHeaders) {
// Add headers
for (int i = 0; i < data.nrheader; i++) {
String value = data.inputRowMeta.getString(rowData, data.indexOfHeaderFields[i]);
// unsure if an already set header will be returned to builder
builder = builder.header(data.headerNames[i], value);
if ("Content-Type".equals(data.headerNames[i])) {
contentType = value;
}
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "Rest.Log.HeaderValue", data.headerNames[i], value));
}
}
}
ClientResponse response = null;
String entityString = null;
if (data.useBody) {
// Set Http request entity
entityString = Const.NVL(data.inputRowMeta.getString(rowData, data.indexOfBodyField), null);
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "Rest.Log.BodyValue", entityString));
}
}
try {
if (data.method.equals(RestMeta.HTTP_METHOD_GET)) {
response = builder.get(ClientResponse.class);
} else if (data.method.equals(RestMeta.HTTP_METHOD_POST)) {
if (null != contentType) {
response = builder.type(contentType).post(ClientResponse.class, entityString);
} else {
response = builder.type(data.mediaType).post(ClientResponse.class, entityString);
}
} else if (data.method.equals(RestMeta.HTTP_METHOD_PUT)) {
if (null != contentType) {
response = builder.type(contentType).put(ClientResponse.class, entityString);
} else {
response = builder.type(data.mediaType).put(ClientResponse.class, entityString);
}
} else if (data.method.equals(RestMeta.HTTP_METHOD_DELETE)) {
response = builder.delete(ClientResponse.class);
} else if (data.method.equals(RestMeta.HTTP_METHOD_HEAD)) {
response = builder.head();
} else if (data.method.equals(RestMeta.HTTP_METHOD_OPTIONS)) {
response = builder.options(ClientResponse.class);
} else if (data.method.equals(RestMeta.HTTP_METHOD_PATCH)) {
if (null != contentType) {
response = builder.type(contentType).method(RestMeta.HTTP_METHOD_PATCH, ClientResponse.class, entityString);
} else {
response = builder.type(data.mediaType).method(RestMeta.HTTP_METHOD_PATCH, ClientResponse.class, entityString);
}
} else {
throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.UnknownMethod", data.method));
}
} catch (UniformInterfaceException u) {
response = u.getResponse();
}
// Get response time
long responseTime = System.currentTimeMillis() - startTime;
if (isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "Rest.Log.ResponseTime", String.valueOf(responseTime), data.realUrl));
}
// Get status
int status = response.getStatus();
// Display status code
if (isDebug()) {
logDebug(BaseMessages.getString(PKG, "Rest.Log.ResponseCode", "" + status));
}
// Get Response
String body;
String headerString = null;
try {
body = response.getEntity(String.class);
} catch (UniformInterfaceException ex) {
body = "";
}
// get Header
MultivaluedMap<String, String> headers = searchForHeaders(response);
JSONObject json = new JSONObject();
for (java.util.Map.Entry<String, List<String>> entry : headers.entrySet()) {
String name = entry.getKey();
List<String> value = entry.getValue();
if (value.size() > 1) {
json.put(name, value);
} else {
json.put(name, value.get(0));
}
}
headerString = json.toJSONString();
// for output
int returnFieldsOffset = data.inputRowMeta.size();
// add response to output
if (!Utils.isEmpty(data.resultFieldName)) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
returnFieldsOffset++;
}
// add status to output
if (!Utils.isEmpty(data.resultCodeFieldName)) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(status));
returnFieldsOffset++;
}
// add response time to output
if (!Utils.isEmpty(data.resultResponseFieldName)) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
returnFieldsOffset++;
}
// add response header to output
if (!Utils.isEmpty(data.resultHeaderFieldName)) {
newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, headerString);
}
} catch (Exception e) {
throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.CanNotReadURL", data.realUrl), e);
} finally {
if (webResource != null) {
webResource = null;
}
if (client != null) {
client.destroy();
}
}
return newRow;
}
use of javax.ws.rs.core.MultivaluedMap in project kylo by Teradata.
the class AlertsController method createCriteria.
private AlertCriteria createCriteria(UriInfo uriInfo) {
// Query params: limit, state, level, before-time, after-time, before-alert, after-alert
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
AlertCriteria criteria = provider.criteria();
try {
Optional.ofNullable(params.get("type")).ifPresent(list -> list.forEach(typeStr -> criteria.type(URI.create(typeStr))));
Optional.ofNullable(params.get("subtype")).ifPresent(list -> list.forEach(subtype -> criteria.subtype(subtype)));
Optional.ofNullable(params.get("limit")).ifPresent(list -> list.forEach(limitStr -> criteria.limit(Integer.parseInt(limitStr))));
Optional.ofNullable(params.get("state")).ifPresent(list -> list.forEach(stateStr -> criteria.state(Alert.State.valueOf(stateStr.toUpperCase()))));
Optional.ofNullable(params.get("level")).ifPresent(list -> list.forEach(levelStr -> criteria.level(Alert.Level.valueOf(levelStr.toUpperCase()))));
Optional.ofNullable(params.get("before")).ifPresent(list -> list.forEach(timeStr -> criteria.before(Formatters.parseDateTime(timeStr))));
Optional.ofNullable(params.get("after")).ifPresent(list -> list.forEach(timeStr -> criteria.after(Formatters.parseDateTime(timeStr))));
return criteria;
} catch (IllegalArgumentException e) {
throw new WebApplicationException("Invalid query parameter: " + e.getMessage(), Status.BAD_REQUEST);
}
}
use of javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
the class ResponseWriter method writeResponseStatusAndHeaders.
@Override
public OutputStream writeResponseStatusAndHeaders(final long contentLength, final ContainerResponse responseContext) throws ContainerException {
this.responseContext.complete(responseContext);
// first set the content length, so that if headers have an explicit value, it takes precedence over this one
if (responseContext.hasEntity() && contentLength != -1 && contentLength < Integer.MAX_VALUE) {
response.setContentLength((int) contentLength);
}
// Note that the writing of headers MUST be performed before
// the invocation of sendError as on some Servlet implementations
// modification of the response headers will have no effect
// after the invocation of sendError.
final MultivaluedMap<String, String> headers = getResponseContext().getStringHeaders();
for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
final Iterator<String> it = e.getValue().iterator();
if (!it.hasNext()) {
continue;
}
final String header = e.getKey();
if (response.containsHeader(header)) {
// replace any headers previously set with values from Jersey container response.
response.setHeader(header, it.next());
}
while (it.hasNext()) {
response.addHeader(header, it.next());
}
}
final String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
if (reasonPhrase != null) {
response.setStatus(responseContext.getStatus(), reasonPhrase);
} else {
response.setStatus(responseContext.getStatus());
}
if (!responseContext.hasEntity()) {
return null;
} else {
try {
final OutputStream outputStream = response.getOutputStream();
// so that any Servlet filters in the chain can still write to the response after us.
return new NonCloseableOutputStreamWrapper(outputStream);
} catch (final IOException e) {
throw new ContainerException(e);
}
}
}
use of javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
the class MultiPartReaderClientSide method readMultiPart.
protected MultiPart readMultiPart(final Class<MultiPart> type, final Type genericType, final Annotation[] annotations, MediaType mediaType, final MultivaluedMap<String, String> headers, final InputStream stream) throws IOException, MIMEParsingException {
mediaType = unquoteMediaTypeParameters(mediaType, "boundary");
final MIMEMessage mimeMessage = new MIMEMessage(stream, mediaType.getParameters().get("boundary"), mimeConfig);
final boolean formData = MediaTypes.typeEqual(mediaType, MediaType.MULTIPART_FORM_DATA_TYPE);
final MultiPart multiPart = formData ? new FormDataMultiPart() : new MultiPart();
final MessageBodyWorkers workers = messageBodyWorkers.get();
multiPart.setMessageBodyWorkers(workers);
final MultivaluedMap<String, String> multiPartHeaders = multiPart.getHeaders();
for (final Map.Entry<String, List<String>> entry : headers.entrySet()) {
final List<String> values = entry.getValue();
for (final String value : values) {
multiPartHeaders.add(entry.getKey(), value);
}
}
final boolean fileNameFix;
if (!formData) {
multiPart.setMediaType(mediaType);
fileNameFix = false;
} else {
// see if the User-Agent header corresponds to some version of MS Internet Explorer
// if so, need to set fileNameFix to true to handle issue http://java.net/jira/browse/JERSEY-759
final String userAgent = headers.getFirst(HttpHeaders.USER_AGENT);
fileNameFix = userAgent != null && userAgent.contains(" MSIE ");
}
for (final MIMEPart mimePart : getMimeParts(mimeMessage)) {
final BodyPart bodyPart = formData ? new FormDataBodyPart(fileNameFix) : new BodyPart();
// Configure providers.
bodyPart.setMessageBodyWorkers(workers);
// Copy headers.
for (final Header header : mimePart.getAllHeaders()) {
bodyPart.getHeaders().add(header.getName(), header.getValue());
}
try {
final String contentType = bodyPart.getHeaders().getFirst("Content-Type");
if (contentType != null) {
bodyPart.setMediaType(MediaType.valueOf(contentType));
}
bodyPart.getContentDisposition();
} catch (final IllegalArgumentException ex) {
throw new BadRequestException(ex);
}
// Copy data into a BodyPartEntity structure.
bodyPart.setEntity(new BodyPartEntity(mimePart));
// Add this BodyPart to our MultiPart.
multiPart.getBodyParts().add(bodyPart);
}
return multiPart;
}
use of javax.ws.rs.core.MultivaluedMap in project jersey by jersey.
the class FeedEntriesAtomBodyWriter method writeTo.
@Override
public void writeTo(List<FeedEntry> entries, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
List<SyndEntry> syndEntries = entries.parallelStream().map(entry -> {
SyndContent description = new SyndContentImpl();
description.setType(MediaType.TEXT_PLAIN);
description.setValue(entry.getDescription());
SyndEntry syndEntry = new SyndEntryImpl();
syndEntry.setTitle(entry.getTitle());
syndEntry.setLink(entry.getLink());
syndEntry.setPublishedDate(entry.getPublishDate());
syndEntry.setDescription(description);
return syndEntry;
}).collect(Collectors.toList());
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("atom_1.0");
feed.setTitle("Combined Feed");
feed.setDescription("Combined Feed created by a feed-combiner application");
feed.setPublishedDate(new Date());
feed.setEntries(syndEntries);
writeSyndFeed(entityStream, feed);
}
Aggregations