Create a response builder for a TimeMap response.

@param mementos the mementos
@param baseUrl the base URL
@param req the LDP request
@return a response builder object
348825
public ResponseBuilder getTimeMapBuilder(final SortedSet<Instant> mementos, final TrellisRequest req,
            final String baseUrl) {

        final List<MediaType> acceptableTypes = req.getAcceptableMediaTypes();
        final String identifier = fromUri(baseUrl).path(req.getPath()).build().toString();
        final List<Link> links = getMementoLinks(identifier, mementos).collect(toList());

        final ResponseBuilder builder = ok().link(identifier, ORIGINAL + " " + TIMEGATE);
        builder.links(links.stream().map(this::filterLinkParams).toArray(Link[]::new))
            .link(Resource.getIRIString(), TYPE).link(RDFSource.getIRIString(), TYPE)
            .header(ALLOW, join(",", GET, HEAD, OPTIONS));

        final RDFSyntax syntax = getSyntax(trellis.getIOService(), acceptableTypes, APPLICATION_LINK_FORMAT);

        if (syntax != null) {
            final IRI profile = getProfile(acceptableTypes, syntax);
            final IRI jsonldProfile = profile != null ? profile : compacted;

            final StreamingOutput stream = new StreamingOutput() {
                @Override
                public void write(final OutputStream out) throws IOException {
                    trellis.getIOService().write(timemap.asRdf(identifier, links), out, syntax, jsonldProfile);
                }
            };

            return builder.type(syntax.mediaType()).entity(stream);
        }

        return builder.type(APPLICATION_LINK_FORMAT)
            .entity(links.stream().map(this::filterLinkParams).map(Link::toString).collect(joining(",\n")) + "\n");
    }
358636
public BaseServerResponseException addResponseHeader(String theName, String theValue) {
		Validate.notBlank(theName, "theName must not be null or empty");
		Validate.notBlank(theValue, "theValue must not be null or empty");
		if (getResponseHeaders().containsKey(theName) == false) {
			getResponseHeaders().put(theName, new ArrayList<>());
		}
		getResponseHeaders().get(theName).add(theValue);
		return this;
	}
547703
@Override
    public void sendResponse(StoreStats performanceStats,
                             boolean isFromLocalZone,
                             long startTimeInMs) throws Exception {

        /*
         * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage.
         * However when writing to the outputStream we only send the multiPart object and not the entire
         * mimeMessage. This is intentional.
         *
         * In the earlier version of this code we used to create a multiPart object and just send that multiPart
         * across the wire.
         *
         * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates
         * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated
         * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the
         * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders()
         * on the body part. It's this updateHeaders call that transfers the content type from the
         * DataHandler to the part's MIME Content-Type header.
         *
         * To make sure that the Content-Type headers are being updated (without changing too much code), we decided
         * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart.
         * This is to make sure multiPart's headers are updated accurately.
         */

        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
        MimeMultipart multiPart = new MimeMultipart();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        String contentLocationKey = "/" + this.storeName + "/" + base64Key;

        for(Versioned<byte[]> versionedValue: versionedValues) {

            byte[] responseValue = versionedValue.getValue();

            VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
            String eTag = RestUtils.getSerializedVectorClock(vectorClock);
            numVectorClockEntries += vectorClock.getVersionMap().size();

            // Create the individual body part for each versioned value of the
            // requested key
            MimeBodyPart body = new MimeBodyPart();
            try {
                // Add the right headers
                body.addHeader(CONTENT_TYPE, "application/octet-stream");
                body.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
                body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag);
                body.setContent(responseValue, "application/octet-stream");
                body.addHeader(RestMessageHeaders.CONTENT_LENGTH,
                               Integer.toString(responseValue.length));

                multiPart.addBodyPart(body);
            } catch(MessagingException me) {
                logger.error("Exception while constructing body part", me);
                outputStream.close();
                throw me;
            }

        }
        message.setContent(multiPart);
        message.saveChanges();
        try {
            multiPart.writeTo(outputStream);
        } catch(Exception e) {
            logger.error("Exception while writing multipart to output stream", e);
            outputStream.close();
            throw e;
        }
        ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
        responseContent.writeBytes(outputStream.toByteArray());

        // Create the Response object
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

        // Set the right headers
        response.setHeader(CONTENT_TYPE, "multipart/binary");
        response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
        response.setHeader(CONTENT_LOCATION, contentLocationKey);

        // Copy the data into the payload
        response.setContent(responseContent);
        response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

        // Write the response to the Netty Channel
        if(logger.isDebugEnabled()) {
            String keyStr = RestUtils.getKeyHexString(this.key);
            debugLog("GET",
                     this.storeName,
                     keyStr,
                     startTimeInMs,
                     System.currentTimeMillis(),
                     numVectorClockEntries);
        }
        this.messageEvent.getChannel().write(response);

        if(performanceStats != null && isFromLocalZone) {
            recordStats(performanceStats, startTimeInMs, Tracked.GET);
        }

        outputStream.close();

    }
1139088
public static Stream<Link> getMementoLinks(final String identifier, final SortedSet<Instant> mementos) {
        if (mementos.isEmpty()) {
            return empty();
        }
        return concat(getTimeMap(identifier, mementos.first(), mementos.last()),
                mementos.stream().map(mementoToLink(identifier)));
    }
786656
private <T> Sequence<T> run(
      final QueryPlus<T> queryPlus,
      final Map<String, Object> responseContext,
      final UnaryOperator<TimelineLookup<String, ServerSelector>> timelineConverter
  )
  {
    return new SpecificQueryRunnable<>(queryPlus, responseContext).run(timelineConverter);
  }
655678
public static Response createLinksHandler(ParaObject pobj, String id2) {
		try (final Metrics.Context context = Metrics.time(null, RestUtils.class, "links", "create")) {
			if (id2 != null && pobj != null) {
				String linkid = pobj.link(id2);
				if (linkid == null) {
					return getStatusResponse(Response.Status.BAD_REQUEST, "Failed to create link.");
				} else {
					return Response.ok(linkid, MediaType.TEXT_PLAIN_TYPE).build();
				}
			} else {
				return getStatusResponse(Response.Status.BAD_REQUEST, "Parameters 'type' and 'id' are missing.");
			}
		}
	}
925175
public static void addMementoDatetimeHeader(HttpServletResponse response,
			CaptureSearchResult result) {
		response.setHeader(MEMENTO_DATETIME, formatLinkDate(result.getCaptureDate()));
	}
679281
private void respondToListSets(Map<String, String> args,
                                   String baseURL,
                                   List<?> sets,
                                   ResumptionToken resumptionToken,
                                   PrintWriter out) {
        appendTop(out);
        appendRequest(args, baseURL, out);
        out.println("  <ListSets>");
        for (int i = 0; i < sets.size(); i++) {
            SetInfo s = (SetInfo) sets.get(i);
            out.println("    <set>");
            out.println("      <setSpec>" + s.getSpec() + "</setSpec>");
            out.println("      <setName>" + s.getName() + "</setName>");
            Iterator<String> iter = s.getDescriptions().iterator();
            while (iter.hasNext()) {
                out.println("      <setDescription>\n");
                out.println(iter.next());
                out.println("      </setDescription>\n");
            }
            out.println("    </set>");
        }
        appendResumptionToken(resumptionToken, out);
        out.println("  </ListSets>");
        appendBottom(out);
    }
1156639
public static UnitResponse createTimeout(Object dataOrException, String errMsg) {
        return new UnitResponse().setCode(Group.CODE_TIME_OUT).setData(dataOrException).setMessage(errMsg);
    }
401616
static ObjectMapper createModifiableObjectMapper(final ObjectMapper objectMapper) {
        objectMapper.registerModule(new BuilderModule());
        registerModule(objectMapper, "com.fasterxml.jackson.datatype.guava.GuavaModule");
        registerModule(objectMapper, "com.fasterxml.jackson.datatype.jdk8.Jdk8Module");
        registerModule(objectMapper, "com.fasterxml.jackson.datatype.joda.JodaModule");
        registerModule(objectMapper, "com.fasterxml.jackson.datatype.jsr310.JavaTimeModule");
        registerAdditionalModules(objectMapper, System::getProperty);
        objectMapper.configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
        objectMapper.setDateFormat(new StdDateFormat());
        return objectMapper;
    }
890971
public HttpResponseHandler<SdkBaseException> createErrorResponseHandler(
            JsonErrorResponseMetadata errorResponsMetadata) {
        return new ApiGatewayErrorResponseHandler(
                createErrorUnmarshallers(errorResponsMetadata.getErrorShapes().stream()),
                SdkStructuredPlainJsonFactory.JSON_FACTORY);
    }
223623
public void addAnyTimeInterrogationResponse(long invokeId, SubscriberInfo subscriberInfo,
            MAPExtensionContainer extensionContainer) throws MAPException {
        doAddAnyTimeInterrogationResponse(false, invokeId, subscriberInfo, extensionContainer);
    }
1058890
public void getTimeOid (ClientObject source, String timeBase,
                            TimeBaseService.GotTimeBaseListener listener)
        throws InvocationException
    {
        // look up the time base object in question
        TimeBaseObject time = getTimeBase(timeBase);
        if (time == null) {
            throw new InvocationException(NO_SUCH_TIME_BASE);
        }
        // and send the response
        listener.gotTimeOid(time.getOid());
    }
242267
public Response.ResponseBuilder getTimeGateBuilder(final LdpRequest req, final String baseUrl) {
        final String identifier = getBaseUrl(baseUrl, req) + req.getPartition() + req.getPath();
        return Response.status(FOUND)
            .location(fromUri(identifier + "?version=" + req.getDatetime().getInstant().toEpochMilli()).build())
            .link(identifier, ORIGINAL + " " + TIMEGATE)
            .links(getMementoLinks(identifier, resource.getMementos()).toArray(Link[]::new))
            .header(VARY, ACCEPT_DATETIME);
    }
1165386
public void addResponse(CheckRequest req, CheckResponse resp) {
    if (cache == null) {
      return;
    }
    String signature = sign(req).toString();
    long now = ticker.read();
    int quotaScale = 0; // WIP
    synchronized (cache) {
      CachedItem item = cache.getIfPresent(signature);
      if (item == null) {
        cache.put(signature, new CachedItem(resp, req, kinds, now, quotaScale));
      } else {
        item.lastCheckTimestamp = now;
        item.response = resp;
        item.quotaScale = quotaScale;
        item.isFlushing = false;
        cache.put(signature, item);
      }
    }
  }
687076
@Deprecated
    public static SitemapGenerator of(String baseUrl, AdditionalNamespace[] additionalNamespaces) {
        return new SitemapGenerator(baseUrl, additionalNamespaces);
    }
886326
public static <T> GenericResponseBuilder<T> fromResponse(GenericResponse<T> response) {
    GenericResponseBuilder<T> builder =
        genericResponseBuilderFactory.create(response.getStatus(), response.body());

    for (String headerName : response.getHeaders().keySet()) {
      List<Object> headerValues = response.getHeaders().get(headerName);
      for (Object headerValue : headerValues) {
        builder.header(headerName, headerValue);
      }
    }
    return builder;
  }