Search in sources :

Example 1 with Form

use of org.restlet.data.Form in project qi4j-sdk by Qi4j.

the class ContextResource method formForMethod.

private Form formForMethod(Method interactionMethod) {
    Form form = new Form();
    Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
    Form entityAsForm;
    Representation representation = Request.getCurrent().getEntity();
    if (representation != null && !EmptyRepresentation.class.isInstance(representation)) {
        entityAsForm = new Form(representation);
    } else {
        entityAsForm = new Form();
    }
    Class<?> valueType = interactionMethod.getParameterTypes()[0];
    if (ValueComposite.class.isAssignableFrom(valueType)) {
        ValueDescriptor valueDescriptor = module.valueDescriptor(valueType.getName());
        for (PropertyDescriptor propertyDescriptor : valueDescriptor.state().properties()) {
            String value = getValue(propertyDescriptor.qualifiedName().name(), queryAsForm, entityAsForm);
            if (value == null) {
                Object initialValue = propertyDescriptor.initialValue(module);
                if (initialValue != null) {
                    value = initialValue.toString();
                }
            }
            form.add(propertyDescriptor.qualifiedName().name(), value);
        }
    } else if (valueType.isInterface() && interactionMethod.getParameterTypes().length == 1) {
        // Single entity as input
        form.add("entity", getValue("entity", queryAsForm, entityAsForm));
    } else {
        // Construct form out of individual parameters instead
        for (Annotation[] annotations : interactionMethod.getParameterAnnotations()) {
            Name name = (Name) first(filter(isType(Name.class), iterable(annotations)));
            form.add(name.value(), getValue(name.value(), queryAsForm, entityAsForm));
        }
    }
    return form;
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) Form(org.restlet.data.Form) ValueDescriptor(org.qi4j.api.value.ValueDescriptor) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) Name(org.qi4j.api.constraint.Name)

Example 2 with Form

use of org.restlet.data.Form in project qi4j-sdk by Qi4j.

the class SPARQLResource method getQuery.

private Query getQuery(Repository repository, RepositoryConnection repositoryCon, String queryStr) throws ResourceException {
    Form form = getRequest().getResourceRef().getQueryAsForm();
    Query result;
    // default query language is SPARQL
    QueryLanguage queryLn = QueryLanguage.SPARQL;
    // determine if inferred triples should be included in query evaluation
    boolean includeInferred = true;
    // build a dataset, if specified
    String[] defaultGraphURIs = form.getValuesArray(DEFAULT_GRAPH_PARAM_NAME);
    String[] namedGraphURIs = form.getValuesArray(NAMED_GRAPH_PARAM_NAME);
    DatasetImpl dataset = null;
    if (defaultGraphURIs.length > 0 || namedGraphURIs.length > 0) {
        dataset = new DatasetImpl();
        if (defaultGraphURIs.length > 0) {
            for (String defaultGraphURI : defaultGraphURIs) {
                try {
                    URI uri = repository.getValueFactory().createURI(defaultGraphURI);
                    dataset.addDefaultGraph(uri);
                } catch (IllegalArgumentException e) {
                    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Illegal URI for default graph: " + defaultGraphURI);
                }
            }
        }
        if (namedGraphURIs.length > 0) {
            for (String namedGraphURI : namedGraphURIs) {
                try {
                    URI uri = repository.getValueFactory().createURI(namedGraphURI);
                    dataset.addNamedGraph(uri);
                } catch (IllegalArgumentException e) {
                    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
                }
            }
        }
    }
    try {
        result = repositoryCon.prepareQuery(queryLn, queryStr);
        result.setIncludeInferred(includeInferred);
        if (dataset != null) {
            result.setDataset(dataset);
        }
        // determine if any variable bindings have been set on this query.
        @SuppressWarnings("unchecked") Enumeration<String> parameterNames = Collections.enumeration(form.getValuesMap().keySet());
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            if (parameterName.startsWith(BINDING_PREFIX) && parameterName.length() > BINDING_PREFIX.length()) {
                String bindingName = parameterName.substring(BINDING_PREFIX.length());
                Value bindingValue = parseValueParam(repository, form, parameterName);
                result.setBinding(bindingName, bindingValue);
            }
        }
    } catch (UnsupportedQueryLanguageException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    } catch (MalformedQueryException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    } catch (RepositoryException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e.getMessage());
    }
    return result;
}
Also used : Form(org.restlet.data.Form) RepositoryException(org.openrdf.repository.RepositoryException) DatasetImpl(org.openrdf.query.impl.DatasetImpl) URI(org.openrdf.model.URI) Value(org.openrdf.model.Value) ResourceException(org.restlet.resource.ResourceException)

Example 3 with Form

use of org.restlet.data.Form in project pinot by linkedin.

the class PqlQueryResource method get.

@Override
public Representation get() {
    try {
        Form query = getQuery();
        LOGGER.debug("Running query: " + query);
        String pqlQuery = query.getValues("pql");
        String traceEnabled = query.getValues("trace");
        // Get resource table name.
        String tableName;
        try {
            tableName = REQUEST_COMPILER.compileToBrokerRequest(pqlQuery).getQuerySource().getTableName();
        } catch (Exception e) {
            LOGGER.error("Caught exception while compiling PQL query: " + pqlQuery, e);
            return new StringRepresentation(QueryException.getException(QueryException.PQL_PARSING_ERROR, e).toString());
        }
        // Get brokers for the resource table.
        List<String> instanceIds = _pinotHelixResourceManager.getBrokerInstancesFor(tableName);
        if (instanceIds.isEmpty()) {
            return new StringRepresentation(QueryException.BROKER_RESOURCE_MISSING_ERROR.toString());
        }
        // Retain only online brokers.
        instanceIds.retainAll(_pinotHelixResourceManager.getOnlineInstanceList());
        if (instanceIds.isEmpty()) {
            return new StringRepresentation(QueryException.BROKER_INSTANCE_MISSING_ERROR.toString());
        }
        // Send query to a random broker.
        String instanceId = instanceIds.get(RANDOM.nextInt(instanceIds.size()));
        InstanceConfig instanceConfig = _pinotHelixResourceManager.getHelixInstanceConfig(instanceId);
        String url = "http://" + instanceConfig.getHostName().split("_")[1] + ":" + instanceConfig.getPort() + "/query";
        return new StringRepresentation(sendPQLRaw(url, pqlQuery, traceEnabled));
    } catch (Exception e) {
        LOGGER.error("Caught exception while processing get request", e);
        return new StringRepresentation(QueryException.getException(QueryException.INTERNAL_ERROR, e).toString());
    }
}
Also used : InstanceConfig(org.apache.helix.model.InstanceConfig) Form(org.restlet.data.Form) StringRepresentation(org.restlet.representation.StringRepresentation) IOException(java.io.IOException) QueryException(com.linkedin.pinot.common.exception.QueryException)

Example 4 with Form

use of org.restlet.data.Form in project camel by apache.

the class DefaultRestletBinding method populateRestletRequestFromExchange.

public void populateRestletRequestFromExchange(Request request, Exchange exchange) {
    request.setReferrerRef("camel-restlet");
    final Method method = request.getMethod();
    MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
    if (mediaType == null) {
        mediaType = MediaType.APPLICATION_WWW_FORM;
    }
    Form form = null;
    // Use forms only for PUT, POST and x-www-form-urlencoded
    if ((Method.PUT == method || Method.POST == method) && MediaType.APPLICATION_WWW_FORM.equals(mediaType, true)) {
        form = new Form();
        if (exchange.getIn().getBody() instanceof Map) {
            //Body is key value pairs
            try {
                Map pairs = exchange.getIn().getBody(Map.class);
                for (Object key : pairs.keySet()) {
                    Object value = pairs.get(key);
                    form.add(key.toString(), value != null ? value.toString() : null);
                }
            } catch (Exception e) {
                throw new RuntimeCamelException("body for " + MediaType.APPLICATION_WWW_FORM + " request must be Map<String,String> or string format like name=bob&password=secRet", e);
            }
        } else {
            // use string based for forms
            String body = exchange.getIn().getBody(String.class);
            if (body != null) {
                List<NameValuePair> pairs = URLEncodedUtils.parse(body, Charset.forName(IOHelper.getCharsetName(exchange, true)));
                for (NameValuePair p : pairs) {
                    form.add(p.getName(), p.getValue());
                }
            }
        }
    }
    // get outgoing custom http headers from the exchange if they exists
    Series<Header> restletHeaders = exchange.getIn().getHeader(HeaderConstants.ATTRIBUTE_HEADERS, Series.class);
    if (restletHeaders == null) {
        restletHeaders = new Series<Header>(Header.class);
        request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, restletHeaders);
    } else {
        // if the restlet headers already exists on the exchange, we need to filter them
        for (String name : restletHeaders.getNames()) {
            if (headerFilterStrategy.applyFilterToCamelHeaders(name, restletHeaders.getValues(name), exchange)) {
                restletHeaders.removeAll(name);
            }
        }
        request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, restletHeaders);
        // since the restlet headers already exists remove them from the exchange so they don't get added again below
        // we will get a new set of restlet headers on the response
        exchange.getIn().removeHeader(HeaderConstants.ATTRIBUTE_HEADERS);
    }
    // login and password are filtered by header filter strategy
    String login = exchange.getIn().getHeader(RestletConstants.RESTLET_LOGIN, String.class);
    String password = exchange.getIn().getHeader(RestletConstants.RESTLET_PASSWORD, String.class);
    if (login != null && password != null) {
        ChallengeResponse authentication = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, login, password);
        request.setChallengeResponse(authentication);
        LOG.debug("Basic HTTP Authentication has been applied");
    }
    for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
            // Use forms only for PUT, POST and x-www-form-urlencoded
            if (form != null) {
                if (key.startsWith("org.restlet.")) {
                    // put the org.restlet headers in attributes
                    request.getAttributes().put(key, value);
                } else {
                    // put the user stuff in the form
                    if (value instanceof Collection) {
                        for (Object v : (Collection<?>) value) {
                            form.add(key, v.toString());
                            if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
                                restletHeaders.set(key, value.toString());
                            }
                        }
                    } else {
                        //Add headers to headers and to body
                        form.add(key, value.toString());
                        if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
                            restletHeaders.set(key, value.toString());
                        }
                    }
                }
            } else {
                // For non-form post put all the headers in custom headers
                if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    restletHeaders.set(key, value.toString());
                }
            }
            LOG.debug("Populate Restlet request from exchange header: {} value: {}", key, value);
        }
    }
    if (form != null) {
        request.setEntity(form.getWebRepresentation());
        LOG.debug("Populate Restlet {} request from exchange body as form using media type {}", method, mediaType);
    } else {
        // include body if PUT or POST
        if (request.getMethod() == Method.PUT || request.getMethod() == Method.POST) {
            Representation body = createRepresentationFromBody(exchange, mediaType);
            request.setEntity(body);
            LOG.debug("Populate Restlet {} request from exchange body: {} using media type {}", method, body, mediaType);
        } else {
            // no body
            LOG.debug("Populate Restlet {} request from exchange using media type {}", method, mediaType);
            request.setEntity(new EmptyRepresentation());
        }
    }
    // accept
    String accept = exchange.getIn().getHeader("Accept", String.class);
    final ClientInfo clientInfo = request.getClientInfo();
    final List<Preference<MediaType>> acceptedMediaTypesList = clientInfo.getAcceptedMediaTypes();
    if (accept != null) {
        final MediaType[] acceptedMediaTypes = exchange.getContext().getTypeConverter().tryConvertTo(MediaType[].class, exchange, accept);
        for (final MediaType acceptedMediaType : acceptedMediaTypes) {
            acceptedMediaTypesList.add(new Preference<MediaType>(acceptedMediaType));
        }
    }
    final MediaType[] acceptedMediaTypes = exchange.getIn().getHeader(Exchange.ACCEPT_CONTENT_TYPE, MediaType[].class);
    if (acceptedMediaTypes != null) {
        for (final MediaType acceptedMediaType : acceptedMediaTypes) {
            acceptedMediaTypesList.add(new Preference<MediaType>(acceptedMediaType));
        }
    }
}
Also used : NameValuePair(org.apache.http.NameValuePair) Form(org.restlet.data.Form) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) StreamRepresentation(org.restlet.representation.StreamRepresentation) Representation(org.restlet.representation.Representation) DecodeRepresentation(org.restlet.engine.application.DecodeRepresentation) Method(org.restlet.data.Method) ParseException(java.text.ParseException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ChallengeResponse(org.restlet.data.ChallengeResponse) Header(org.restlet.data.Header) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) Preference(org.restlet.data.Preference) MediaType(org.restlet.data.MediaType) Collection(java.util.Collection) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ClientInfo(org.restlet.data.ClientInfo) Map(java.util.Map)

Example 5 with Form

use of org.restlet.data.Form in project camel by apache.

the class DefaultRestletBinding method populateExchangeFromRestletRequest.

public void populateExchangeFromRestletRequest(Request request, Response response, Exchange exchange) throws Exception {
    Message inMessage = exchange.getIn();
    inMessage.setHeader(RestletConstants.RESTLET_REQUEST, request);
    inMessage.setHeader(RestletConstants.RESTLET_RESPONSE, response);
    // extract headers from restlet
    for (Map.Entry<String, Object> entry : request.getAttributes().entrySet()) {
        if (!headerFilterStrategy.applyFilterToExternalHeaders(entry.getKey(), entry.getValue(), exchange)) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (HeaderConstants.ATTRIBUTE_HEADERS.equalsIgnoreCase(key)) {
                Series<Header> series = (Series<Header>) value;
                for (Header header : series) {
                    if (!headerFilterStrategy.applyFilterToExternalHeaders(header.getName(), header.getValue(), exchange)) {
                        inMessage.setHeader(header.getName(), header.getValue());
                    }
                }
            } else {
                inMessage.setHeader(key, value);
            }
            LOG.debug("Populate exchange from Restlet request header: {} value: {}", key, value);
        }
    }
    // copy query string to header
    String query = request.getResourceRef().getQuery();
    if (query != null) {
        inMessage.setHeader(Exchange.HTTP_QUERY, query);
    }
    // copy URI to header
    inMessage.setHeader(Exchange.HTTP_URI, request.getResourceRef().getIdentifier(true));
    // copy HTTP method to header
    inMessage.setHeader(Exchange.HTTP_METHOD, request.getMethod().toString());
    if (!request.isEntityAvailable()) {
        return;
    }
    // only deal with the form if the content type is "application/x-www-form-urlencoded"
    if (request.getEntity().getMediaType() != null && request.getEntity().getMediaType().equals(MediaType.APPLICATION_WWW_FORM, true)) {
        Form form = new Form(request.getEntity());
        for (String paramName : form.getValuesMap().keySet()) {
            String[] values = form.getValuesArray(paramName);
            Object value = null;
            if (values != null && values.length > 0) {
                if (values.length == 1) {
                    value = values[0];
                } else {
                    value = values;
                }
            }
            if (value == null) {
                inMessage.setBody(paramName);
                LOG.debug("Populate exchange from Restlet request body: {}", paramName);
            } else {
                if (!headerFilterStrategy.applyFilterToExternalHeaders(paramName, value, exchange)) {
                    inMessage.setHeader(paramName, value);
                    LOG.debug("Populate exchange from Restlet request user header: {} value: {}", paramName, value);
                }
            }
        }
    } else {
        InputStream is = request.getEntity().getStream();
        Object body = RestletHelper.readResponseBodyFromInputStream(is, exchange);
        inMessage.setBody(body);
    }
}
Also used : Series(org.restlet.util.Series) Message(org.apache.camel.Message) Header(org.restlet.data.Header) Form(org.restlet.data.Form) InputStream(java.io.InputStream) Map(java.util.Map)

Aggregations

Form (org.restlet.data.Form)30 Request (org.restlet.Request)8 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)6 MediaType (org.restlet.data.MediaType)6 IOException (java.io.IOException)5 Representation (org.restlet.representation.Representation)5 AccessTokenVerifier (org.forgerock.oauth2.core.AccessTokenVerifier)4 Parameter (org.restlet.data.Parameter)4 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)4 ResourceException (org.restlet.resource.ResourceException)4 Test (org.testng.annotations.Test)4 Map (java.util.Map)3 Context (org.locationtech.geogig.api.Context)3 Reference (org.restlet.data.Reference)3 StringRepresentation (org.restlet.representation.StringRepresentation)3 Representation (org.restlet.resource.Representation)3 Optional (com.google.common.base.Optional)2 InputStream (java.io.InputStream)2 URL (java.net.URL)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2