Search in sources :

Example 11 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project OpenAM by OpenRock.

the class ConsumerRequest method postConsumerRegistrations.

/**
     * POST method for registering a Service Consumer
     * and obtaining corresponding consumer key & secret.
     *
     * @param formParams {@link String} containing the service 
     * consumer's description.
     * This description takes the form of name=value pairs separated by &.
     * The following parameters are supported:
     * <OL>
     * <LI>name - the service consumer's name.</LI>
     * <LI>icon - the service consumer's URI for its icon (MUST be unique).</LI>
     * <LI>service - the service consumer's URI for its service</LI>
     * <LI>rsapublickey - (optional) the RSA public key of the Service Consumer.</LI>
     * </OL>
     * <p>
     *
     * Example of string:
     * <pre>
     *  name=Service XYZ&icon=http://www.example.com/icon.jpg&service=http://www.example.com
     * </pre>
     *
     *
     * @return an HTTP response with content of the created resource.
     * The location URI is set to the newly created OAuth consumer key.
     * The body of the response is of the form:
     * <pre>
     * consumer_key=http://serviceprovider/0123456762121
     * consumer_secret=12345633
     * </pre>
     * Both values are URL encoded.
     */
@POST
@Consumes("application/x-www-form-urlencoded")
public Response postConsumerRegistrations(MultivaluedMap<String, String> formParams) {
    OAuthResourceManager oauthResMgr = OAuthResourceManager.getInstance();
    try {
        Consumer cons = new Consumer();
        String cert = null;
        String tmpsecret = null;
        Boolean keyed = false;
        Set<String> pnames = formParams.keySet();
        Iterator<String> iter = pnames.iterator();
        Encoder enc = ESAPI.encoder();
        Validator validator = ESAPI.validator();
        while (iter.hasNext()) {
            String key = iter.next();
            String val = formParams.getFirst(key);
            if (key.equalsIgnoreCase(C_NAME)) {
                String consumerName = enc.canonicalize(val);
                if (!validator.isValidInput(C_NAME, consumerName, "HTTPParameterValue", 512, true)) {
                    String resp = "Invalid name entered entered. Please try again.";
                    return Response.ok().entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
                }
                // Check if a consumer with the same name is already registered,
                // if so, will not do the registration again.
                Map<String, String> searchMap = new HashMap<String, String>();
                searchMap.put(CONSUMER_NAME, consumerName);
                List<Consumer> consumers = oauthResMgr.searchConsumers(searchMap);
                if ((consumers != null) && (!consumers.isEmpty())) {
                    String resp = "A consumer is already registered with name " + enc.encodeForHTML(consumerName) + ".";
                    return Response.ok().entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
                }
                cons.setConsName(consumerName);
            } else if (key.equalsIgnoreCase(C_CERT)) {
                // The cert is in PEM format (no URL decode needed)
                cert = val;
            } else if (key.equalsIgnoreCase(C_SECRET)) {
                tmpsecret = URLDecoder.decode(val);
            } else if (key.equalsIgnoreCase(C_KEY)) {
                keyed = true;
                String consumerKey = enc.canonicalize(val);
                if (!validator.isValidInput(C_KEY, consumerKey, "HTTPParameterValue", 512, true)) {
                    String resp = "Invalid key entered entered. Please try again.";
                    return Response.ok().entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
                }
                // Check if a consumer with the same key is already registered,
                // if so, will not do the registration again.
                cons.setConsKey(consumerKey);
                Map<String, String> searchMap = new HashMap<String, String>();
                searchMap.put(CONSUMER_KEY, consumerKey);
                List<Consumer> consumers = oauthResMgr.searchConsumers(searchMap);
                if ((consumers != null) && (!consumers.isEmpty())) {
                    String resp = "A consumer is already registered with key " + enc.encodeForHTML(consumerKey) + ".";
                    return Response.ok().entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
                }
            } else {
            // anything else is ignored for the time being
            }
        }
        if (cert != null) {
            cons.setConsRsakey(cert);
        }
        if (tmpsecret != null) {
            cons.setConsSecret(tmpsecret);
        } else {
            cons.setConsSecret(new UniqueRandomString().getString());
        }
        if (!keyed) {
            String baseUri = context.getBaseUri().toString();
            if (baseUri.endsWith("/"))
                baseUri = baseUri.substring(0, baseUri.length() - 1);
            URI loc = URI.create(baseUri + PathDefs.CONSUMERS_PATH + "/" + new UniqueRandomString().getString());
            String consKey = loc.toString();
            cons.setConsKey(consKey);
        }
        oauthResMgr.createConsumer(null, cons);
        String resp = "consumer_key=" + URLEncoder.encode(cons.getConsKey()) + "&consumer_secret=" + URLEncoder.encode(cons.getConsSecret());
        return Response.created(URI.create(cons.getConsKey())).entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
    } catch (OAuthServiceException e) {
        Logger.getLogger(ConsumerRequest.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    } catch (IntrusionException e) {
        Logger.getLogger(ConsumerRequest.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    } catch (EncodingException e) {
        Logger.getLogger(ConsumerRequest.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    }
}
Also used : UniqueRandomString(com.sun.identity.oauth.service.util.UniqueRandomString) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) EncodingException(org.owasp.esapi.errors.EncodingException) UniqueRandomString(com.sun.identity.oauth.service.util.UniqueRandomString) URI(java.net.URI) Consumer(com.sun.identity.oauth.service.models.Consumer) Encoder(org.owasp.esapi.Encoder) URLEncoder(java.net.URLEncoder) List(java.util.List) IntrusionException(org.owasp.esapi.errors.IntrusionException) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Validator(org.owasp.esapi.Validator) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 12 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project cloudstack by apache.

the class MidoNetElement method getChain.

protected RuleChain getChain(String networkId, String accountUuid, String routerName, RuleChainCode chainCode) {
    String chainName = getChainName(networkId, routerName, chainCode);
    MultivaluedMap findChain = new MultivaluedMapImpl();
    findChain.add("tenant_id", accountUuid);
    ResourceCollection<RuleChain> ruleChains = api.getChains(findChain);
    for (RuleChain chain : ruleChains) {
        if (chain.getName().equals(chainName)) {
            return chain;
        }
    }
    return null;
}
Also used : RuleChain(org.midonet.client.resource.RuleChain) MultivaluedMapImpl(com.sun.jersey.core.util.MultivaluedMapImpl) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 13 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project tika by apache.

the class ZipWriter method writeTo.

public void writeTo(Map<String, byte[]> parts, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    ZipArchiveOutputStream zip = new ZipArchiveOutputStream(entityStream);
    zip.setMethod(ZipArchiveOutputStream.STORED);
    for (Map.Entry<String, byte[]> entry : parts.entrySet()) {
        zipStoreBuffer(zip, entry.getKey(), entry.getValue());
    }
    zip.close();
}
Also used : ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 14 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project ddf by codice.

the class TestOpenSearchSource method givenSource.

private OpenSearchSource givenSource(Answer<BinaryContent> answer) throws IOException, ResourceNotFoundException, ResourceNotSupportedException {
    WebClient client = mock(WebClient.class);
    ResourceReader mockReader = mock(ResourceReader.class);
    Response clientResponse = mock(Response.class);
    when(clientResponse.getEntity()).thenReturn(getBinaryData());
    when(clientResponse.getHeaderString(eq(OpenSearchSource.HEADER_ACCEPT_RANGES))).thenReturn(OpenSearchSource.BYTES);
    when(client.get()).thenReturn(clientResponse);
    SecureCxfClientFactory factory = getMockFactory(client);
    when(mockReader.retrieveResource(any(URI.class), any(Map.class))).thenReturn(new ResourceResponseImpl(new ResourceImpl(getBinaryData(), "")));
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
    headers.put(HttpHeaders.CONTENT_TYPE, Arrays.<Object>asList("application/octet-stream"));
    when(clientResponse.getHeaders()).thenReturn(headers);
    OverriddenOpenSearchSource source = new OverriddenOpenSearchSource(FILTER_ADAPTER, encryptionService);
    source.setEndpointUrl("http://localhost:8181/services/catalog/query");
    source.setParameters(DEFAULT_PARAMETERS);
    source.init();
    source.setLocalQueryOnly(true);
    source.setInputTransformer(getMockInputTransformer());
    source.factory = factory;
    source.setResourceReader(mockReader);
    return source;
}
Also used : ResourceReader(ddf.catalog.resource.ResourceReader) SecureCxfClientFactory(org.codice.ddf.cxf.SecureCxfClientFactory) ResourceResponseImpl(ddf.catalog.operation.impl.ResourceResponseImpl) Matchers.containsString(org.hamcrest.Matchers.containsString) WebClient(org.apache.cxf.jaxrs.client.WebClient) URI(java.net.URI) Response(javax.ws.rs.core.Response) ResourceResponse(ddf.catalog.operation.ResourceResponse) SourceResponse(ddf.catalog.operation.SourceResponse) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ResourceImpl(ddf.catalog.resource.impl.ResourceImpl) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 15 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project ddf by codice.

the class BodyWriter method writeBody.

<T> void writeBody(T o, Message outMessage, Class<?> cls, Type type, Annotation[] anns, OutputStream os) {
    if (o == null) {
        return;
    }
    @SuppressWarnings("unchecked") MultivaluedMap<String, Object> headers = (MultivaluedMap<String, Object>) outMessage.get(Message.PROTOCOL_HEADERS);
    @SuppressWarnings("unchecked") Class<T> theClass = (Class<T>) cls;
    MediaType contentType = JAXRSUtils.toMediaType(headers.getFirst("Content-Type").toString());
    List<WriterInterceptor> writers = ClientProviderFactory.getInstance(outMessage).createMessageBodyWriterInterceptor(theClass, type, anns, contentType, outMessage, null);
    if (writers != null) {
        try {
            JAXRSUtils.writeMessageBody(writers, o, theClass, type, anns, contentType, headers, outMessage);
            OutputStream realOs = outMessage.get(OutputStream.class);
            if (realOs != null) {
                realOs.flush();
            }
        } catch (Exception ex) {
            LOGGER.debug("Unable to write message body for final ECP response.");
        }
    } else {
        LOGGER.debug("No writers available for final ECP response");
    }
}
Also used : WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) OutputStream(java.io.OutputStream) MediaType(javax.ws.rs.core.MediaType) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Aggregations

MultivaluedMap (javax.ws.rs.core.MultivaluedMap)29 Map (java.util.Map)11 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)8 List (java.util.List)8 IOException (java.io.IOException)6 MediaType (javax.ws.rs.core.MediaType)6 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)6 OutputStream (java.io.OutputStream)5 HashMap (java.util.HashMap)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 OutputStreamWriter (java.io.OutputStreamWriter)3 Type (java.lang.reflect.Type)3 URI (java.net.URI)3 MessageBodyWriter (javax.ws.rs.ext.MessageBodyWriter)3 JSONEntitlement (com.sun.identity.entitlement.JSONEntitlement)2 OAuthServiceException (com.sun.identity.oauth.service.OAuthServiceException)2 UniformInterfaceException (com.sun.jersey.api.client.UniformInterfaceException)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2