/*
(non-Javadoc)
@see org.fcrepo.server.security.xacml.pep.ContextHandler#buildRequest(java.util.List,
java.util.Map, java.util.Map, java.util.Map)
979818
@Override
    public RequestCtx buildRequest(List<Map<URI, List<AttributeValue>>> subjects,
                                   Map<URI, AttributeValue> actions,
                                   Map<URI, AttributeValue> resources,
                                   Map<URI, AttributeValue> environment)
            throws PEPException {
        try {
            return m_contextUtil.buildRequest(subjects,
                                            actions,
                                            resources,
                                            environment,
                                            m_relationshipResolver);
        } catch (MelcoeXacmlException e) {
            throw new PEPException(e);
        }
    }
345578
public RequestBuilder<T,ID> addParameter(String name,String value)
    {
        parameters.add(name, value);
        return this;
    }
482877
@SuppressWarnings("unchecked")
  protected AppendRequest buildAppendEntriesRequest(RaftMemberContext member, long lastIndex) {
    final RaftLogReader reader = member.getLogReader();

    final Indexed<RaftLogEntry> prevEntry = reader.getCurrentEntry();

    final DefaultRaftMember leader = raft.getLeader();
    AppendRequest.Builder builder = AppendRequest.builder()
        .withTerm(raft.getTerm())
        .withLeader(leader != null ? leader.memberId() : null)
        .withPrevLogIndex(prevEntry != null ? prevEntry.index() : reader.getFirstIndex() - 1)
        .withPrevLogTerm(prevEntry != null ? prevEntry.entry().term() : 0)
        .withCommitIndex(raft.getCommitIndex());

    // Build a list of entries to send to the member.
    final List<RaftLogEntry> entries = new ArrayList<>();

    // Build a list of entries up to the MAX_BATCH_SIZE. Note that entries in the log may
    // be null if they've been compacted and the member to which we're sending entries is just
    // joining the cluster or is otherwise far behind. Null entries are simply skipped and not
    // counted towards the size of the batch.
    // If there exists an entry in the log with size >= MAX_BATCH_SIZE the logic ensures that
    // entry will be sent in a batch of size one
    int size = 0;

    // Iterate through the log until the last index or the end of the log is reached.
    while (reader.hasNext()) {
      // Otherwise, read the next entry and add it to the batch.
      Indexed<RaftLogEntry> entry = reader.next();
      entries.add(entry.entry());
      size += entry.size();
      if (entry.index() == lastIndex || size >= MAX_BATCH_SIZE) {
        break;
      }
    }

    // Add the entries to the request builder and build the request.
    return builder.withEntries(entries).build();
  }
653215
@Override
	public Future<?> buildAsync(final Callable<?> builder, final HttpServletRequest req) {
		return getExecutors().getBuildExecutor().submit(new Callable<Object>() {
			public Object call() throws Exception {
				AbstractAggregatorImpl.this.currentRequest.set(req);
				Object result;
				try {
					result = builder.call();
				} finally {
					AbstractAggregatorImpl.this.currentRequest.set(null);
				}
				return result;
			}
		});
	}
156452
protected RequestContext createRequestContext(HttpServletRequest request, HttpServletResponse response) {
        return new RequestContext(request, response, getServletContext());
    }
510052
protected com.squareup.okhttp.Request buildHttpRequest(Request request)
    {
        RequestBody requestBody = null;
        if(request.getRequestMethod().isBodyRequest())
            requestBody = RequestBody.create(JSON, serializeBody(request));

        return new com.squareup.okhttp.Request.Builder()
                .url(buildUrl(request))
                .headers(getHeaders(request))
                .method(request.getRequestMethod().name(),requestBody)
                .build();
    }
384540
@Override
    public ModelNode buildRequestWithoutHeaders(CommandContext ctx) throws CommandFormatException {

        final ParsedCommandLine parsedCmd = ctx.getParsedCommandLine();
        final String name = this.name.getValue(parsedCmd);
        if(name == null || name.isEmpty()) {
            throw new CommandFormatException("Required argument " + this.name.getFullName() + " is not specified.");
        }

        final OperationRequestAddress address = getAddress(ctx, false);
        ModelNode req = Util.buildRequest(ctx, address, Util.READ_ATTRIBUTE);
        req.get(Util.NAME).set(name);
        if( resolve.isPresent(parsedCmd)){
            req.get(Util.RESOLVE_EXPRESSIONS).set(true);
        }

        final String includeDefaults = this.includeDefaults.getValue(parsedCmd);
        if(includeDefaults != null && !includeDefaults.isEmpty()) {
            req.get(Util.INCLUDE_DEFAULTS).set(includeDefaults);
        }

        if(verbose.isPresent(parsedCmd)) {
            final ModelNode composite = new ModelNode();
            composite.get(Util.OPERATION).set(Util.COMPOSITE);
            composite.get(Util.ADDRESS).setEmptyList();
            final ModelNode steps = composite.get(Util.STEPS);
            steps.add(req);
            steps.add(Util.buildRequest(ctx, address, Util.READ_RESOURCE_DESCRIPTION));
            req = composite;
        }

        return req;
    }
1372553
function buildRequest(ts, doc, query, pos) {
    var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
    if (!allowFragments) delete query.fullDocs;
    if (typeof query == "string") query = {type: query};
    query.lineCharPositions = true;
    if (query.end == null) {
      query.end = pos || doc.doc.getCursor("end");
      if (doc.doc.somethingSelected())
        query.start = doc.doc.getCursor("start");
    }
    var startPos = query.start || query.end;

    if (doc.changed) {
      if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
          doc.changed.to - doc.changed.from < 100 &&
          doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
        files.push(getFragmentAround(doc, startPos, query.end));
        query.file = "#0";
        var offsetLines = files[0].offsetLines;
        if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
        query.end = Pos(query.end.line - offsetLines, query.end.ch);
      } else {
        files.push({type: "full",
                    name: doc.name,
                    text: docValue(ts, doc)});
        query.file = doc.name;
        doc.changed = null;
      }
    } else {
      query.file = doc.name;
    }
    for (var name in ts.docs) {
      var cur = ts.docs[name];
      if (cur.changed && cur != doc) {
        files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
        cur.changed = null;
      }
    }

    return {query: query, files: files};
  }
134858
@SuppressWarnings("unchecked")
    public List<RpcResponse> request(List<RpcRequest> reqList) {
        List<RpcResponse> respList = new ArrayList<RpcResponse>();

        List<Map> marshaledReqs = new ArrayList<Map>();
        Map<String,RpcRequest> byReqId = new HashMap<String,RpcRequest>();
        for (RpcRequest req : reqList) {
            try {
                marshaledReqs.add(req.marshal(contract));
                byReqId.put(req.getId(), req);
            }
            catch (RpcException e) {
                respList.add(new RpcResponse(req, e));
            }
        }

        InputStream is = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            serializer.write(marshaledReqs, bos);
            bos.close();
            byte[] data = bos.toByteArray();
            
            is = requestRaw(data);
            List<Map> responses = serializer.readList(is);
            for (Map map : responses) {
                String id = (String)map.get("id");
                if (id != null) {
                    RpcRequest req = byReqId.get(id);
                    if (req == null) {
                        // TODO: ?? log error?
                    }
                    else {
                        byReqId.remove(id);
                        respList.add(unmarshal(req, map));
                    }
                }
                else {
                    // TODO: ?? log error?
                }
            }

            if (byReqId.size() > 0) {
                for (RpcRequest req : byReqId.values()) {
                    String msg = "No response in batch for request " + req.getId();
                    RpcException exc = RpcException.Error.INVALID_RESP.exc(msg);
                    RpcResponse resp = new RpcResponse(req, exc);
                    respList.add(resp);
                }
            }
        }
        catch (IOException e) {
            String msg = "IOException requesting batch " +
                " from: " + endpoint + " - " + e.getMessage();
            RpcException exc = RpcException.Error.INTERNAL.exc(msg);
            respList.add(new RpcResponse(null, exc));
        }
        finally {
            closeQuietly(is);
        }
        
        return respList;
    }
448694
@SafeVarargs
    public final RequestBuilder params(Map.Entry<String, ?>... params) {
        this.params = Lists.of(params);
        return this;
    }
825040
public static String buildRequestDescriptor(String...requestInfo) {
        return Stream.of(requestInfo).collect(Collectors.joining(INTER_FIELD_DELIMITER));
    }
295948
private static String buildCacheID(ApiRequest request) {
        StringBuilder req = new StringBuilder();
        if (request.getContract() != null) {
            req.append(request.getApiKey());
        } else {
            req.append(request.getApiOrgId()).append(KEY_SEPARATOR).append(request.getApiId())
                    .append(KEY_SEPARATOR).append(request.getApiVersion());
        }
        req.append(KEY_SEPARATOR).append(request.getType()).append(KEY_SEPARATOR)
                .append(request.getDestination());
        return req.toString();
    }
866489
@SuppressWarnings("unchecked")
	private Map<String, Object> buildParameters(Object parameters) {
		Map<String, Object> parameterMap = new HashMap<String, Object>();

		if (parameters != null) {
			if (parameters.getClass().isArray()) {
				Object[] paramValues = (Object[]) parameters;
				for (int i = 0; i < paramValues.length; i++) {
					if (paramValues[i] == null) {
						paramValues[i] = "";
					}
					parameterMap.put(Integer.toString(i), paramValues[i]);
				}
			} else if (parameters instanceof Map) {
				parameterMap = (Map<String, Object>) parameters;
			} else {
				Class<? extends Object> paramClass = parameters.getClass();
				Field[] fields = paramClass.getDeclaredFields();
				for (Field field : fields) {
					field.setAccessible(true);

					String fieldName = field.getName();
					Object fieldValue = null;
					try {
						fieldValue = field.get(parameters);
					} catch (Exception e) {
						fieldValue = null;
					}
					if (fieldName != null && fieldValue != null) {
						parameterMap.put(fieldName, fieldValue);
					}
				}
			}
		}

		return parameterMap;
	}
745682
protected Map<String,String> buildRoot(HttpServletRequest request,
      XMLOutputter doc) {
    final String path = request.getPathInfo() != null
      ? request.getPathInfo() : "/";
    final String exclude = request.getParameter("exclude") != null
      ? request.getParameter("exclude") : "\\..*\\.crc";
    final String filter = request.getParameter("filter") != null
      ? request.getParameter("filter") : ".*";
    final boolean recur = request.getParameter("recursive") != null
      && "yes".equals(request.getParameter("recursive"));

    Map<String, String> root = new HashMap<String, String>();
    root.put("path", path);
    root.put("recursive", recur ? "yes" : "no");
    root.put("filter", filter);
    root.put("exclude", exclude);
    root.put("time", df.get().format(new Date()));
    root.put("version", VersionInfo.getVersion());
    return root;
  }
570809
public HttpRequest buildPostRequest(GenericUrl url, HttpContent content) throws IOException {
    return buildRequest(HttpMethods.POST, url, content);
  }
404633
@Override
    Map<String, Object> constructRequestArgs() {
        Map<String, Object> args = new HashMap<String, Object>();

        args.put(KeenQueryConstants.STEPS, this.steps.constructParameterRequestArgs());

        if (null != this.timeframe) {
            args.putAll(timeframe.constructTimeframeArgs());
        }

        return args;
    }
905790
public ServiceRequestContext build() {
        // Determine the client address; use remote address unless overridden.
        final InetAddress clientAddress;
        if (this.clientAddress != null) {
            clientAddress = this.clientAddress;
        } else {
            clientAddress = remoteAddress().getAddress();
        }

        // Build a fake server which never starts up.
        final ServerBuilder serverBuilder = new ServerBuilder().meterRegistry(meterRegistry())
                                                               .workerGroup(eventLoop(), false)
                                                               .service(path(), service);
        serverConfigurators.forEach(configurator -> configurator.accept(serverBuilder));

        final Server server = serverBuilder.build();
        server.addListener(rejectingListener);

        // Retrieve the ServiceConfig of the fake service.
        final ServiceConfig serviceCfg = findServiceConfig(server, path(), service);

        // Build a fake object related with path mapping.
        final PathMappingContext pathMappingCtx = DefaultPathMappingContext.of(
                server.config().defaultVirtualHost(),
                localAddress().getHostString(),
                path(),
                query(),
                ((HttpRequest) request()).headers(),
                null);

        final PathMappingResult pathMappingResult =
                this.pathMappingResult != null ? this.pathMappingResult
                                               : PathMappingResult.of(path(), query());

        // Build the context with the properties set by a user and the fake objects.
        if (isRequestStartTimeSet()) {
            return new DefaultServiceRequestContext(
                    serviceCfg, fakeChannel(), meterRegistry(), sessionProtocol(), pathMappingCtx,
                    pathMappingResult, request(), sslSession(), proxiedAddresses, clientAddress,
                    requestStartTimeNanos(), requestStartTimeMicros());
        } else {
            return new DefaultServiceRequestContext(
                    serviceCfg, fakeChannel(), meterRegistry(), sessionProtocol(), pathMappingCtx,
                    pathMappingResult, request(), sslSession(), proxiedAddresses, clientAddress);
        }
    }