Search in sources :

Example 76 with MultivaluedMap

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;
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) KettleException(org.pentaho.di.core.exception.KettleException) WebResource(com.sun.jersey.api.client.WebResource) UniformInterfaceException(com.sun.jersey.api.client.UniformInterfaceException) KettleException(org.pentaho.di.core.exception.KettleException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UniformInterfaceException(com.sun.jersey.api.client.UniformInterfaceException) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) List(java.util.List) Client(com.sun.jersey.api.client.Client) UriBuilder(javax.ws.rs.core.UriBuilder) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 77 with MultivaluedMap

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);
    }
}
Also used : AlertCriteria(com.thinkbiganalytics.alerts.api.AlertCriteria) AlertManager(com.thinkbiganalytics.alerts.spi.AlertManager) PathParam(javax.ws.rs.PathParam) AlertResponder(com.thinkbiganalytics.alerts.api.AlertResponder) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) AggregatingAlertProvider(com.thinkbiganalytics.alerts.api.core.AggregatingAlertProvider) Path(javax.ws.rs.Path) ApiResponses(io.swagger.annotations.ApiResponses) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) AlertSummary(com.thinkbiganalytics.alerts.api.AlertSummary) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) AlertProvider(com.thinkbiganalytics.alerts.api.AlertProvider) QueryParam(javax.ws.rs.QueryParam) AlertCreateRequest(com.thinkbiganalytics.alerts.rest.model.AlertCreateRequest) RestResponseStatus(com.thinkbiganalytics.rest.model.RestResponseStatus) Consumes(javax.ws.rs.Consumes) Alert(com.thinkbiganalytics.alerts.api.Alert) AlertUpdateRequest(com.thinkbiganalytics.alerts.rest.model.AlertUpdateRequest) DefaultValue(javax.ws.rs.DefaultValue) AccessController(com.thinkbiganalytics.security.AccessController) AlertRange(com.thinkbiganalytics.alerts.rest.model.AlertRange) Formatters(com.thinkbiganalytics.Formatters) URI(java.net.URI) Named(javax.inject.Named) Api(io.swagger.annotations.Api) Status(javax.ws.rs.core.Response.Status) POST(javax.ws.rs.POST) OperationsAccessControl(com.thinkbiganalytics.jobrepo.security.OperationsAccessControl) Collection(java.util.Collection) AlertType(com.thinkbiganalytics.alerts.rest.model.AlertType) Set(java.util.Set) Collectors(java.util.stream.Collectors) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) List(java.util.List) Component(org.springframework.stereotype.Component) ApiResponse(io.swagger.annotations.ApiResponse) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) KyloEntityAwareAlertManager(com.thinkbiganalytics.metadata.alerts.KyloEntityAwareAlertManager) UriInfo(javax.ws.rs.core.UriInfo) AlertsModel(com.thinkbiganalytics.alerts.rest.AlertsModel) AlertSummaryGrouped(com.thinkbiganalytics.alerts.rest.model.AlertSummaryGrouped) AlertCriteria(com.thinkbiganalytics.alerts.api.AlertCriteria) AlertCriteriaInput(com.thinkbiganalytics.alerts.api.core.AlertCriteriaInput) AlertResponse(com.thinkbiganalytics.alerts.api.AlertResponse) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 78 with MultivaluedMap

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);
        }
    }
}
Also used : ContainerException(org.glassfish.jersey.server.ContainerException) OutputStream(java.io.OutputStream) List(java.util.List) IOException(java.io.IOException) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 79 with MultivaluedMap

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;
}
Also used : MessageBodyWorkers(org.glassfish.jersey.message.MessageBodyWorkers) BodyPart(org.glassfish.jersey.media.multipart.BodyPart) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) BodyPartEntity(org.glassfish.jersey.media.multipart.BodyPartEntity) MultiPart(org.glassfish.jersey.media.multipart.MultiPart) FormDataMultiPart(org.glassfish.jersey.media.multipart.FormDataMultiPart) Header(org.jvnet.mimepull.Header) MIMEMessage(org.jvnet.mimepull.MIMEMessage) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) FormDataMultiPart(org.glassfish.jersey.media.multipart.FormDataMultiPart) BadRequestException(javax.ws.rs.BadRequestException) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MIMEPart(org.jvnet.mimepull.MIMEPart)

Example 80 with MultivaluedMap

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);
}
Also used : SyndEntry(com.sun.syndication.feed.synd.SyndEntry) Produces(javax.ws.rs.Produces) Provider(javax.ws.rs.ext.Provider) FeedEntry(org.glassfish.jersey.examples.feedcombiner.model.FeedEntry) Date(java.util.Date) SyndFeedImpl(com.sun.syndication.feed.synd.SyndFeedImpl) LoggerFactory(org.slf4j.LoggerFactory) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) FeedException(com.sun.syndication.io.FeedException) MediaType(javax.ws.rs.core.MediaType) SyndContentImpl(com.sun.syndication.feed.synd.SyndContentImpl) OutputStreamWriter(java.io.OutputStreamWriter) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) Collection(java.util.Collection) IOException(java.io.IOException) SyndFeedOutput(com.sun.syndication.io.SyndFeedOutput) Collectors(java.util.stream.Collectors) SyndContent(com.sun.syndication.feed.synd.SyndContent) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) SyndEntryImpl(com.sun.syndication.feed.synd.SyndEntryImpl) Annotation(java.lang.annotation.Annotation) WebApplicationException(javax.ws.rs.WebApplicationException) SyndFeed(com.sun.syndication.feed.synd.SyndFeed) SyndFeed(com.sun.syndication.feed.synd.SyndFeed) SyndContent(com.sun.syndication.feed.synd.SyndContent) SyndContentImpl(com.sun.syndication.feed.synd.SyndContentImpl) SyndEntry(com.sun.syndication.feed.synd.SyndEntry) SyndEntryImpl(com.sun.syndication.feed.synd.SyndEntryImpl) SyndFeedImpl(com.sun.syndication.feed.synd.SyndFeedImpl) Date(java.util.Date)

Aggregations

MultivaluedMap (javax.ws.rs.core.MultivaluedMap)135 Map (java.util.Map)67 List (java.util.List)51 HashMap (java.util.HashMap)45 MediaType (javax.ws.rs.core.MediaType)35 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)28 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)27 ArrayList (java.util.ArrayList)24 IOException (java.io.IOException)23 Test (org.junit.Test)21 WebApplicationException (javax.ws.rs.WebApplicationException)19 LinkedHashMap (java.util.LinkedHashMap)18 Type (java.lang.reflect.Type)16 Response (javax.ws.rs.core.Response)16 InputStream (java.io.InputStream)14 OutputStream (java.io.OutputStream)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)13 Method (java.lang.reflect.Method)11 Optional (java.util.Optional)11