Parses a {@link RestRequest} body and returns a {@link MultiSearchScriptTemplateRequest}
494588
public static MultiSearchScriptTemplateRequest parseRequest(final RestRequest restRequest, final boolean allowExplicitIndex)
            throws IOException {
        final MultiSearchScriptTemplateRequest multiRequest = new MultiSearchScriptTemplateRequest();
        if (restRequest.hasParam("max_concurrent_searches")) {
            multiRequest.maxConcurrentSearchRequests(restRequest.paramAsInt("max_concurrent_searches", 0));
        }

        RestMultiSearchAction.parseMultiLineRequest(restRequest, multiRequest.indicesOptions(), allowExplicitIndex,
                (searchRequest, bytes) -> {
                    try {
                        final SearchScriptTemplateRequest searchTemplateRequest = RestSearchScriptTemplateAction.parse(bytes);
                        if (searchTemplateRequest.getScript() != null) {
                            searchTemplateRequest.setRequest(searchRequest);
                            multiRequest.add(searchTemplateRequest);
                        } else {
                            throw new IllegalArgumentException("Malformed search template");
                        }
                    } catch (final IOException e) {
                        throw new ElasticsearchParseException("Exception when parsing search template request", e);
                    }
                });
        return multiRequest;
    }
972280
private Map<String, Object> getMultipartBodyAsDictionary() throws CouchbaseLiteException {
        MultipartDocumentReader reader = new MultipartDocumentReader(db);
        reader.setHeaders(Utils.headersToMap(connection.getRequestProperties()));
        byte[] buffer = new byte[BUF_LEN];
        int numBytesRead;
        InputStream contentStream = connection.getRequestInputStream();
        try {
            while ((numBytesRead = contentStream.read(buffer)) != -1)
                reader.appendData(buffer, 0, numBytesRead);
        } catch (IOException ioe) {
            Log.e(Log.TAG_ROUTER, "Error in load data from stream.");
            throw new CouchbaseLiteException(Status.BAD_REQUEST);
        } finally {
            if (contentStream != null) {
                try {
                    contentStream.close();
                } catch (IOException ioe) {
                }
            }
        }
        reader.finish();
        return reader.getDocumentProperties();
    }
595729
public static Map<String,String> processResults(String responseBody) {
        JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627);

        try {
            JSONObject object = (JSONObject)parser.parse(responseBody);
            Object results = object.get("docs");
            if(results!=null && results instanceof JSONArray) {
                return parseDocs((JSONArray)results);
            }else {
                return Collections.EMPTY_MAP;
            }
        } catch (Exception e){
            return Collections.EMPTY_MAP;
        }
    }
365729
private void parseBodyAttributes() {
        if (!undecodedChunk.hasArray()) {
            parseBodyAttributesStandard();
            return;
        }
        SeekAheadOptimize sao = new SeekAheadOptimize(undecodedChunk);
        int firstpos = undecodedChunk.readerIndex();
        int currentpos = firstpos;
        int equalpos;
        int ampersandpos;
        if (currentStatus == MultiPartStatus.NOTSTARTED) {
            currentStatus = MultiPartStatus.DISPOSITION;
        }
        boolean contRead = true;
        try {
            loop: while (sao.pos < sao.limit) {
                char read = (char) (sao.bytes[sao.pos++] & 0xFF);
                currentpos++;
                switch (currentStatus) {
                case DISPOSITION:// search '='
                    if (read == '=') {
                        currentStatus = MultiPartStatus.FIELD;
                        equalpos = currentpos - 1;
                        String key = decodeAttribute(undecodedChunk.toString(firstpos, equalpos - firstpos, charset),
                                charset);
                        currentAttribute = factory.createAttribute(request, key);
                        firstpos = currentpos;
                    } else if (read == '&') { // special empty FIELD
                        currentStatus = MultiPartStatus.DISPOSITION;
                        ampersandpos = currentpos - 1;
                        String key = decodeAttribute(
                                undecodedChunk.toString(firstpos, ampersandpos - firstpos, charset), charset);
                        currentAttribute = factory.createAttribute(request, key);
                        currentAttribute.setValue(""); // empty
                        addHttpData(currentAttribute);
                        currentAttribute = null;
                        firstpos = currentpos;
                        contRead = true;
                    }
                    break;
                case FIELD:// search '&' or end of line
                    if (read == '&') {
                        currentStatus = MultiPartStatus.DISPOSITION;
                        ampersandpos = currentpos - 1;
                        setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos));
                        firstpos = currentpos;
                        contRead = true;
                    } else if (read == HttpConstants.CR) {
                        if (sao.pos < sao.limit) {
                            read = (char) (sao.bytes[sao.pos++] & 0xFF);
                            currentpos++;
                            if (read == HttpConstants.LF) {
                                currentStatus = MultiPartStatus.PREEPILOGUE;
                                ampersandpos = currentpos - 2;
                                sao.setReadPosition(0);
                                setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos));
                                firstpos = currentpos;
                                contRead = false;
                                break loop;
                            } else {
                                // Error
                                sao.setReadPosition(0);
                                throw new ErrorDataDecoderException("Bad end of line");
                            }
                        } else {
                            if (sao.limit > 0) {
                                currentpos--;
                            }
                        }
                    } else if (read == HttpConstants.LF) {
                        currentStatus = MultiPartStatus.PREEPILOGUE;
                        ampersandpos = currentpos - 1;
                        sao.setReadPosition(0);
                        setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos));
                        firstpos = currentpos;
                        contRead = false;
                        break loop;
                    }
                    break;
                default:
                    // just stop
                    sao.setReadPosition(0);
                    contRead = false;
                    break loop;
                }
            }
            if (isLastChunk && currentAttribute != null) {
                // special case
                ampersandpos = currentpos;
                if (ampersandpos > firstpos) {
                    setFinalBuffer(undecodedChunk.copy(firstpos, ampersandpos - firstpos));
                } else if (!currentAttribute.isCompleted()) {
                    setFinalBuffer(EMPTY_BUFFER);
                }
                firstpos = currentpos;
                currentStatus = MultiPartStatus.EPILOGUE;
            } else if (contRead && currentAttribute != null && currentStatus == MultiPartStatus.FIELD) {
                // reset index except if to continue in case of FIELD getStatus
                currentAttribute.addContent(undecodedChunk.copy(firstpos, currentpos - firstpos),
                                            false);
                firstpos = currentpos;
            }
            undecodedChunk.readerIndex(firstpos);
        } catch (ErrorDataDecoderException e) {
            // error while decoding
            undecodedChunk.readerIndex(firstpos);
            throw e;
        } catch (IOException e) {
            // error while decoding
            undecodedChunk.readerIndex(firstpos);
            throw new ErrorDataDecoderException(e);
        } catch (IllegalArgumentException e) {
            // error while decoding
            undecodedChunk.readerIndex(firstpos);
            throw new ErrorDataDecoderException(e);
        }
    }
271565
@Override
    public DocumentTranslationRequestData createDocumentTranslationRequest(
            NewDocumentTranslationRequestData newTranslationRequestData)
            throws ServiceException {
        if (newTranslationRequestData == null) {
            throw new IllegalArgumentException("Non-empty newTranslationRequestData must be specified.");
        }

        RestInputDocumentTranslationRequestData newRestTRData = new RestInputDocumentTranslationRequestData(newTranslationRequestData);
        Gson gson = createGson(RestInputDocumentTranslationRequestData.class.getName());
        String jsonBody = gson.toJson(newRestTRData, RestInputDocumentTranslationRequestData.class);
        DocumentTranslationRequestResponse resp = invokeApiJson(
                "POST",
                escapePathSegment(account.getInstanceId()) + "/v2/doc-trs/new",
                jsonBody,
                DocumentTranslationRequestResponse.class);

        if (resp.getStatus() == Status.ERROR) {
            throw new ServiceException(resp.getMessage());
        }

        return new DocumentTranslationRequestDataImpl(resp.id, resp.translationRequest);
    
    }
416380
public RequestTemplate body(Request.Body body) {
    this.body = body;

    header(CONTENT_LENGTH);
    if (body.length() > 0) {
      header(CONTENT_LENGTH, String.valueOf(body.length()));
    }

    return this;
  }
1099741
private static String getRequestBody(HttpServletRequest request) {
        String body = null;
        try (BufferedReader requestReader = request.getReader()) {
            StringBuffer bodyLines = new StringBuffer();
            String bodyLine;
            while ((bodyLine = requestReader.readLine()) != null) {
                bodyLines.append(bodyLine);
            }
            body = bodyLines.toString();
        } catch (IOException e) {
            LOG.info("Failed to obtain a Reader for a potential body of"
                + " this POST, assuming KVP");
        }

        return body;
    }
888069
private Set<String> getPagePathsForTemplate(String[] templates, String rootPath, SlingHttpServletRequest request) {
    Set<String> pagePaths = new HashSet<>();

    if (templates != null && templates.length > 0) {
      try {
        NodeIterator nodes = searchNodesByTemplate(templates, rootPath, request);
        while (nodes.hasNext()) {
          Node node = nodes.nextNode();
          String path = StringUtils.removeEnd(node.getPath(), "/jcr:content");
          pagePaths.add(path);
        }
      }
      catch (RepositoryException ex) {
        log.warn("Seaching nodes by template failed.", ex);
      }
    }

    return pagePaths;
  }
1320489
@Override
    @Nullable
    public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request,
                                 Class<?> expectedResultType) throws Exception {

        final MediaType contentType = request.contentType();
        if (contentType != null && (contentType.is(MediaType.JSON) ||
                                    contentType.subtype().endsWith("+json"))) {
            final ObjectReader reader = readers.computeIfAbsent(expectedResultType, mapper::readerFor);
            if (reader != null) {
                final String content = request.content(contentType.charset().orElse(StandardCharsets.UTF_8));
                try {
                    return reader.readValue(content);
                } catch (JsonProcessingException e) {
                    throw new IllegalArgumentException("failed to parse a JSON document: " + e, e);
                }
            }
        }
        return RequestConverterFunction.fallthrough();
    }
61982
private static String getRequestBody(final HttpServletRequest request) {
        val body = readRequestBodyIfAny(request);
        if (!StringUtils.hasText(body)) {
            LOGGER.trace("Looking at the request attribute [{}] to locate SAML request body", SamlProtocolConstants.PARAMETER_SAML_REQUEST);
            return (String) request.getAttribute(SamlProtocolConstants.PARAMETER_SAML_REQUEST);
        }
        return body;
    }
571750
@Deprecated
  public RequestTemplate bodyTemplate(String bodyTemplate) {
    this.body(Request.Body.bodyTemplate(bodyTemplate, Util.UTF_8));
    return this;
  }
374171
String getBody(Object object, ContentType contentType) {
        if (contentType == ContentType.APPLICATION_FORM_URLENCODED) {
            return jsonToUrlEncodedString((JsonObject) new JsonParser().parse(gson.toJson(object)));
        }

        return gson.toJson(object);
    }
977242
public static TemplatedURLFormatter getTemplatedURLFormatter(ServletRequest servletRequest)
    {
        assert servletRequest != null : "The ServletRequest cannot be null.";

        if (servletRequest == null) {
            throw new IllegalArgumentException("The ServletRequest cannot be null.");
        }

        return (TemplatedURLFormatter) servletRequest.getAttribute(TEMPLATED_URL_FORMATTER_ATTR);
    }
593638
@Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate=new RestTemplate();
        List<HttpMessageConverter<?>> mc=restTemplate.getMessageConverters();
        MappingJackson2HttpMessageConverter json=new MappingJackson2HttpMessageConverter();
        List<MediaType> supportedMediaTypes=new ArrayList<MediaType>();
        supportedMediaTypes.add(new MediaType("text","javascript",Charset.forName("utf-8")));
        supportedMediaTypes.add(new MediaType("application", "javascript", Charset.forName("UTF-8")));
        json.setSupportedMediaTypes(supportedMediaTypes);
        mc.add(json);
        restTemplate.setMessageConverters(mc);
        return restTemplate;
    }
99893
public static Document parseBodyFragment(String bodyHtml, String baseUri) {
        return Parser.parseBodyFragment(bodyHtml, baseUri);
    }
317669
public static <T> MultivaluedMap<String, String> getBodyAsMultiValuedMap(Request<T> request) {
		MultivaluedMap<String, String> map = new BodyMultivaluedMap();

		Class<?> referenceClazz = request.getClass();
		List<Field> fields = ClassUtil.getAnnotatedFields(referenceClazz, Body.class);
		for (Field field : fields) {
			Body body = field.getAnnotation(Body.class);
			String parameter = body.value();

			// in case the value() is null or empty
			if (parameter == null || (parameter != null && parameter.isEmpty())) {
				parameter = field.getName();
			}
			String value = ClassUtil.getValueOf(field, request, referenceClazz, String.class);

			map.putSingle(parameter, value);
		}

		return map;
	}
254997
public static Document parseBodyFragment(String bodyHtml, String baseUri) {
        Document doc = Document.createShell(baseUri);
        Element body = doc.body();
        List<Node> nodeList = parseFragment(bodyHtml, body, baseUri);
        Node[] nodes = nodeList.toArray(new Node[0]); // the node list gets modified when re-parented
        for (int i = nodes.length - 1; i > 0; i--) {
            nodes[i].remove();
        }
        for (Node node : nodes) {
            body.appendChild(node);
        }
        return doc;
    }