Search in sources :

Example 1 with FormParams

use of com.lonepulse.robozombie.annotation.FormParams in project RoboZombie by sahan.

the class FormParamProcessor method process.

/**
	 * <p>Accepts the {@link InvocationContext} with an {@link HttpEntityEnclosingRequestBase} and 
	 * creates a list of <a href="http://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms">
	 * form-urlencoded</a> name-value pairs using arguments annotated with @{@link FormParam} and 
	 * @{@link FormParams}. It's then inserted to the body of the request being processed.</p>
	 * 
	 * <p><b>Note</b> that any {@link HttpRequestBase}s which aren't {@link HttpEntityEnclosingRequestBase}s 
	 * will be ignored.</p>
	 * 
	 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
	 * 
	 * @param context
	 * 			the {@link InvocationContext} which is used to discover any annotated form parameters 
	 * <br><br>
	 * @param request
	 * 			prefers an instance of {@link HttpPost} so as to conform with HTTP 1.1; however, other  
	 * 			{@link HttpEntityEnclosingRequestBase}s will be entertained to allow compliance with 
	 * 			unusual endpoint definitions (as long as they are {@link HttpEntityEnclosingRequestBase}s) 
	 * <br><br>
 	 * @return the same instance of {@link HttpRequestBase} which was given for processing form parameters 
	 * <br><br>
	 * @throws RequestProcessorException
	 * 			if a form parameters failed to be created and inserted into the request body
	 * <br><br>
	 * @since 1.3.0
	 */
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {
    try {
        if (request instanceof HttpEntityEnclosingRequestBase) {
            List<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
            //add static name and value pairs
            List<Param> constantFormParams = RequestUtils.findStaticFormParams(context);
            for (Param param : constantFormParams) {
                nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));
            }
            //add individual name and value pairs
            List<Entry<FormParam, Object>> formParams = Metadata.onParams(FormParam.class, context);
            for (Entry<FormParam, Object> entry : formParams) {
                String name = entry.getKey().value();
                Object value = entry.getValue();
                if (!(value instanceof CharSequence)) {
                    StringBuilder errorContext = new StringBuilder().append("Form (url-encoded) parameters can only be of type ").append(CharSequence.class.getName()).append(". Please consider implementing CharSequence ").append("and providing a meaningful toString() representation for the ").append("<name> of the form parameter. ");
                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }
                nameValuePairs.add(new BasicNameValuePair(name, String.valueOf(value)));
            }
            //add batch name and value pairs (along with any static params)
            List<Entry<FormParams, Object>> queryParamMaps = Metadata.onParams(FormParams.class, context);
            for (Entry<FormParams, Object> entry : queryParamMaps) {
                Param[] constantParams = entry.getKey().value();
                if (constantParams != null && constantParams.length > 0) {
                    for (Param param : constantParams) {
                        nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));
                    }
                }
                Object map = entry.getValue();
                if (!(map instanceof Map)) {
                    StringBuilder errorContext = new StringBuilder().append("@FormParams can only be applied on <java.util.Map>s. ").append("Please refactor the method to provide a Map of name and value pairs. ");
                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }
                Map<?, ?> nameAndValues = (Map<?, ?>) map;
                for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) {
                    Object name = nameAndValue.getKey();
                    Object value = nameAndValue.getValue();
                    if (!(name instanceof CharSequence && (value instanceof CharSequence || value instanceof Collection))) {
                        StringBuilder errorContext = new StringBuilder().append("The <java.util.Map> identified by @FormParams can only contain mappings of type ").append("<java.lang.CharSequence, java.lang.CharSequence> or ").append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>");
                        throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                    }
                    if (value instanceof CharSequence) {
                        nameValuePairs.add(new BasicNameValuePair(((CharSequence) name).toString(), ((CharSequence) value).toString()));
                    } else {
                        //add multi-valued form params 
                        Collection<?> multivalues = (Collection<?>) value;
                        for (Object multivalue : multivalues) {
                            if (!(multivalue instanceof CharSequence)) {
                                StringBuilder errorContext = new StringBuilder().append("Values for the <java.util.Map> identified by @FormParams can only contain collections ").append("of type java.util.Collection<? extends CharSequence>");
                                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                            }
                            nameValuePairs.add(new BasicNameValuePair(((CharSequence) name).toString(), ((CharSequence) multivalue).toString()));
                        }
                    }
                }
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
            urlEncodedFormEntity.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
            request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
        return request;
    } catch (Exception e) {
        throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e : new RequestProcessorException(context, getClass(), e);
    }
}
Also used : Entry(java.util.Map.Entry) FormParams(com.lonepulse.robozombie.annotation.FormParams) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) LinkedList(java.util.LinkedList) FormParam(com.lonepulse.robozombie.annotation.FormParam) Param(com.lonepulse.robozombie.annotation.Param) Collection(java.util.Collection) FormParam(com.lonepulse.robozombie.annotation.FormParam) Map(java.util.Map)

Example 2 with FormParams

use of com.lonepulse.robozombie.annotation.FormParams in project RoboZombie by sahan.

the class RequestUtils method findStaticFormParams.

/**
	  * <p>Finds all <b><i>constant</i> form parameters</b> in the given {@link InvocationContext}.</p> 
	  * <p>Constant form parameters are introduced with @{@link Param} at <b>request level</b> using 
	  * the @{@link FormParams} annotation.</p>
	  *
	  * @param context
	  * 			the {@link InvocationContext} from which all {@link FormParams} annotations applied 
	  * 			on the endpoint method will be extracted
	  * <br><br>
	  * @return an <b>unmodifiable</b> {@link List} which aggregates all the @{@link Param} annotations 
	  * 	   	   found on the {@link FormParams} annotation
	  * <br><br>
	  * @throws NullPointerException
	  * 			if the supplied {@link InvocationContext} was {@code null}
	  * <br><br>
	  * @since 1.3.0
	  */
static List<Param> findStaticFormParams(InvocationContext context) {
    Method request = assertNotNull(context).getRequest();
    FormParams formParams = request.getAnnotation(FormParams.class);
    return Collections.unmodifiableList(formParams != null ? Arrays.asList(formParams.value()) : new ArrayList<Param>());
}
Also used : FormParams(com.lonepulse.robozombie.annotation.FormParams) ArrayList(java.util.ArrayList) RequestMethod(com.lonepulse.robozombie.annotation.Request.RequestMethod) Method(java.lang.reflect.Method)

Aggregations

FormParams (com.lonepulse.robozombie.annotation.FormParams)2 FormParam (com.lonepulse.robozombie.annotation.FormParam)1 Param (com.lonepulse.robozombie.annotation.Param)1 RequestMethod (com.lonepulse.robozombie.annotation.Request.RequestMethod)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Entry (java.util.Map.Entry)1 NameValuePair (org.apache.http.NameValuePair)1 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)1 HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)1 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)1