text:
package br.com.jgon.canary.ws.rest.link;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Link;
import javax.ws.rs.core.Link.Builder;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonRootName;
//import com.google.common.base.CaseFormat;

import br.com.jgon.canary.exception.ApplicationException;
import br.com.jgon.canary.exception.ApplicationRuntimeException;
import br.com.jgon.canary.util.CollectionUtil;
import br.com.jgon.canary.util.MessageSeverity;
import br.com.jgon.canary.util.Page;
import br.com.jgon.canary.util.ReflectionUtil;
import br.com.jgon.canary.ws.rest.param.WSFieldParam;
import br.com.jgon.canary.ws.rest.param.WSParamFormat;
import br.com.jgon.canary.ws.rest.util.DominiosRest;
import br.com.jgon.canary.ws.rest.util.HalJsonRootName;
import br.com.jgon.canary.ws.rest.util.ResponseError;
import br.com.jgon.canary.ws.rest.util.json.JsonCollectionLinkEntity;
import br.com.jgon.canary.ws.rest.util.json.JsonHALLinkEntity;
import br.com.jgon.canary.ws.rest.util.json.JsonLinkEntity;

/**
 * Provider que habilita a inclusao de links na response
 *
 * @author Jurandir C. Goncalves
 *
 * @version 1.0
 *
 */
@Provider
public class LinkResponseFilter implements ContainerResponseFilter {

	private static final String REGEX_REQUEST_PATH_PARAMETERS = "\\{[a-z-A-Z]+\\}";
	private static final String REGEX_PATH_PARAMETERS_REQ = "[^\\#\\$]\\{[a-z-A-Z]+\\}";
	private static final String REGEX_PATH_PARAMETERS_ENTITY = "(\\#|\\$)\\{[a-z-A-Z\\.]+\\}";
	private static final String REGEX_REPLACE_PARAM = "\\#|\\$|\\{|\\}";
	private static final String REGEX_LINK_TEMPLATE = "(^\\{[a-zA-Z_-]+\\})|([^\\#\\$]\\{[a-zA-Z_-]+\\})";
	public static final String MEDIA_TYPE_APPLICATION_HAL_JSON = "application/hal+json";

	private Class<?> serviceClass;
	private Method serviceMethod;

	private Logger logger = LoggerFactory.getLogger(LinkResponseFilter.class);

	public LinkResponseFilter() {

	}

	public LinkResponseFilter(Class<?> serviceClass, Method serviceMethod) {
		super();
		this.serviceClass = serviceClass;
		this.serviceMethod = serviceMethod;
	}

	/**
	 * Intercepta a response para configrar os links
	 */
	@Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    	if(responseContext.getEntityAnnotations() != null
    			&& (responseContext.getEntityClass() == null
    			|| !responseContext.getEntityClass().equals(ResponseError.class))){

    		try{
    			configLinks(requestContext.getUriInfo(), responseContext);
			} catch (ApplicationException e) {
				throw new ApplicationRuntimeException(e);
			}
    	}
    }

	/**
	 * Configura os links para a response
	 * @param uriInfo
	 * @param responseContext
	 * @throws ApplicationException
	 */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	private void configLinks(UriInfo uriInfo, ContainerResponseContext responseContext) throws ApplicationException{
    	LinkResource linkResource = null;
    	LinkResources linkResources = null;
    	LinkPaginate linkPaginate = null;
    	LinkFormat linkFormat = null;

    	boolean isHalLinks = responseContext.getMediaType() != null && responseContext.getMediaType().toString().equals(MEDIA_TYPE_APPLICATION_HAL_JSON);

    	Map<Path, List<LinkResource>> linkPaginateEntity = null;

    	Path path = null;

    	for(Annotation a: responseContext.getEntityAnnotations()){
    		if(a instanceof LinkResource){
    			linkResource = (LinkResource) a;
    		}else if(a instanceof LinkResources){
    			linkResources = (LinkResources) a;
    		}else if(a instanceof LinkPaginate){
    			linkPaginate = (LinkPaginate) a;
    		}else if(a instanceof LinkFormat){
    			linkFormat = (LinkFormat) a;
    		}else if(a instanceof Path){
    			path = (Path) a;
    		}
    	}

    	List<Link> linksHeader = new ArrayList<Link>();
    	List<Link> linksEntity = new ArrayList<Link>();
    	List<Link> paginateLinks = new ArrayList<Link>();

    	if(linkPaginate != null){
    		paginateLinks.addAll(getPaginateLink(responseContext.getEntity(), linkPaginate, uriInfo, path, responseContext.getStringHeaders()));

    		//Adiciona link na entidade somente se requisicao for hal+json
    		if(isHalLinks){
    			linkPaginateEntity = new HashMap<Path, List<LinkResource>>();

    			if(linkPaginate.collectionLinks().value().length > 0){
    				linkPaginateEntity.put(path, CollectionUtil.convertArrayToList(linkPaginate.collectionLinks().value()));
    			}

    			if(!linkPaginate.collectionLinks().serviceClass().equals(void.class) && StringUtils.isNotBlank(linkPaginate.collectionLinks().serviceMethodName())){
    				Class<?> serviceClassPag = linkPaginate.collectionLinks().serviceClass();
    				String serviceMethodNamePag = linkPaginate.collectionLinks().serviceMethodName();
    				Path pathAux = ReflectionUtil.getAnnotation(serviceClassPag, serviceMethodNamePag, Path.class);

    				List<LinkResource> linkResAux = new ArrayList<LinkResource>();

    				LinkResource lrAux = ReflectionUtil.getAnnotation(serviceClassPag,  serviceMethodNamePag, LinkResource.class);
    				if(lrAux != null){
    					linkResAux.add(reconfigLink(lrAux, serviceClassPag,  serviceMethodNamePag));
    				}

    				LinkResources lkRes = ReflectionUtil.getAnnotation(serviceClassPag,  serviceMethodNamePag, LinkResources.class);
    				if(lkRes != null){
    					for(LinkResource lr : lkRes.value()){
    						linkResAux.add(reconfigLink(lr, serviceClassPag,  serviceMethodNamePag));
    					}
    				}

    				linkPaginateEntity.put(pathAux, linkResAux);
    			}
    		}
    	}

    	//Adiciona link na entidade somente se requisicao for hal+json
    	//LINKRESOURCE
    	if(isHalLinks && linkResource != null){
    		boolean isCollection = linkPaginate == null && (responseContext.getEntity() instanceof Collection);
    		if(isCollection){
    			List<LinkResource> linkResAux;
    			if(!linkResource.serviceClass().equals(void.class)){
    				Path pathAux = ReflectionUtil.getAnnotation(linkResource.serviceClass(), linkResource.serviceMethodName(), Path.class);
    				linkResAux = new ArrayList<LinkResource>();
    				LinkResource linkResourceAux = ReflectionUtil.getAnnotation(linkResources.serviceClass(), linkResources.serviceMethodName(), LinkResource.class);
    				if(linkResourceAux != null){
    					linkResAux.add(reconfigLink(linkResourceAux, linkResource.serviceClass(), linkResource.serviceMethodName()));
    					linkPaginateEntity.put(pathAux, linkResAux);
    				}
    			}else{
    				linkResAux = new ArrayList<LinkResource>();
    				linkResAux.add(linkResource);
    				linkPaginateEntity.put(path, linkResAux);
    			}
    		}else{
    			Link link = getLink(linkResource, uriInfo, null, responseContext.getEntity(), path, false);
    			if(link != null){
    				if(linkResource.target().equals(LinkTarget.ENTITY)){
    					linksEntity.add(link);
    				}else{
    					linksHeader.add(link);
    				}
    			}
    		}
    	}
    	//Adiciona link na entidade somente se requisicao for hal+json
    	//LINKRESOURCES
    	if(isHalLinks && linkResources != null){
    		boolean isCollection = linkPaginate == null && (responseContext.getEntity() instanceof Collection);
    		if(isCollection){
    			linkPaginateEntity = new HashMap<Path, List<LinkResource>>();
    			List<LinkResource> linkResAux;
    			if(!linkResources.serviceClass().equals(void.class)){
    				Path pathAux = ReflectionUtil.getAnnotation(linkResources.serviceClass(), linkResources.serviceMethodName(), Path.class);
    				linkResAux = new ArrayList<LinkResource>();
    				LinkResources linkResourcesAux = ReflectionUtil.getAnnotation(linkResources.serviceClass(), linkResources.serviceMethodName(), LinkResources.class);
    				if(linkResourcesAux != null && linkResourcesAux.value().length > 0){
    					for(LinkResource lr : linkResourcesAux.value()){
    						linkResAux.add(reconfigLink(lr, linkResources.serviceClass(), linkResources.serviceMethodName()));
    					}
    					linkPaginateEntity.put(pathAux, linkResAux);
    				}
    			}else{
    				linkResAux = new ArrayList<LinkResource>();
    				for(LinkResource lr : linkResources.value()){
    					linkResAux.add(lr);
    				}
    				linkPaginateEntity.put(path, linkResAux);
    			}
    		}else{
    			Link link;
    			for(LinkResource lr : linkResources.value()){
    				link = getLink(lr, uriInfo, null, responseContext.getEntity(), path, false);
    				if(link != null){
    					if(lr.target().equals(LinkTarget.ENTITY)){
    						linksEntity.add(link);
    					}else{
    						linksHeader.add(link);
    					}
    				}
    			}
    			if(!linkResources.serviceClass().equals(void.class)){
	    			Path pathAux = ReflectionUtil.getAnnotation(linkResources.serviceClass(), linkResources.serviceMethodName(), Path.class);
					LinkResources linkResourcesAux = ReflectionUtil.getAnnotation(linkResources.serviceClass(), linkResources.serviceMethodName(), LinkResources.class);

					if(linkResourcesAux != null){
						for(LinkResource lr : linkResourcesAux.value()){
							link = getLink(lr, uriInfo, null, responseContext.getEntity(), pathAux, false);
							if(link != null){
								if(lr.target().equals(LinkTarget.ENTITY)){
									linksEntity.add(link);
								}else{
									linksHeader.add(link);
								}
							}
						}
					}

					LinkResource linkResourceAux =  ReflectionUtil.getAnnotation(linkResources.serviceClass(), linkResources.serviceMethodName(), LinkResource.class);
					if(linkResourceAux != null){
						link = getLink(linkResourceAux, uriInfo, null, responseContext.getEntity(), pathAux, false);
						if(link != null){
							if(linkResourceAux.target().equals(LinkTarget.ENTITY)){
								linksEntity.add(link);
							}else{
								linksHeader.add(link);
							}
						}
					}
    			}
    		}
    	}

    	if(!paginateLinks.isEmpty()){
    		if(isHalLinks || linkPaginate.target().equals(LinkTarget.ENTITY)){
				linksEntity.addAll(paginateLinks);
			}else{
				linksHeader.addAll(paginateLinks);
			}
    	}

    	Collection<String> attrNotPresentInRequest = getRequiredParamNotPresentInRequest(serviceMethod, uriInfo);

    	if(!linksEntity.isEmpty() || (linkPaginateEntity != null && !linkPaginateEntity.isEmpty())){
    		if(!(responseContext.getEntity() instanceof Collection)){
    			if(isHalLinks || (linkFormat != null && linkFormat.value().equals(LinkFormatType.HAL))){
    				JsonHALLinkEntity json = new JsonHALLinkEntity();
        			json.setEntity(configEntityAttributes(responseContext.getEntity(), attrNotPresentInRequest));
        			json.addAllLink(linksEntity);
        			responseContext.setEntity(json);
    			}else{
	    			JsonLinkEntity json = new JsonLinkEntity();
	    			json.setEntity(configEntityAttributes(responseContext.getEntity(), attrNotPresentInRequest));
	    			json.addAllLink(linksEntity);
	    			responseContext.setEntity(json);
    			}
    		}else if(linkPaginate == null){
    			if(isHalLinks){
    				responseContext.setEntity(getCollectionEntityLink((Collection<Object>) responseContext.getEntity(), isHalLinks, linkPaginateEntity, uriInfo, attrNotPresentInRequest));
    			}
    		}else{
    			String childName;
    			if(linkPaginate != null && StringUtils.isNotBlank(linkPaginate.embeddedCollectionName())){
    				childName = linkPaginate.embeddedCollectionName();
    			}else{
    				childName = getChildClassName((Collection<Object>) responseContext.getEntity());
    				if(StringUtils.isBlank(childName)){
    					childName = "items";
    				}else{
    					childName += "Items";
    				}
    			}

    			JsonCollectionLinkEntity json = new JsonCollectionLinkEntity();
    			json.setHalLink(isHalLinks || linkFormat == null || linkFormat.value().equals(LinkFormatType.HAL));
    			if(isHalLinks){
    				json.setEmbedded(getCollectionEntityLink((Collection<Object>) responseContext.getEntity(), isHalLinks, linkPaginateEntity, uriInfo, attrNotPresentInRequest));
    			}else{
    				json.setEmbedded(getCollectionEntity((Collection<Object>) responseContext.getEntity(), attrNotPresentInRequest));
    			}

    			json.addAllLink(linksEntity);
    			json.setItemsName(childName);

    			responseContext.setEntity(json);

    			if(json.isHalLink()){
    				json.setTotalElements(responseContext.getHeaders().getFirst(DominiosRest.X_PAGINATION_TOTAL_ELEMENTS) == null ? null : Long.valueOf(responseContext.getHeaders().getFirst(DominiosRest.X_PAGINATION_TOTAL_ELEMENTS).toString()));
    				json.setElementsPerPage(responseContext.getHeaders().getFirst(DominiosRest.X_PAGINATION_ELEMENTS_PER_PAGE) == null ? null : Integer.valueOf(responseContext.getHeaders().getFirst(DominiosRest.X_PAGINATION_ELEMENTS_PER_PAGE).toString()));
    				json.setCurrentPage(responseContext.getHeaders().getFirst(DominiosRest.X_PAGINATION_CURRENT_PAGE) == null ? null : Integer.valueOf(responseContext.getHeaders().getFirst(DominiosRest.X_PAGINATION_CURRENT_PAGE).toString()));
    				json.setTotalPages(responseContext.getHeaders().getFirst(DominiosRest.X_PAGINATION_TOTAL_PAGE) == null ? null : Integer.valueOf(responseContext.getHeaders().getFirst(DominiosRest.X_PAGINATION_TOTAL_PAGE).toString()));

    				responseContext.getHeaders().remove(DominiosRest.X_PAGINATION_TOTAL_ELEMENTS);
    				responseContext.getHeaders().remove(DominiosRest.X_PAGINATION_ELEMENTS_PER_PAGE);
    				responseContext.getHeaders().remove(DominiosRest.X_PAGINATION_CURRENT_PAGE);
    				responseContext.getHeaders().remove(DominiosRest.X_PAGINATION_TOTAL_PAGE);
    			}
    		}
    	}else if(attrNotPresentInRequest != null && !attrNotPresentInRequest.isEmpty()){
    		if(responseContext.getEntity() instanceof Collection){
    			responseContext.setEntity(getCollectionEntity((Collection<Object>) responseContext.getEntity(), attrNotPresentInRequest));
    		}else if(responseContext.getEntity() instanceof Page){
    			((Page) responseContext.getEntity()).setElements(getCollectionEntity(((Page) responseContext.getEntity()).getElements(), attrNotPresentInRequest));
    		}else{
    			responseContext.setEntity(configEntityAttributes(responseContext.getEntity(), attrNotPresentInRequest));
    		}
    	}

    	if(!linksHeader.isEmpty()){
    		responseContext.getHeaders().add("Link", linksHeader);
    	}
    }

    /**
     * Retorno o valor do parametro para configurar o link corretamente
     * @param param
     * @param entity
     * @return
     */
    private String valueFromParameter(String param, Object entity){
    	Pattern pattern = Pattern.compile(REGEX_PATH_PARAMETERS_ENTITY);
    	Matcher m = pattern.matcher(param);

    	StringBuffer sb = new StringBuffer();

    	while(m.find()){
    		Object objRet = ReflectionUtil.getAttributteValue(entity, m.group().replaceAll(REGEX_REPLACE_PARAM, ""));
    		if(objRet == null){
    			return null;
    		}
    		m.appendReplacement(sb, objRet.toString());
    	}

    	m.appendTail(sb);

    	return sb.toString();
    }

    /**
     * Configura a entidade e seus objetos complexos filhos para null.
     * @param entity
     * @param listAttributes
     * @return
     */
    private Object configEntityAttributes(Object entity, Collection<String> listAttributes){
    	try {
    		if(listAttributes != null && !listAttributes.isEmpty()){
    			ReflectionUtil.setValueToNullCascade(entity, CollectionUtil.convertCollectionToArray(String.class, listAttributes));
    		}
		} catch (Exception e) {
			// Ignora o erro se nao conseguir setar para nulo
		}

    	return entity;
    }

    /**
     * Configura os links nos objetos da colecao
     * @param entityList
     * @param isHalLinks
     * @param linkResources
     * @param uriInfo
     * @param attrNotPresentInRequest
     * @return
     * @throws ApplicationException
     */
    private Collection<Object> getCollectionEntityLink(Collection<Object> entityList, boolean isHalLinks, Map<Path, List<LinkResource>> linkResources, UriInfo uriInfo, Collection<String> attrNotPresentInRequest) throws ApplicationException{
    	if(linkResources!=null && !linkResources.isEmpty()){
    		List<Object> entityCollection = new ArrayList<Object>(entityList.size());
    		List<Link> listLink = new ArrayList<Link>(2);
    		if(isHalLinks){
    			JsonHALLinkEntity json;
    			for(Object entity : entityList){
    				listLink.clear();
    				for(Path path : linkResources.keySet()){
    					for(LinkResource lr : linkResources.get(path)){
    						listLink.add(getLink(lr, uriInfo, null, entity, path, false));
    					}
    				}
    				json = new JsonHALLinkEntity();
					json.setEntity(configEntityAttributes(entity, attrNotPresentInRequest));
					json.addAllLink(listLink);

					entityCollection.add(json);
    			}
    		}else{
    			JsonLinkEntity json;
    			for(Object entity : entityList){
    				listLink.clear();
    				for(Path path : linkResources.keySet()){
    					for(LinkResource lr : linkResources.get(path)){
    						listLink.add(getLink(lr, uriInfo, null, entity, path, false));
    					}
    				}
    				json = new JsonLinkEntity();
					json.setEntity(configEntityAttributes(entity, attrNotPresentInRequest));
					json.addAllLink(listLink);

					entityCollection.add(json);
    			}
    		}
    		return entityCollection;
    	}else{
    		return getCollectionEntity(entityList, attrNotPresentInRequest);
    	}
    }
    /**
     *
     * @param entityList
     * @param attrNotPresentInRequest
     * @return
     * @throws ApplicationException
     */
    private Collection<Object> getCollectionEntity(Collection<Object> entityList, Collection<String> attrNotPresentInRequest) throws ApplicationException{
    	if(attrNotPresentInRequest != null && !attrNotPresentInRequest.isEmpty()){
    		List<Object> entityCollection = new ArrayList<Object>(entityList.size());
    		for(Object entity : entityList){
    			entityCollection.add(configEntityAttributes(entity, attrNotPresentInRequest));
    		}
    		return entityCollection;
    	}else{
    		return entityList;
    	}
    }
    /**
     * Configura o link
     * @param linkResource
     * @param uriInfo
     * @param queryParams
     * @param entity
     * @param path
     * @param forceAbsolutePath
     * @return
     * @throws ApplicationException
     */
    private Link getLink(LinkResource linkResource, UriInfo uriInfo, List<SimpleEntry<String, Object>> queryParams, Object entity, Path path, boolean forceAbsolutePath) throws ApplicationException{
    	return getLink(linkResource.pathParameters(), linkResource.queryParameters(), linkResource.serviceClass(), linkResource.serviceMethodName(), linkResource.basePath(), linkResource.includeRequestQueryParams(), linkResource.rel(), linkResource.type(), linkResource.title(), uriInfo, queryParams, entity, path, forceAbsolutePath);
    }
    /**
     * Configura o link
     * @param linkPathParameters
     * @param linkQueryParameter
     * @param linkServiceClass
     * @param linkServiceMethodName
     * @param linkBasePath
     * @param linkIncludeQueryParams
     * @param linkRel
     * @param linkType
     * @param linkTitle
     * @param uriInfo
     * @param queryParams
     * @param entity
     * @param path
     * @param forceAbsolutePath
     * @return
     * @throws ApplicationException
     */
    private Link getLink(String[] linkPathParameters, String[] linkQueryParameter, Class<?> linkServiceClass, String linkServiceMethodName, LinkResouceBasePath linkBasePath, boolean linkIncludeQueryParams, String linkRel, String linkType, String linkTitle, UriInfo uriInfo, List<SimpleEntry<String, Object>> queryParams, Object entity, Path path, boolean forceAbsolutePath) throws ApplicationException{
    	Builder builder;

    	List<Object> values = new LinkedList<Object>();
    	boolean linkTemplate = false;

    	Pattern pattern = Pattern.compile(REGEX_REQUEST_PATH_PARAMETERS);
    	Matcher mReqPathParam = pattern.matcher(path.toString());

    	List<String> reqPathParamOrder = new LinkedList<String>();

    	while(mReqPathParam.find()){
    		String mRAux = mReqPathParam.group();
    		reqPathParamOrder.add(mRAux.substring(1, mRAux.length() - 1));
    	}

    	for(String rpAux : reqPathParamOrder){
    		boolean test = true;
    		if(linkPathParameters != null && linkPathParameters.length > 0){
    			for(int i = 0; i < linkPathParameters.length; i++){
    				//if(linkPathParameters[i].equals("{" + rpAux + "}")){
    				if(StringUtils.isBlank(linkPathParameters[i])){
    					test = false;
    					values.add("");
    				}else if(linkPathParameters[i].matches(REGEX_PATH_PARAMETERS_REQ) && uriInfo.getPathParameters(false).get(rpAux) != null){
    					if(uriInfo.getPathParameters(false).get(rpAux).size() > 1){
    						values.add(uriInfo.getPathParameters(false).get(rpAux));
    					}else{
    						values.add(uriInfo.getPathParameters(false).getFirst(rpAux));
    					}
    				}else{
    					test = false;
    					if(linkPathParameters[i].matches(REGEX_LINK_TEMPLATE)){
    						linkTemplate = true;
    					}
    					values.add(valueFromParameter(linkPathParameters[i], entity));
    				}
    				//	}
    			}
    		}
    		if(test){
    			if(uriInfo.getPathParameters(false).get(rpAux) != null){
    				if(uriInfo.getPathParameters(false).get(rpAux).size() > 1){
    					values.add(uriInfo.getPathParameters(false).get(rpAux));
    				}else{
    					values.add(uriInfo.getPathParameters(false).getFirst(rpAux));
    				}
    			}else{
    				ApplicationException ae = new ApplicationException(MessageSeverity.ERROR, "link-response.field-not-found", rpAux);
    				logger.error("[getLink]", ae);
    				throw ae;
    			}
    		}
    	}

    	//Configura os PathParams adicionados, vinculados ao objeto de retorno
    	if(linkPathParameters != null && linkPathParameters.length > 0){
    		for(int i = 0; i < linkPathParameters.length; i++){
    			if(reqPathParamOrder.contains(linkPathParameters[i])){
    				continue;
    			}else if(StringUtils.isBlank(linkPathParameters[i])){
    				values.add("");
    			}else{
    				if(linkPathParameters[i].matches(REGEX_LINK_TEMPLATE)){
    					linkTemplate = true;
    				}
    				values.add(valueFromParameter(linkPathParameters[i], entity));
    			}
    		}
    	}

    	UriBuilder uriBuilder = null;

    	Class<?> serviceClassAux = linkServiceClass.equals(void.class) ? serviceClass : linkServiceClass;
    	String serviceMethodName = StringUtils.isBlank(linkServiceMethodName) ? serviceMethod.getName() : linkServiceMethodName;

    	if(linkBasePath.equals(LinkResouceBasePath.COMPLETE) || forceAbsolutePath){
    		uriBuilder = uriInfo.getBaseUriBuilder().path(serviceClassAux);
    		if(StringUtils.isNotBlank(linkServiceMethodName)){
    			uriBuilder.path(serviceClassAux, serviceMethodName);
    		}else{
    			uriBuilder.path(serviceMethod);
    		}
    	}else if(linkBasePath.equals(LinkResouceBasePath.RESOURCE)){
    		uriBuilder = UriBuilder.fromResource(serviceClassAux);
    	}else if(linkBasePath.equals(LinkResouceBasePath.METHOD)){
    		uriBuilder = UriBuilder.fromMethod(serviceClassAux, serviceMethodName);
    	}

    	if(linkIncludeQueryParams){// || queryParams != null){
    		for(String key : uriInfo.getQueryParameters().keySet()){
    			if(uriInfo.getQueryParameters(false).get(key).size() > 1) {
    				for(Object o : uriInfo.getQueryParameters(false).get(key)) {
    					uriBuilder.queryParam(key, o);
    				}
    				//uriBuilder.replaceQueryParam(key, uriInfo.getQueryParameters(false).get(key));
    			}else {
    				uriBuilder.replaceQueryParam(key, uriInfo.getQueryParameters(false).getFirst(key));
    			}
    		}
    	}

    	pattern = Pattern.compile(REGEX_LINK_TEMPLATE);

    	if(queryParams != null){
    		for(SimpleEntry<String, Object> qp : queryParams){
    			Matcher m = pattern.matcher(qp.getValue().toString());

    			StringBuffer sb = new StringBuffer();

    			while(m.find()){
    				linkTemplate = true;
    				String val = m.group().indexOf("{") == 1 ? m.group().substring(1) : m.group();
    				m.appendReplacement(sb, val);
    			}
    			if(linkTemplate){
    				m.appendTail(sb);
    				values.add(sb.toString());
    			}
    			uriBuilder.replaceQueryParam(qp.getKey(), qp.getValue());
    		}
    	}

    	if(linkQueryParameter != null && linkQueryParameter.length > 0){
    		for(int i = 0; i < linkQueryParameter.length; i++){
    			if(StringUtils.isNotBlank(linkQueryParameter[i])){
    				String paramName = linkQueryParameter[i].substring(0, linkQueryParameter[i].indexOf("="));
    				uriBuilder.replaceQueryParam(paramName, valueFromParameter(linkQueryParameter[i].substring(linkQueryParameter[i].indexOf("=") + 1), entity));
    			}
    		}
    	}

    	builder = Link.fromUriBuilder(uriBuilder).rel(linkRel);

    	if(StringUtils.isNotBlank(linkTitle)){
    		builder = builder.title(linkTitle);
    	}

    	if(StringUtils.isNotBlank(linkType)){
    		builder = builder.type(linkType);
    	}

    	if(linkTemplate){
    		builder.param("templated", "true");
    	}

    	try{
    		if(!values.isEmpty()){
    			Object[] valuesAux = values.toArray(new Object[]{});
    			return builder.build(valuesAux);
    		}else{
    			return builder.build();
    		}
    	}catch(IllegalArgumentException e){
    		logger.error("[getLink]", e);
    		throw new ApplicationException("error.link-builder", e);
    	}
    }
    /**
     * Configura o link de paginacao
     * @param entity
     * @param linkPaginate
     * @param uriInfo
     * @param path
     * @param headers
     * @return
     * @throws ApplicationException
     */
    private List<Link> getPaginateLink(Object entity, LinkPaginate linkPaginate, UriInfo uriInfo, Path path, MultivaluedMap<String, String> headers) throws ApplicationException{

    	if(StringUtils.isBlank(linkPaginate.pageParamName())){
    		return Collections.emptyList();
    	}

    	List<Link> paginationLinks = new ArrayList<Link>(4);

    	int pgAtual = 0;
    	int limitPg = 0;
    	long maxPgs = 0;

    	if(entity != null && entity instanceof Page){
    		Page<?> pEntity = (Page<?>) entity;

    		pgAtual = pEntity.getCurrentPage();
    		limitPg = pEntity.getElementsPerPage();

    	}else if(headers.containsKey(DominiosRest.X_PAGINATION_CURRENT_PAGE)
    				&& headers.containsKey(DominiosRest.X_PAGINATION_ELEMENTS_PER_PAGE)
    				&& headers.containsKey(DominiosRest.X_PAGINATION_TOTAL_PAGE)){

    		pgAtual = Integer.parseInt(headers.getFirst(DominiosRest.X_PAGINATION_CURRENT_PAGE));
        	limitPg = Integer.parseInt(headers.getFirst(DominiosRest.X_PAGINATION_ELEMENTS_PER_PAGE));
        	maxPgs = Long.parseLong(headers.getFirst(DominiosRest.X_PAGINATION_TOTAL_PAGE));
    	}else{
    		//Retorna lista vazia pois não tem parâmetros de paginaçao
    		return Collections.emptyList();
    	}

    	List<SimpleEntry<String, Object>> queryParams = new ArrayList<SimpleEntry<String, Object>>(2);

    	if(StringUtils.isNotBlank(linkPaginate.limitParamName())){
    		if(uriInfo.getQueryParameters().containsKey(linkPaginate.limitParamName())){
    			int limit = Integer.parseInt(uriInfo.getQueryParameters(false).getFirst(linkPaginate.limitParamName()));
    			if(limit > limitPg){
    				queryParams.add(new SimpleEntry<String, Object>(linkPaginate.limitParamName(), limitPg));
    			}
    		}else{
    			queryParams.add(new SimpleEntry<String, Object>(linkPaginate.limitParamName(), limitPg));
    		}
    	}

    	List<SimpleEntry<String, Object>> queryParamsAux = new ArrayList<SimpleEntry<String, Object>>(2);

    	//SELF
    	if(!linkPaginate.disableSelf()){
    		paginationLinks.add(getLink(linkPaginate.self(), uriInfo,  queryParams, entity, path, linkPaginate.absolutePath()));
    	}

    	//FIRST
    	if(!linkPaginate.disableFirst() && pgAtual > 1){
    		queryParamsAux.clear();
    		queryParamsAux.addAll(queryParams);
    		queryParamsAux.add(new SimpleEntry<String, Object>(linkPaginate.pageParamName(), 1));
    		paginationLinks.add(getLink(linkPaginate.first(), uriInfo, queryParamsAux, entity, path, linkPaginate.absolutePath()));
    	}

    	//PREVIOUS
    	if(!linkPaginate.disablePrevious() && pgAtual > 1){
    		queryParamsAux.clear();
    		queryParamsAux.addAll(queryParams);
    		queryParamsAux.add(new SimpleEntry<String, Object>(linkPaginate.pageParamName(), pgAtual - 1));
    		paginationLinks.add(getLink(linkPaginate.previous(), uriInfo, queryParamsAux, entity, path, linkPaginate.absolutePath()));
    	}

    	//NEXT
    	if(!linkPaginate.disableNext() && maxPgs > pgAtual){
    		queryParamsAux.clear();
    		queryParamsAux.addAll(queryParams);
    		queryParamsAux.add(new SimpleEntry<String, Object>(linkPaginate.pageParamName(), pgAtual + 1));
    		paginationLinks.add(getLink(linkPaginate.next(), uriInfo, queryParamsAux, entity, path, linkPaginate.absolutePath()));
    	}

    	//LAST
    	if(!linkPaginate.disableLast() && maxPgs > pgAtual){
    		queryParamsAux.clear();
    		queryParamsAux.addAll(queryParams);
    		queryParamsAux.add(new SimpleEntry<String, Object>(linkPaginate.pageParamName(), maxPgs));
    		paginationLinks.add(getLink(linkPaginate.last(), uriInfo, queryParamsAux, entity, path, linkPaginate.absolutePath()));
    	}

    	//Pagination Template
    	if(!linkPaginate.disablePaginationTemplate()){
    		queryParamsAux.clear();
    		queryParamsAux.addAll(queryParams);
    		queryParamsAux.add(new SimpleEntry<String, Object>(linkPaginate.pageParamName(), linkPaginate.paginationTemplate().pageParamName()));
    		if(linkPaginate.paginationTemplate().includeLimitParamTemplate()){
    			queryParamsAux.add(new SimpleEntry<String, Object>(linkPaginate.limitParamName(), linkPaginate.paginationTemplate().limitParamName()));
    		}
    		paginationLinks.add(getLink(linkPaginate.paginationTemplate().pathParameters(), linkPaginate.paginationTemplate().queryParameters(), linkPaginate.paginationTemplate().serviceClass(), linkPaginate.paginationTemplate().serviceMethodName(), linkPaginate.paginationTemplate().basePath(), linkPaginate.paginationTemplate().includeRequestQueryParams(), linkPaginate.paginationTemplate().rel(), linkPaginate.paginationTemplate().type(), linkPaginate.paginationTemplate().title(), uriInfo, queryParamsAux, entity, path, linkPaginate.absolutePath()));
    	}

    	return paginationLinks;
    }
    /**
     * @param list
     * @return
     */
	private <T> String getChildClassName(Collection<T> list){
    	if(list != null){
    		for(T obj: list){
    			Class<?> klass = obj.getClass();
    			if(klass.isAnnotationPresent(HalJsonRootName.class)){
    				return klass.getAnnotation(HalJsonRootName.class).value();
    			}else if(klass.isAnnotationPresent(JsonRootName.class)){
    				return klass.getAnnotation(JsonRootName.class).value();
    			}
    			return obj.getClass().getSimpleName();
    		}
    	}
    	return null;
    }
	/**
	 * Reconfigura a annotation de link
	 * @param link
	 * @param serviceClass
	 * @param serviceMethodName
	 * @return
	 */
    private LinkResource reconfigLink(LinkResource link, Class<?> serviceClass, String serviceMethodName){
    	return new LinkResource() {
			@Override
			public Class<? extends Annotation> annotationType() {
				return link.annotationType();
			}
			@Override
			public String type() {
				return link.type();
			}
			@Override
			public String title() {
				return link.title();
			}

			@Override
			public LinkTarget target() {
				return link.target();
			}
			@Override
			public String serviceMethodName() {
				return serviceMethodName;
			}
			@Override
			public Class<?> serviceClass() {
				return serviceClass;
			}
			@Override
			public String rel() {
				return link.rel();
			}
			@Override
			public String[] pathParameters() {
				return link.pathParameters();
			}
			@Override
			public boolean includeRequestQueryParams() {
				return link.includeRequestQueryParams();
			}
			@Override
			public LinkResouceBasePath basePath() {
				return link.basePath();
			}
			@Override
			public String[] queryParameters() {
				return link.queryParameters();
			}
		};
    }
    /**
     * Retorna o parametro obrigatorio para a cricao do link mas que nao esta na lista de parametros solicitados na requisicao,
     * utilizado para remover o parametro da resposta
     * @param serviceMethod
     * @param uriInfo
     * @return
     * @throws ApplicationException
     */
	private Collection<String> getRequiredParamNotPresentInRequest(Method serviceMethod, UriInfo uriInfo) throws ApplicationException {

		Annotation[][] parametrosAnotados = serviceMethod.getParameterAnnotations();
		Class<?>[] parameterTypes = serviceMethod.getParameterTypes();

		QueryParam queryParam = null;
		WSParamFormat wsParam = null;
		DefaultValue defValue = null;

		for(int i=0; i < parametrosAnotados.length; i++){
			Annotation[] parametroAnotado = parametrosAnotados[i];
			if(parameterTypes[i].equals(WSFieldParam.class)){
				for(Annotation a : parametroAnotado){
					if(a instanceof QueryParam){
						queryParam = (QueryParam) a;
					}else if( a instanceof WSParamFormat){
						wsParam = (WSParamFormat) a;
					}else if(a instanceof DefaultValue){
						defValue = (DefaultValue) a;
					}
				}
				break;
			}
		}

		if(queryParam == null || wsParam == null){
			return null;
		}

		List<LinkResource> listResources = new ArrayList<LinkResource>(1);
		listResources.addAll(paramFields(serviceMethod));

		if(!listResources.isEmpty()){
			Pattern pattern = Pattern.compile(REGEX_PATH_PARAMETERS_ENTITY);
			Matcher matcher;
			Set<String> listParamsRemove = new HashSet<String>();

			Set<String> listParams = new HashSet<String>();
			if(uriInfo.getQueryParameters().containsKey(queryParam.value())){
				listParams.addAll(uriInfo.getQueryParameters(false).get(queryParam.value()));
			}

			//Campos forcados na annotation
			for(String f : wsParam.forceFields()){
				if(!listParams.contains(f)){
					listParams.add(f);
				}
			}

			if(listParams.isEmpty() && defValue != null){
				for(String dAux : defValue.value().split(",")){
					listParams.add(dAux);
				}
			}

			for(LinkResource linkResource : listResources){
				String mGroup;
				for(String qp : linkResource.queryParameters()){
					matcher = pattern.matcher(qp);
					while(matcher.find()){
						mGroup = matcher.group().replaceAll(REGEX_REPLACE_PARAM, "");
						if(!CollectionUtil.constainsValue(listParams, mGroup)){
							listParamsRemove.add(mGroup);
						}
					}
				}

				for(String qp : linkResource.pathParameters()){
					matcher = pattern.matcher(qp);
					while(matcher.find()){
						mGroup = matcher.group().replaceAll(REGEX_REPLACE_PARAM, "");
						if(!CollectionUtil.constainsValue(listParams, mGroup)){
							listParamsRemove.add(mGroup);
						}
					}
				}
			}
			return listParamsRemove;
		}
		return null;
	}

	/**
	 * Parametros exigidos no metedo para criacao do link
	 * @param method
	 * @return
	 */
	private List<LinkResource> paramFields(Method method){
		Annotation[][] parametrosAnotados = method.getParameterAnnotations();
		Class<?>[] parameterTypes = method.getParameterTypes();

		WSParamFormat wsAnnotation = null;

		for(int i=0; i < parametrosAnotados.length; i++){
			Annotation[] parametroAnotado = parametrosAnotados[i];
			if(parameterTypes[i].equals(WSFieldParam.class)){
				for(Annotation a : parametroAnotado){
					if(a instanceof WSParamFormat){
						wsAnnotation = (WSParamFormat) a;
					}
				}
				break;
			}
		}

		if(wsAnnotation != null){
			List<LinkResource> listResources = new ArrayList<LinkResource>(1);

			LinkResource lr = method.getAnnotation(LinkResource.class);
			LinkResources lrs = method.getAnnotation(LinkResources.class);
			LinkPaginate lp = method.getAnnotation(LinkPaginate.class);

			if(lr != null){
				listResources.add(lr);
			}

			if(lrs != null){
				if(lrs.value().length > 0){
					listResources.addAll(CollectionUtil.convertArrayToList(lrs.value()));
				}
				if(!lrs.serviceClass().equals(void.class)){
					listResources.addAll(paramFields(ReflectionUtil.getMethod(lrs.serviceClass(), lrs.serviceMethodName())));
				}
			}

			if(lp != null){
				if(lp.collectionLinks().value().length > 0){
					listResources.addAll(CollectionUtil.convertArrayToList(lp.collectionLinks().value()));
				}

				if(!lp.collectionLinks().serviceClass().equals(void.class)){
					listResources.addAll(paramFields(ReflectionUtil.getMethod(lp.collectionLinks().serviceClass(), lp.collectionLinks().serviceMethodName())));
				}
			}

			return listResources;
		}
		return null;
	}

	/**
	 *
	 * @param value
	 * @return
	 */
	public static String toSnakeCase(String value){
		return  value.replaceAll("([A-Z]+)","\\_$1").toLowerCase();
	}
	/**
	 *
	 * @param value
	 * @return
	 */
	public static String toCamelCase(String value){
		StringBuilder sb = new StringBuilder();
		for (String s : value.split("_")) {
			if(sb.length() > 1){
				sb.append(Character.toUpperCase(s.charAt(0)));
				if (s.length() > 1) {
					sb.append(s.substring(1, s.length()).toLowerCase());
				}
			}else{
				sb.append(s.toLowerCase());
			}
		}

		return  sb.toString();
	}
}


text:
namespace syncer {

namespace {

class P2PInvalidatorTestDelegate {
 public:
  P2PInvalidatorTestDelegate() : fake_push_client_(NULL) {}

  ~P2PInvalidatorTestDelegate() {
    DestroyInvalidator();
  }

  void CreateInvalidator(
      const std::string& invalidator_client_id,
      const std::string& initial_state,
      const base::WeakPtr<InvalidationStateTracker>&
          invalidation_state_tracker) {
    DCHECK(!fake_push_client_);
    DCHECK(!invalidator_.get());
    fake_push_client_ = new notifier::FakePushClient();
    invalidator_.reset(
        new P2PInvalidator(
            scoped_ptr<notifier::PushClient>(fake_push_client_),
            invalidator_client_id,
            NOTIFY_OTHERS));
  }

  P2PInvalidator* GetInvalidator() {
    return invalidator_.get();
  }

  notifier::FakePushClient* GetPushClient() {
    return fake_push_client_;
  }

  void DestroyInvalidator() {
    invalidator_.reset();
    fake_push_client_ = NULL;
  }

  void WaitForInvalidator() {
    // Do Nothing.
  }

  void TriggerOnInvalidatorStateChange(InvalidatorState state) {
    if (state == INVALIDATIONS_ENABLED) {
      fake_push_client_->EnableNotifications();
    } else {
      fake_push_client_->DisableNotifications(ToNotifierReasonForTest(state));
    }
  }

  void TriggerOnIncomingInvalidation(
      const ObjectIdInvalidationMap& invalidation_map) {
    const P2PNotificationData notification_data(
        std::string(), NOTIFY_ALL, invalidation_map);
    notifier::Notification notification;
    notification.channel = kSyncP2PNotificationChannel;
    notification.data = notification_data.ToString();
    fake_push_client_->SimulateIncomingNotification(notification);
  }

 private:
  // Owned by |invalidator_|.
  notifier::FakePushClient* fake_push_client_;
  scoped_ptr<P2PInvalidator> invalidator_;
};

class P2PInvalidatorTest : public testing::Test {
 protected:
  P2PInvalidatorTest()
      : next_sent_notification_to_reflect_(0) {
    default_enabled_ids_.insert(invalidation::ObjectId(10, "A"));
    default_enabled_ids_.insert(invalidation::ObjectId(10, "B"));
    delegate_.CreateInvalidator("sender",
                                "fake_state",
                                base::WeakPtr<InvalidationStateTracker>());
    delegate_.GetInvalidator()->RegisterHandler(&fake_handler_);
  }

  virtual ~P2PInvalidatorTest() {
    delegate_.GetInvalidator()->UnregisterHandler(&fake_handler_);
  }

  ObjectIdInvalidationMap MakeInvalidationMap(ObjectIdSet ids) {
    return ObjectIdInvalidationMap::InvalidateAll(ids);
  }

  // Simulate receiving all the notifications we sent out since last
  // time this was called.
  void ReflectSentNotifications() {
    const std::vector<notifier::Notification>& sent_notifications =
        delegate_.GetPushClient()->sent_notifications();
    for(size_t i = next_sent_notification_to_reflect_;
        i < sent_notifications.size(); ++i) {
      delegate_.GetInvalidator()->OnIncomingNotification(sent_notifications[i]);
    }
    next_sent_notification_to_reflect_ = sent_notifications.size();
  }

  ObjectIdSet default_enabled_ids_;

  FakeInvalidationHandler fake_handler_;
  P2PInvalidatorTestDelegate delegate_;

 private:
  size_t next_sent_notification_to_reflect_;
};

// Make sure the P2PNotificationTarget <-> string conversions work.
TEST_F(P2PInvalidatorTest, P2PNotificationTarget) {
  for (int i = FIRST_NOTIFICATION_TARGET;
       i <= LAST_NOTIFICATION_TARGET; ++i) {
    P2PNotificationTarget target = static_cast<P2PNotificationTarget>(i);
    const std::string& target_str = P2PNotificationTargetToString(target);
    EXPECT_FALSE(target_str.empty());
    EXPECT_EQ(target, P2PNotificationTargetFromString(target_str));
  }
  EXPECT_EQ(NOTIFY_SELF, P2PNotificationTargetFromString("unknown"));
}

// Make sure notification targeting works correctly.
TEST_F(P2PInvalidatorTest, P2PNotificationDataIsTargeted) {
  {
    const P2PNotificationData notification_data(
        "sender", NOTIFY_SELF, ObjectIdInvalidationMap());
    EXPECT_TRUE(notification_data.IsTargeted("sender"));
    EXPECT_FALSE(notification_data.IsTargeted("other1"));
    EXPECT_FALSE(notification_data.IsTargeted("other2"));
  }
  {
    const P2PNotificationData notification_data(
        "sender", NOTIFY_OTHERS, ObjectIdInvalidationMap());
    EXPECT_FALSE(notification_data.IsTargeted("sender"));
    EXPECT_TRUE(notification_data.IsTargeted("other1"));
    EXPECT_TRUE(notification_data.IsTargeted("other2"));
  }
  {
    const P2PNotificationData notification_data(
        "sender", NOTIFY_ALL, ObjectIdInvalidationMap());
    EXPECT_TRUE(notification_data.IsTargeted("sender"));
    EXPECT_TRUE(notification_data.IsTargeted("other1"));
    EXPECT_TRUE(notification_data.IsTargeted("other2"));
  }
}

// Make sure the P2PNotificationData <-> string conversions work for a
// default-constructed P2PNotificationData.
TEST_F(P2PInvalidatorTest, P2PNotificationDataDefault) {
  const P2PNotificationData notification_data;
  EXPECT_TRUE(notification_data.IsTargeted(std::string()));
  EXPECT_FALSE(notification_data.IsTargeted("other1"));
  EXPECT_FALSE(notification_data.IsTargeted("other2"));
  EXPECT_TRUE(notification_data.GetIdInvalidationMap().Empty());
  const std::string& notification_data_str = notification_data.ToString();
  EXPECT_EQ(
      "{\"invalidations\":[],\"notificationType\":\"notifySelf\","
      "\"senderId\":\"\"}", notification_data_str);

  P2PNotificationData notification_data_parsed;
  EXPECT_TRUE(notification_data_parsed.ResetFromString(notification_data_str));
  EXPECT_TRUE(notification_data.Equals(notification_data_parsed));
}

// Make sure the P2PNotificationData <-> string conversions work for a
// non-default-constructed P2PNotificationData.
TEST_F(P2PInvalidatorTest, P2PNotificationDataNonDefault) {
  ObjectIdInvalidationMap invalidation_map =
      ObjectIdInvalidationMap::InvalidateAll(default_enabled_ids_);
  const P2PNotificationData notification_data("sender",
                                              NOTIFY_ALL,
                                              invalidation_map);
  EXPECT_TRUE(notification_data.IsTargeted("sender"));
  EXPECT_TRUE(notification_data.IsTargeted("other1"));
  EXPECT_TRUE(notification_data.IsTargeted("other2"));
  EXPECT_EQ(invalidation_map, notification_data.GetIdInvalidationMap());
  const std::string& notification_data_str = notification_data.ToString();
  EXPECT_EQ(
      "{\"invalidations\":["
      "{\"isUnknownVersion\":true,"
      "\"objectId\":{\"name\":\"A\",\"source\":10}},"
      "{\"isUnknownVersion\":true,"
      "\"objectId\":{\"name\":\"B\",\"source\":10}}"
      "],\"notificationType\":\"notifyAll\","
      "\"senderId\":\"sender\"}",
      notification_data_str);

  P2PNotificationData notification_data_parsed;
  EXPECT_TRUE(notification_data_parsed.ResetFromString(notification_data_str));
  EXPECT_TRUE(notification_data.Equals(notification_data_parsed));
}

// Set up the P2PInvalidator, simulate a successful connection, and send
// a notification with the default target (NOTIFY_OTHERS).  The
// observer should receive only a notification from the call to
// UpdateEnabledTypes().
TEST_F(P2PInvalidatorTest, NotificationsBasic) {
  P2PInvalidator* const invalidator = delegate_.GetInvalidator();
  notifier::FakePushClient* const push_client = delegate_.GetPushClient();

  invalidator->UpdateRegisteredIds(&fake_handler_, default_enabled_ids_);

  const char kEmail[] = "foo@bar.com";
  const char kToken[] = "token";
  invalidator->UpdateCredentials(kEmail, kToken);
  {
    notifier::Subscription expected_subscription;
    expected_subscription.channel = kSyncP2PNotificationChannel;
    expected_subscription.from = kEmail;
    EXPECT_TRUE(notifier::SubscriptionListsEqual(
        push_client->subscriptions(),
        notifier::SubscriptionList(1, expected_subscription)));
  }
  EXPECT_EQ(kEmail, push_client->email());
  EXPECT_EQ(kToken, push_client->token());

  ReflectSentNotifications();
  push_client->EnableNotifications();
  EXPECT_EQ(INVALIDATIONS_ENABLED, fake_handler_.GetInvalidatorState());

  ReflectSentNotifications();
  EXPECT_EQ(1, fake_handler_.GetInvalidationCount());
  EXPECT_THAT(MakeInvalidationMap(default_enabled_ids_),
              Eq(fake_handler_.GetLastInvalidationMap()));

  // Sent with target NOTIFY_OTHERS so should not be propagated to
  // |fake_handler_|.
  invalidator->SendInvalidation(default_enabled_ids_);

  ReflectSentNotifications();
  EXPECT_EQ(1, fake_handler_.GetInvalidationCount());
}

// Set up the P2PInvalidator and send out notifications with various
// target settings.  The notifications received by the observer should
// be consistent with the target settings.
TEST_F(P2PInvalidatorTest, SendNotificationData) {
  ObjectIdSet enabled_ids;
  ObjectIdSet changed_ids;
  ObjectIdSet expected_ids;

  enabled_ids.insert(invalidation::ObjectId(20, "A"));
  enabled_ids.insert(invalidation::ObjectId(20, "B"));
  enabled_ids.insert(invalidation::ObjectId(20, "C"));

  changed_ids.insert(invalidation::ObjectId(20, "A"));
  changed_ids.insert(invalidation::ObjectId(20, "Z"));

  expected_ids.insert(invalidation::ObjectId(20, "A"));

  const ObjectIdInvalidationMap& invalidation_map =
      MakeInvalidationMap(changed_ids);

  P2PInvalidator* const invalidator = delegate_.GetInvalidator();
  notifier::FakePushClient* const push_client = delegate_.GetPushClient();

  invalidator->UpdateRegisteredIds(&fake_handler_, enabled_ids);

  invalidator->UpdateCredentials("foo@bar.com", "fake_token");

  ReflectSentNotifications();
  push_client->EnableNotifications();
  EXPECT_EQ(INVALIDATIONS_ENABLED, fake_handler_.GetInvalidatorState());

  ReflectSentNotifications();
  EXPECT_EQ(1, fake_handler_.GetInvalidationCount());
  EXPECT_EQ(enabled_ids, fake_handler_.GetLastInvalidationMap().GetObjectIds());

  // Should be dropped.
  invalidator->SendNotificationDataForTest(P2PNotificationData());
  ReflectSentNotifications();
  EXPECT_EQ(1, fake_handler_.GetInvalidationCount());

  // Should be propagated.
  invalidator->SendNotificationDataForTest(
      P2PNotificationData("sender", NOTIFY_SELF, invalidation_map));
  ReflectSentNotifications();
  EXPECT_EQ(2, fake_handler_.GetInvalidationCount());
  EXPECT_EQ(expected_ids,
            fake_handler_.GetLastInvalidationMap().GetObjectIds());

  // Should be dropped.
  invalidator->SendNotificationDataForTest(
      P2PNotificationData("sender2", NOTIFY_SELF, invalidation_map));
  ReflectSentNotifications();
  EXPECT_EQ(2, fake_handler_.GetInvalidationCount());

  // Should be dropped.
  invalidator->SendNotificationDataForTest(
      P2PNotificationData("sender", NOTIFY_SELF, ObjectIdInvalidationMap()));
  ReflectSentNotifications();
  EXPECT_EQ(2, fake_handler_.GetInvalidationCount());

  // Should be dropped.
  invalidator->SendNotificationDataForTest(
      P2PNotificationData("sender", NOTIFY_OTHERS, invalidation_map));
  ReflectSentNotifications();
  EXPECT_EQ(2, fake_handler_.GetInvalidationCount());

  // Should be propagated.
  invalidator->SendNotificationDataForTest(
      P2PNotificationData("sender2", NOTIFY_OTHERS, invalidation_map));
  ReflectSentNotifications();
  EXPECT_EQ(3, fake_handler_.GetInvalidationCount());
  EXPECT_EQ(expected_ids,
            fake_handler_.GetLastInvalidationMap().GetObjectIds());

  // Should be dropped.
  invalidator->SendNotificationDataForTest(
      P2PNotificationData("sender2", NOTIFY_OTHERS, ObjectIdInvalidationMap()));
  ReflectSentNotifications();
  EXPECT_EQ(3, fake_handler_.GetInvalidationCount());

  // Should be propagated.
  invalidator->SendNotificationDataForTest(
      P2PNotificationData("sender", NOTIFY_ALL, invalidation_map));
  ReflectSentNotifications();
  EXPECT_EQ(4, fake_handler_.GetInvalidationCount());
  EXPECT_EQ(expected_ids,
            fake_handler_.GetLastInvalidationMap().GetObjectIds());

  // Should be propagated.
  invalidator->SendNotificationDataForTest(
      P2PNotificationData("sender2", NOTIFY_ALL, invalidation_map));
  ReflectSentNotifications();
  EXPECT_EQ(5, fake_handler_.GetInvalidationCount());
  EXPECT_EQ(expected_ids,
            fake_handler_.GetLastInvalidationMap().GetObjectIds());

  // Should be dropped.
  invalidator->SendNotificationDataForTest(
  P2PNotificationData("sender2", NOTIFY_ALL, ObjectIdInvalidationMap()));
  ReflectSentNotifications();
  EXPECT_EQ(5, fake_handler_.GetInvalidationCount());
}

INSTANTIATE_TYPED_TEST_CASE_P(
    P2PInvalidatorTest, InvalidatorTest,
    P2PInvalidatorTestDelegate);

}  // namespace

}  // namespace syncer

redpajama_set_name: RedPajamaGithub


text:
package com.macasaet.fernet.jersey.example.common;

import java.security.SecureRandom;
import java.util.Collection;
import java.util.function.Supplier;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.macasaet.fernet.Key;
import com.macasaet.fernet.Token;
import com.macasaet.fernet.Validator;

/**
 * This is an example of a resource that generates a Fernet token. Here, the
 * Fernet token identifies a session. Once a client has started a session using
 * this resource, they can issue requests by providing only the token they have
 * been provided. They do not need to provide login credentials again until the
 * session expires or is revoked.
 *
 *
Copyright © 2017 Carlos Macasaet.

 *
 * @author Carlos Macasaet
 */
@Path("session")
public class AuthenticationResource {

	private final SecureRandom random = new SecureRandom();

	@Inject
	private PasswordService passwordService;
	@Inject
	private SessionRepository sessionRepository;
	@Inject
	private Validator<Session> sessionValidator;

    /**
     * This provides the secret keys. There is no need to share the keys
     * with the client. The resource that generates the tokens and the
     * resource that validates the tokens need not share the same
     * infrastructure as long as they both have access to the same keys.
     */
	@Inject
	private Supplier<Collection<Key>> keySupplier;

	/**
	 * This is an example of an endpoint that generates a new Fernet token. The
	 * client authenticates using this method then can use the token provided to
	 * perform secured operations. The client may, at their discretion, store
	 * the token insecurely (e.g. in a cookie or browser storage) since it will
	 * no longer be valid after the TTL (60 seconds by default).
	 *
	 * @param request
	 *            client credentials to create a new session token
	 * @return a Fernet token
	 */
	@POST
	@Produces(MediaType.TEXT_PLAIN)
	@Consumes(MediaType.APPLICATION_JSON)
	public String createSession(final LoginRequest request) {
		final User user = passwordService.authenticateUser(request.getUsername(), request.getPlainTextPassword());
		if (user != null) {
			// password is correct, so generate an ephemeral session
		    // store the session ID in the token payload
		    final Session session = new Session(request.getUsername());
		    sessionRepository.saveSession(session);

		    final Key key = keySupplier.get().iterator().next();
			final Token token = Token.generate(random, key, session.getId().toString());
			return token.serialise();
		}
		throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).entity("invalid login").build());
	}

	@Path("/revocation")
	@PUT
	@Consumes(MediaType.TEXT_PLAIN)
    public void revokeSession(final String sessionToken) {
        final Token token = Token.fromString(sessionToken);

        // ensure this is a valid token and a non-revoked session
        final Session session = sessionValidator.validateAndDecrypt(keySupplier.get(), token);
        if (session != null) {
            // revoke the session for all associated Fernet tokens
            session.revoke();
            sessionRepository.revokeSession(session);
        }
    }

	@Path("/renewal")
	@PUT
	@Consumes(MediaType.TEXT_PLAIN)
	@Produces(MediaType.TEXT_PLAIN)
    public String renewSession(final String sessionToken) {
        final Token oldToken = Token.fromString(sessionToken);
        // ensure this is a valid token and a non-revoked session
        // if valid, extend the life of the session
        final Session session = sessionValidator.validateAndDecrypt(keySupplier.get(), oldToken);
        if (session != null) {
            // the session is valid, generate a new token
            // both the old and new tokens are valid, but the old one will expire
            // sooner as governed by the Fernet spec
            // revoking the session will revoke all associated Fernet tokens
            final Key key = keySupplier.get().iterator().next();
            final Token newToken = Token.generate(random, key, session.getId().toString());
            return newToken.serialise();
        }
        throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).entity("invalid session token").build());
    }

}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\date\DatePicker;
use yii\helpers\ArrayHelper;
use wbraganca\dynamicform\DynamicFormWidget;
use app\models\Product;
use app\models\Customer;
/* @var $this yii\web\View */
/* @var $model app\models\Delivery */
/* @var $form yii\widgets\ActiveForm */

$js = <<<JS
function updateMoney(){
    var money = new Number(0);
    $(".detail-total").each(function(){
    var detail = new Number($(this).html());
    money += detail;
    });
    $("#delivery-money").val(money.toFixed(2));
}

var prices;
$(document).ready(function(){
    $.post("index.php?r=product/prices",function (data) {
        prices = JSON.parse(data);
    });
});

function getPrice(id) {
    var toReturn;
    $.each(prices, function(i,v){
        if(v.id == id){
            if(v.unit == "B") {
                toReturn = v.price;
            } else {
                toReturn = (v.price * v.specification).toFixed(2);
            }
            return false;
        }
    });
    return toReturn;
}

$("body").on("change",".detail-product-id", function handleProduct(){
    var count_item = $(this).parent().parent().next().children().children(".detail-count");
    var price_item = count_item.parent().parent().next().children().children(".detail-price");
    var total_item = price_item.parent().parent().next().children("em");
    count = count_item.val()
    console.log("count:"+count);
    var product_id = $(this).val();
    if(product_id !== ""){
        price = getPrice(product_id);
        price_item.val(price);
        if(count !="") {
            console.log("total:"+ price*count);
             total_item.html((price * count).toFixed(2));
        }
    }else{
        price_item.val("0.00");
        total_item.html("0.00");
    }
    updateMoney();
});

$("body").on("change",".detail-count",function() {
    var product_item = $(this).parent().parent().prev().children().children(".detail-product-id");
    var price_item = $(this).parent().parent().next().children().children(".detail-price");
    var total_item = $(this).parent().parent().next().next().children("em");
    count = $(this).val();
    var product_id = product_item.val();
    if(!isNaN(count) && product_id != ""){
        price = price_item.val();
        total_item.html((price * count).toFixed(2));
        updateMoney();
    }
});

$("body").on("change", ".detail-price", function() {
    var count_item = $(this).parent().parent().prev().children().children(".detail-count");
    var total_item = $(this).parent().parent().next().children("em");
    total_item.html(($(this).val() * count_item.val()).toFixed(2));
    updateMoney();
});
JS;

$this->registerJs($js, $this::POS_END);
?>

    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>

            <?= Yii::t('app', 'Time') ?>
            <?= DatePicker::widget([
                'id' => 'delivery-time',
                'name' => 'Delivery[time]',
                'value' => $model->time ? $model->time :date('Y-m-d', strtotime('today')),
                'options' => ['placeholder' => Yii::t('app','Select Time')],
                'pluginOptions' => [
                    'format' => 'yyyy-m-dd',
                    'todayHighLight' => true,
                ]
            ]);?>

            <?= $form->field($model, 'customer_id')->dropDownList(
                ArrayHelper::map(Customer::find()->all(), 'id', 'name'),
                ['prompt' => Yii::t('app','Select Customer')]
            ) ?>
            <?= $form->field($model, 'money')->textInput() ?>

                <?php DynamicFormWidget::begin([
                    'widgetContainer' => 'dynamicform_wrapper',
                    'widgetBody' => '.container-items',
                    'widgetItem' => '.item',
                    'limit' => 10,
                    'min' => 1,
                    'insertButton' => '.add-item',
                    'deleteButton' => '.remove-item',
                    'model' => $modelDetails[0],
                    'formId' => 'dynamic-form',
                    'formFields' => [
                        'product_id',
                        'count',
                        'price'
                    ],
                ]); ?>

                    <?php foreach ($modelDetails as $i => $modelDetail): ?>

<?= Yii::t('app', 'Product') ?>

                                    <button type="button" class="add-item btn btn-success btn-xs"></button>
                                    <button type="button" class="remove-item btn btn-danger btn-xs"></button>

                                <?php
                                // necessary for update action.
                                if (! $modelDetail->isNewRecord) {
                                    echo Html::activeHiddenInput($modelDetail, "[{$i}]id");
                                }
                                ?>

                                        <?= $form->field($modelDetail, "[{$i}]product_id")->dropDownList(
                                            ArrayHelper::map(Product::find()->all(), 'id', 'name'),
                                            [
                                                'prompt' => Yii::t('app','Select Product'),
                                                'class' => 'form-control detail-product-id',
                                            ]
                                        );?>

                                        <?= $form->field($modelDetail, "[{$i}]count")->textInput([
                                            'maxlength' => true,
                                            'class' => 'form-control detail-count',
                                        ]) ?>

                                        <?= $form->field($modelDetail, "[{$i}]price")->textInput([
                                            'maxlength' => true,
                                            'class' => 'form-control detail-price',
                                        ]) ?>

                                        <?= Yii::t('app', 'Total').' : ' ?>

                                        <?php
                                        if ($modelDetail->price){
                                            echo number_format($modelDetail->price * $modelDetail->count, 2, '.','');
                                        }else{
                                            echo '0.00';
                                        }
                                        ?>

                    <?php endforeach; ?>

                <?php DynamicFormWidget::end(); ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
package com.twitter.finagle.memcached

import _root_.java.net.SocketAddress
import com.twitter.finagle.builder.{Server => BuiltServer, ServerBuilder}
import com.twitter.finagle.memcached.protocol.text
import com.twitter.finagle.memcached.util.AtomicMap
import com.twitter.io.Buf
import com.twitter.util.{Await, SynchronizedLruMap}

/**
 * An in-process memcached server.
 */
@deprecated("Moved into test", "7.0.0")
class Server(address: SocketAddress) {
  val concurrencyLevel = 16
  val slots = 500000
  val slotsPerLru = slots / concurrencyLevel
  val maps = (0 until concurrencyLevel) map { i =>
    new SynchronizedLruMap[Buf, Entry](slotsPerLru)
  }

  private[this] val service = {
    val interpreter = new Interpreter(new AtomicMap(maps))
    new InterpreterService(interpreter)
  }

  private[this] val serverSpec =
    ServerBuilder()
      .name("finagle")
      .codec(text.Memcached())
      .bindTo(address)

  private[this] var server: Option[BuiltServer] = None

  def start(): BuiltServer = {
    server = Some(serverSpec.build(service))
    server.get
  }

  def stop(blocking: Boolean = false) {
    server.foreach { server =>
      if (blocking) Await.result(server.close())
      else server.close()
      this.server = None
    }
  }
}


text:
package eu.bcvsolutions.idm.core.model.event;

import java.io.Serializable;
import java.util.Map;

import eu.bcvsolutions.idm.core.api.dto.IdmConfigurationDto;
import eu.bcvsolutions.idm.core.api.event.CoreEvent;
import eu.bcvsolutions.idm.core.api.event.EventType;

/**
 * Events for code lists
 *
 * @author Radek Tomiška
 * @since 10.0.0
 */
public class ConfigurationEvent extends CoreEvent<IdmConfigurationDto> {

	private static final long serialVersionUID = 1L;

	/**
	 * Supported core configuration events
	 *
	 */
	public enum ConfigurationEventType implements EventType {
		CREATE,
		UPDATE,
		DELETE
	}

	public ConfigurationEvent(ConfigurationEventType operation, IdmConfigurationDto content) {
		super(operation, content);
	}

	public ConfigurationEvent(ConfigurationEventType operation, IdmConfigurationDto content, Map<String, Serializable> properties) {
		super(operation, content, properties);
	}

}


text:
<?php
/**
 * Página estática: Contato
 */
include("login_acesso.php");
include_once("instalacao.php");
include_once("inc/funcoes.php");
include_once("inc/cabecalho.php");
include_once("inc/menu-cabecalho.php");
?>

<?php include_once("inc/menu-painel.php"); ?>

Contato

Suporte:

No momento não temos como oferecer um suporte pessoal para cada usuário do sistema, entretanto, caso necessite de ajuda, entre em contato conosco por e-mail que tentaremos lhe ajudar. Tente nos explicar da melhor forma possível o que está acontecendo, e qual é a dificuldade encontrada, certo? Nosso e-mail é contato@biblioteca.cc

Notificações de erros:

Ninguém melhor do que quem usa o código diariamente para nos reportar a necessidade de melhorias. E queremos saber de você, usuário, caso encontre erros durante a sua utilização diária. Nosso e-mail de notificações é erros@biblioteca.cc

Gostou e quer ajudar?

Entre em contato conosco por e-mail ou pelas redes sociais, e vamos conversar sobre como podemos trabalhar juntos. Nosso e-mail é contato@biblioteca.cc

Nos dê um olá:

Se você só quer nos dizer oi ou nos mandar um sorriso, estamos no twitter, @gruhn e @ffagundes10.

<?php include_once("inc/rodape.php"); ?>


text:
using System.Collections.Generic;

namespace FuncSharp
{
    public static class IReadOnlyDictionaryExtensions
    {
        public static IOption<V> Get<K, V>(this IReadOnlyDictionary<K, V> dictionary, K key)
        {
            if (Equals(key, null))
            {
                return Option.Empty<V>();
            }
            return Tryer.Invoke<K, V>(dictionary.TryGetValue, key);
        }
    }
}


text:
import hashlib

# test trivial operations
h = hashlib.sha256()
h.update(b'pycom')
print(h.digest())

print(hashlib.sha256(b'pycom').digest())

h = hashlib.sha256(b'pycom')
h.update(b'pycom')
h.update(b'pycom')
print(h.digest())

# test other functions
print(hashlib.md5(b'pycom').digest())
print(hashlib.sha1(b'pycom').digest())
print(hashlib.sha224(b'pycom').digest())
print(hashlib.sha384(b'pycom').digest())
print(hashlib.sha512(b'pycom').digest())

# test buffer operation
buf = b''
for i in range(127):
    buf += bytes(str(i % 10), "UTF8")

h = hashlib.sha512(b'pycom')
h.update(buf)
h.update(buf)
h.update(buf)
print(h.digest())

# test string bigger than buffer
buf = b''
for i in range(255):
    buf += bytes(str(i % 10), "UTF8")

h = hashlib.sha512(b'pycom')
h.update(buf)
h.update(buf)
print(h.digest())


text:
/*
 * exports.h
 */

#ifndef FRAMEWORK_EXPORTS_H_
#define FRAMEWORK_EXPORTS_H_

/* Cmake will define celix_framework_EXPORTS on Windows when it
configures to build a shared library. If you are going to use
another build system on windows or create the visual studio
projects by hand you need to define celix_framework_EXPORTS when
building a DLL on windows.
*/
// We are using the Visual Studio Compiler and building Shared libraries

#if defined _WIN32 || defined __CYGWIN__
  #ifdef celix_framework_EXPORTS
    #ifdef __GNUC__
      #define FRAMEWORK_EXPORT __attribute__ ((dllexport))
      #define ACTIVATOR_EXPORT __attribute__ ((dllexport))
    #else
      #define ACTIVATOR_EXPORT __declspec(dllexport)
      #define FRAMEWORK_EXPORT __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
    #endif
  #else
    #ifdef __GNUC__
      #define ACTIVATOR_EXPORT __attribute__ ((dllexport))
      #define FRAMEWORK_EXPORT __attribute__ ((dllimport))
    #else
      #define ACTIVATOR_EXPORT __declspec(dllexport)
      #define FRAMEWORK_EXPORT __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
    #endif
  #endif
  #define DLL_LOCAL
#else
  #if __GNUC__ >= 4
    #define ACTIVATOR_EXPORT __attribute__ ((visibility ("default")))
    #define FRAMEWORK_EXPORT __attribute__ ((visibility ("default")))
    #define FRAMEWORK_LOCAL  __attribute__ ((visibility ("hidden")))
  #else
    #define ACTIVATOR_EXPORT
    #define FRAMEWORK_EXPORT
    #define FRAMEWORK_LOCAL
  #endif
#endif

#endif /* FRAMEWORK_EXPORTS_H_ */


text:
package io.airlift.command;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import io.airlift.command.model.CommandGroupMetadata;
import io.airlift.command.model.CommandMetadata;
import io.airlift.command.model.OptionMetadata;

import java.util.List;

public class ParseState
{
    private final List<Context> locationStack;
    private final CommandGroupMetadata group;
    private final CommandMetadata command;
    private final ListMultimap<OptionMetadata, Object> parsedOptions;
    private final List<Object> parsedArguments;
    private final OptionMetadata currentOption;
    private final List<String> unparsedInput;

    ParseState(CommandGroupMetadata group,
            CommandMetadata command,
            ListMultimap<OptionMetadata, Object> parsedOptions,
            List<Context> locationStack,
            List<Object> parsedArguments,
            OptionMetadata currentOption,
            List<String> unparsedInput)
    {
        this.group = group;
        this.command = command;
        this.parsedOptions = parsedOptions;
        this.locationStack = locationStack;
        this.parsedArguments = parsedArguments;
        this.currentOption = currentOption;
        this.unparsedInput = unparsedInput;
    }

    public static ParseState newInstance()
    {
        return new ParseState(null, null, ArrayListMultimap.<OptionMetadata, Object>create(), ImmutableList.<Context>of(), ImmutableList.of(), null, ImmutableList.<String>of());
    }

    public ParseState pushContext(Context location)
    {
        ImmutableList<Context> locationStack = ImmutableList.<Context>builder()
                .addAll(this.locationStack)
                .add(location)
                .build();

        return new ParseState(group, command, parsedOptions, locationStack, parsedArguments, currentOption, unparsedInput);
    }

    public ParseState popContext()
    {
        ImmutableList<Context> locationStack = ImmutableList.copyOf(this.locationStack.subList(0, this.locationStack.size() - 1));
        return new ParseState(group, command, parsedOptions, locationStack, parsedArguments, currentOption, unparsedInput);
    }

    public ParseState withOptionValue(OptionMetadata option, Object value)
    {
        ImmutableListMultimap<OptionMetadata, Object> newOptions = ImmutableListMultimap.<OptionMetadata, Object>builder()
                .putAll(parsedOptions)
                .put(option, value)
                .build();

        return new ParseState(group, command, newOptions, locationStack, parsedArguments, currentOption, unparsedInput);
    }

    public ParseState withGroup(CommandGroupMetadata group)
    {
        return new ParseState(group, command, parsedOptions, locationStack, parsedArguments, currentOption, unparsedInput);
    }

    public ParseState withCommand(CommandMetadata command)
    {
        return new ParseState(group, command, parsedOptions, locationStack, parsedArguments, currentOption, unparsedInput);
    }

    public ParseState withOption(OptionMetadata option)
    {
        return new ParseState(group, command, parsedOptions, locationStack, parsedArguments, option, unparsedInput);
    }

    public ParseState withArgument(Object argument)
    {
        ImmutableList<Object> newArguments = ImmutableList.<Object>builder()
                .addAll(parsedArguments)
                .add(argument)
                .build();

        return new ParseState(group, command, parsedOptions, locationStack, newArguments, currentOption, unparsedInput);
    }

    public ParseState withUnparsedInput(String input)
    {
        ImmutableList<String> newUnparsedInput = ImmutableList.<String>builder()
                .addAll(unparsedInput)
                .add(input)
                .build();

        return new ParseState(group, command, parsedOptions, locationStack, parsedArguments, currentOption, newUnparsedInput);
    }

    @Override
    public String toString()
    {
        return "ParseState{" +
                "locationStack=" + locationStack +
                ", group=" + group +
                ", command=" + command +
                ", parsedOptions=" + parsedOptions +
                ", parsedArguments=" + parsedArguments +
                ", currentOption=" + currentOption +
                ", unparsedInput=" + unparsedInput +
                '}';
    }

    public Context getLocation()
    {
        return locationStack.get(locationStack.size() - 1);
    }

    public CommandGroupMetadata getGroup()
    {
        return group;
    }

    public CommandMetadata getCommand()
    {
        return command;
    }

    public OptionMetadata getCurrentOption()
    {
        return currentOption;
    }

    public ListMultimap<OptionMetadata, Object> getParsedOptions()
    {
        return parsedOptions;
    }

    public List<Object> getParsedArguments()
    {
        return parsedArguments;
    }

    public List<String> getUnparsedInput()
    {
        return unparsedInput;
    }
}


text:
namespace mojo {

// static
device::UsbDeviceFilter
TypeConverter<device::UsbDeviceFilter, device::usb::DeviceFilterPtr>::Convert(
    const device::usb::DeviceFilterPtr& mojo_filter) {
  device::UsbDeviceFilter filter;
  if (mojo_filter->has_vendor_id)
    filter.SetVendorId(mojo_filter->vendor_id);
  if (mojo_filter->has_product_id)
    filter.SetProductId(mojo_filter->product_id);
  if (mojo_filter->has_class_code)
    filter.SetInterfaceClass(mojo_filter->class_code);
  if (mojo_filter->has_subclass_code)
    filter.SetInterfaceSubclass(mojo_filter->subclass_code);
  if (mojo_filter->has_protocol_code)
    filter.SetInterfaceProtocol(mojo_filter->protocol_code);
  return filter;
}

// static
device::usb::TransferDirection
TypeConverter<device::usb::TransferDirection, device::UsbEndpointDirection>::
    Convert(const device::UsbEndpointDirection& direction) {
  if (direction == device::USB_DIRECTION_INBOUND)
    return device::usb::TransferDirection::INBOUND;
  DCHECK(direction == device::USB_DIRECTION_OUTBOUND);
  return device::usb::TransferDirection::OUTBOUND;
}

// static
device::usb::TransferStatus
TypeConverter<device::usb::TransferStatus, device::UsbTransferStatus>::Convert(
    const device::UsbTransferStatus& status) {
  switch (status) {
    case device::USB_TRANSFER_COMPLETED:
      return device::usb::TransferStatus::COMPLETED;
    case device::USB_TRANSFER_ERROR:
      return device::usb::TransferStatus::TRANSFER_ERROR;
    case device::USB_TRANSFER_TIMEOUT:
      return device::usb::TransferStatus::TIMEOUT;
    case device::USB_TRANSFER_CANCELLED:
      return device::usb::TransferStatus::CANCELLED;
    case device::USB_TRANSFER_STALLED:
      return device::usb::TransferStatus::STALLED;
    case device::USB_TRANSFER_DISCONNECT:
      return device::usb::TransferStatus::DISCONNECT;
    case device::USB_TRANSFER_OVERFLOW:
      return device::usb::TransferStatus::BABBLE;
    case device::USB_TRANSFER_LENGTH_SHORT:
      return device::usb::TransferStatus::SHORT_PACKET;
    default:
      NOTREACHED();
      return device::usb::TransferStatus::TRANSFER_ERROR;
  }
}

// static
device::UsbDeviceHandle::TransferRequestType
TypeConverter<device::UsbDeviceHandle::TransferRequestType,
              device::usb::ControlTransferType>::
    Convert(const device::usb::ControlTransferType& type) {
  switch (type) {
    case device::usb::ControlTransferType::STANDARD:
      return device::UsbDeviceHandle::STANDARD;
    case device::usb::ControlTransferType::CLASS:
      return device::UsbDeviceHandle::CLASS;
    case device::usb::ControlTransferType::VENDOR:
      return device::UsbDeviceHandle::VENDOR;
    case device::usb::ControlTransferType::RESERVED:
      return device::UsbDeviceHandle::RESERVED;
    default:
      NOTREACHED();
      return device::UsbDeviceHandle::RESERVED;
  }
}

// static
device::UsbDeviceHandle::TransferRecipient
TypeConverter<device::UsbDeviceHandle::TransferRecipient,
              device::usb::ControlTransferRecipient>::
    Convert(const device::usb::ControlTransferRecipient& recipient) {
  switch (recipient) {
    case device::usb::ControlTransferRecipient::DEVICE:
      return device::UsbDeviceHandle::DEVICE;
    case device::usb::ControlTransferRecipient::INTERFACE:
      return device::UsbDeviceHandle::INTERFACE;
    case device::usb::ControlTransferRecipient::ENDPOINT:
      return device::UsbDeviceHandle::ENDPOINT;
    case device::usb::ControlTransferRecipient::OTHER:
      return device::UsbDeviceHandle::OTHER;
    default:
      NOTREACHED();
      return device::UsbDeviceHandle::OTHER;
  }
}

// static
device::usb::EndpointType
TypeConverter<device::usb::EndpointType, device::UsbTransferType>::Convert(
    const device::UsbTransferType& type) {
  switch (type) {
    case device::USB_TRANSFER_ISOCHRONOUS:
      return device::usb::EndpointType::ISOCHRONOUS;
    case device::USB_TRANSFER_BULK:
      return device::usb::EndpointType::BULK;
    case device::USB_TRANSFER_INTERRUPT:
      return device::usb::EndpointType::INTERRUPT;
    // Note that we do not expose control transfer in the public interface
    // because control endpoints are implied rather than explicitly enumerated
    // there.
    default:
      NOTREACHED();
      return device::usb::EndpointType::BULK;
  }
}

// static
device::usb::EndpointInfoPtr
TypeConverter<device::usb::EndpointInfoPtr, device::UsbEndpointDescriptor>::
    Convert(const device::UsbEndpointDescriptor& endpoint) {
  device::usb::EndpointInfoPtr info = device::usb::EndpointInfo::New();
  info->endpoint_number = endpoint.address & 0xf;
  info->direction =
      ConvertTo<device::usb::TransferDirection>(endpoint.direction);
  info->type = ConvertTo<device::usb::EndpointType>(endpoint.transfer_type);
  info->packet_size = static_cast<uint32_t>(endpoint.maximum_packet_size);
  return info;
}

// static
device::usb::AlternateInterfaceInfoPtr
TypeConverter<device::usb::AlternateInterfaceInfoPtr,
              device::UsbInterfaceDescriptor>::
    Convert(const device::UsbInterfaceDescriptor& interface) {
  device::usb::AlternateInterfaceInfoPtr info =
      device::usb::AlternateInterfaceInfo::New();
  info->alternate_setting = interface.alternate_setting;
  info->class_code = interface.interface_class;
  info->subclass_code = interface.interface_subclass;
  info->protocol_code = interface.interface_protocol;

  // Filter out control endpoints for the public interface.
  info->endpoints = mojo::Array<device::usb::EndpointInfoPtr>::New(0);
  for (const auto& endpoint : interface.endpoints) {
    if (endpoint.transfer_type != device::USB_TRANSFER_CONTROL)
      info->endpoints.push_back(device::usb::EndpointInfo::From(endpoint));
  }

  return info;
}

// static
mojo::Array<device::usb::InterfaceInfoPtr>
TypeConverter<mojo::Array<device::usb::InterfaceInfoPtr>,
              std::vector<device::UsbInterfaceDescriptor>>::
    Convert(const std::vector<device::UsbInterfaceDescriptor>& interfaces) {
  auto infos = mojo::Array<device::usb::InterfaceInfoPtr>::New(0);

  // Aggregate each alternate setting into an InterfaceInfo corresponding to its
  // interface number.
  std::map<uint8_t, device::usb::InterfaceInfo*> interface_map;
  for (size_t i = 0; i < interfaces.size(); ++i) {
    auto alternate = device::usb::AlternateInterfaceInfo::From(interfaces[i]);
    auto iter = interface_map.find(interfaces[i].interface_number);
    if (iter == interface_map.end()) {
      // This is the first time we're seeing an alternate with this interface
      // number, so add a new InterfaceInfo to the array and map the number.
      auto info = device::usb::InterfaceInfo::New();
      info->interface_number = interfaces[i].interface_number;
      iter = interface_map
                 .insert(
                     std::make_pair(interfaces[i].interface_number, info.get()))
                 .first;
      infos.push_back(std::move(info));
    }
    iter->second->alternates.push_back(std::move(alternate));
  }

  return infos;
}

// static
device::usb::ConfigurationInfoPtr
TypeConverter<device::usb::ConfigurationInfoPtr, device::UsbConfigDescriptor>::
    Convert(const device::UsbConfigDescriptor& config) {
  device::usb::ConfigurationInfoPtr info =
      device::usb::ConfigurationInfo::New();
  info->configuration_value = config.configuration_value;
  info->interfaces =
      mojo::Array<device::usb::InterfaceInfoPtr>::From(config.interfaces);
  return info;
}

// static
device::usb::DeviceInfoPtr
TypeConverter<device::usb::DeviceInfoPtr, device::UsbDevice>::Convert(
    const device::UsbDevice& device) {
  device::usb::DeviceInfoPtr info = device::usb::DeviceInfo::New();
  info->guid = device.guid();
  info->usb_version_major = device.usb_version() >> 8;
  info->usb_version_minor = device.usb_version() >> 4 & 0xf;
  info->usb_version_subminor = device.usb_version() & 0xf;
  info->class_code = device.device_class();
  info->subclass_code = device.device_subclass();
  info->protocol_code = device.device_protocol();
  info->vendor_id = device.vendor_id();
  info->product_id = device.product_id();
  info->device_version_major = device.device_version() >> 8;
  info->device_version_minor = device.device_version() >> 4 & 0xf;
  info->device_version_subminor = device.device_version() & 0xf;
  info->manufacturer_name = base::UTF16ToUTF8(device.manufacturer_string());
  info->product_name = base::UTF16ToUTF8(device.product_string());
  info->serial_number = base::UTF16ToUTF8(device.serial_number());
  const device::UsbConfigDescriptor* config = device.active_configuration();
  info->active_configuration = config ? config->configuration_value : 0;
  info->configurations = mojo::Array<device::usb::ConfigurationInfoPtr>::From(
      device.configurations());
  return info;
}

// static
device::usb::IsochronousPacketPtr
TypeConverter<device::usb::IsochronousPacketPtr,
              device::UsbDeviceHandle::IsochronousPacket>::
    Convert(const device::UsbDeviceHandle::IsochronousPacket& packet) {
  device::usb::IsochronousPacketPtr info =
      device::usb::IsochronousPacket::New();
  info->length = packet.length;
  info->transferred_length = packet.transferred_length;
  info->status = mojo::ConvertTo<device::usb::TransferStatus>(packet.status);
  return info;
}

}  // namespace mojo


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Contains a registry key string and some version information associated with it</summary>
//-----------------------------------------------------------------------

using System;
using Microsoft.Build.Shared;
using Microsoft.Win32;

namespace Microsoft.Build.Shared
{
    /// <summary>
    /// Contains information about entries in the AssemblyFoldersEx registry keys.
    /// </summary>
    internal class ExtensionFoldersRegistryKey
    {
        /// <summary>
        /// Constructor
        /// </summary>
        internal ExtensionFoldersRegistryKey(string registryKey, Version targetFrameworkVersion)
        {
            ErrorUtilities.VerifyThrowArgumentNull(registryKey, "registryKey");
            ErrorUtilities.VerifyThrowArgumentNull(targetFrameworkVersion, "targetFrameworkVersion");

            RegistryKey = registryKey;
            ComponentVersion = null;
            TargetFrameworkVersion = targetFrameworkVersion;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        internal ExtensionFoldersRegistryKey(string registryKey, Version componentVersion, Version targetFrameworkVersion)
        {
            ErrorUtilities.VerifyThrowArgumentNull(registryKey, "registryKey");
            ErrorUtilities.VerifyThrowArgumentNull(targetFrameworkVersion, "targetFrameworkVersion");

            RegistryKey = registryKey;
            ComponentVersion = componentVersion;
            TargetFrameworkVersion = targetFrameworkVersion;
        }

        /// <summary>
        /// The registry key to the component
        /// </summary>
        internal string RegistryKey
        {
            get;
            private set;
        }

        /// <summary>
        /// Target framework version for the registry key
        /// </summary>
        internal Version ComponentVersion
        {
            get;
            private set;
        }

        /// <summary>
        /// Target framework version for the registry key
        /// </summary>
        internal Version TargetFrameworkVersion
        {
            get;
            private set;
        }
    }
}


text:
<?php
return array (
  'There is a new HumHub Version (%version%) available.' => 'Er is een nieuwe versie van HumHub beschikbaar (versie %version%).',
);


text:
@interface UIView (Hierarchy)

////////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark - Instance Methods

- (UIView *)firstResponderView;
- (void)logHierarchy;

@end


text:
import validAttributes from './rules/validAttributes'
import validChildren from './rules/validChildren'
import validTag from './rules/validTag'
import validTypes from './rules/validTypes'
import errorAttr from './rules/errorAttr'

const MJMLRulesCollection = {
  validAttributes,
  validChildren,
  validTag,
  validTypes,
  errorAttr,
}

export function registerRule(rule, name) {
  if (typeof rule !== 'function') {
    return console.error('Your rule must be a function')
  }

  if (name) {
    MJMLRulesCollection[name] = rule
  } else {
    MJMLRulesCollection[rule.name] = rule
  }

  return true
}

export default MJMLRulesCollection


text:
class DropTheAdminsTable < ActiveRecord::Migration
  def up
    drop_table :admins
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end


text:
sap.ui.define([
	"sap/ui/core/UIComponent"
], function (UIComponent) {
	"use strict";

	return UIComponent.extend("sap.m.sample.TableSelectDialogGrowing.Component", {

		metadata: {
			manifest: "json"
		}

	});
});


text:
from NodeDefender.manage.setup import (manager, print_message, print_topic,
                                       print_info)
from flask_script import prompt
import NodeDefender

@manager.command
def general():
    port = None
    while port is None:
        port = prompt("Which port should the server be running on")

    print_info("Security Key is used to Encrypt Password etc.")
    key = None
    while key is None:
        key = prompt("Enter Secret Key")

    print_info("Salt is used to genereate URLS and more.")
    salt = None
    while salt is None:
        salt = prompt("Please enter Salt")

    print_info("You can either have users register by themselfs on the\
               authentication- page or via invite mail. Invite mail requires\
               that you also enable mail- support so that NodeDefender can send\
               invitation- mail and such. Superuser can still administrate\
               users in the same way.")
    self_registration = None
    while self_registration is None:
        self_registration = prompt("Enable self-registration(Y/N)").upper()
        if 'Y' in self_registration:
            self_registration = True
        elif 'N' in self_registration:
            self_registration = False
        else:
            self_registration = None

    NodeDefender.config.general.set(port=port,
                                    key=key,
                                    salt=salt,
                                    self_registration=self_registration)
    if NodeDefender.config.general.write():
        print_info("General- config successfully written")
    return True