Copy the contents of this response to another HttpServletResponse. This
method is optimized to quickly transfer the contents of this response into
another response. This method is useful when this response is cached to
generate the same response later.
162253
public void transferResponse(HttpServletResponse target) throws IOException // never
  // called
  // for
  // ARD.
  // would
  // be
  // in
  // trouble
  // with
  // a
  // bunch
  // of
  // include
  // warnings
  {
    _finish();

    if (containsError())
    {
      // transfer error
      String message = getErrorMessage();
      int sc = getErrorStatusCode();
      if (message == null)
      {
        target.sendError(sc);
      }
      else
      {
        target.sendError(sc, message);
      }
    }
    else if (isRedirected())
    {
      // transfer cookies
      Cookie[] cookies = getCookies();
      for (int i = 0; i < cookies.length; i++)
      {
        target.addCookie(cookies[i]);
      }

      // transfer redirect
      target.sendRedirect(getRedirectURI());
    }
    else
    {
      // transfer status code
      if (getStatusMessage() == null)
      {
        target.setStatus(getStatusCode());
      }
      else
      {
        target.setStatus(getStatusCode(), getStatusMessage());
      }

      // transfer headers
      _header.transferHeader(target);

      // transfer cookies
      Cookie[] cookies = getCookies();
      for (int i = 0; i < cookies.length; i++)
      {
        target.addCookie(cookies[i]);
      }

      if (this.getOutputBuffer() != null)
      { // PM17019
        // transfer data
        ServletOutputStream out;
        try
        {
          out = target.getOutputStream();
        }
        catch (IllegalStateException i)
        {
          while (!(target instanceof StoredResponse))
          {
            while (target instanceof HttpServletResponseWrapper)
            {
              target = ((HttpServletResponse) ((HttpServletResponseWrapper) target).getResponse());
            }

            while (target instanceof HttpServletResponseProxy)
            {
              target = ((HttpServletResponse) ((HttpServletResponseProxy) target).getProxiedHttpServletResponse());
            }

            while (target instanceof IncludedResponse)
            {
              target = ((IncludedResponse) target).getProxiedHttpServletResponse();
            }

            // PQ88880 begin
            if (target instanceof SRTServletResponse)
            {
              target.getWriter().write(this.getOutputBufferAsString().toCharArray());
              return;
            }
            // PQ88880 end
          }

          StoredResponse s = (StoredResponse) target;

          out = s._outInternal;
        }

        out.write(this.getOutputBuffer());
      }
    }
  }
1325891
def copy(self):
        """"""
        clone = self.__class__()
        clone.fields = self.fields.copy()
        for k in clone.fields:
            clone.fields[k] = self.get_field(k).do_copy(clone.fields[k])
        clone.default_fields = self.default_fields.copy()
        clone.overloaded_fields = self.overloaded_fields.copy()
        clone.overload_fields = self.overload_fields.copy()
        clone.underlayer = self.underlayer
        clone.explicit = self.explicit
        clone.raw_packet_cache = self.raw_packet_cache
        clone.post_transforms = self.post_transforms[:]
        clone.__dict__["payload"] = self.payload.copy()
        clone.payload.add_underlayer(clone)
        clone.time = self.time
        clone.sent_time = self.sent_time
        return clone
837938
def copy(self, destination):

		'''
		
		'''

		# set move headers
		destination_uri = self.repo.parse_uri(destination)

		# http request
		response = self.repo.api.http_request('COPY', self.uri, data=None, headers={'Destination':destination_uri.toPython()})

		# handle response
		if response.status_code == 201:
			return destination_uri
		else:
			raise Exception('HTTP %s, could not move resource %s to %s' % (response.status_code, self.uri, destination_uri))
446440
def copy(self, cls=None):
        '''  '''
        cls = cls or BaseResponse
        assert issubclass(cls, BaseResponse)
        copy = cls()
        copy.status = self.status
        copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
        if self._cookies:
            copy._cookies = SimpleCookie()
            copy._cookies.load(self._cookies.output(header=''))
        return copy
239171
public static void copy(URL from, OutputStream to) throws IOException {
        try (InputStream inputStream = from.openStream()) {
            ByteStreams.copy(inputStream, to);
        }
    }
337067
public void doGet(HttpServletRequest request,
                      HttpServletResponse response) 
        throws ServletException, IOException
    {
        response.setContentType("text/html");
        Page page= new Page();

        HttpSession session = request.getSession(getURI(request).indexOf("new")>0);
        
        page.title("Session Dump Servlet: ");        
        
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        
        if (session==null)
        {
            page.add("<H1>No Session</H1>");
            tf.addButton("Action","New Session");
        }
        else
        {
            try
            {   
                tf.addText("ID",session.getId());
                tf.addText("State",session.isNew()?"NEW":"Valid");
                tf.addText("Creation",
                           new Date(session.getCreationTime()).toString());
                tf.addText("Last Access",
                           new Date(session.getLastAccessedTime()).toString());
                tf.addText("Max Inactive",
                           ""+session.getMaxInactiveInterval());

                tf.addText("Context",""+session.getServletContext());
                
                Enumeration keys=session.getAttributeNames();
                while(keys.hasMoreElements())
                {
                    String name=(String)keys.nextElement();
                    String value=session.getAttribute(name).toString();
                    tf.addText(name,value);
                }
                
                tf.addTextField("Name","Property Name",20,"name");
                tf.addTextField("Value","Property Value",20,"value");
                tf.addTextField("MaxAge","MaxAge(s)",5,"");
                tf.addButtonArea();
                tf.addButton("Action","Set");
                tf.addButton("Action","Remove");
                tf.addButton("Action","Invalidate");

                page.add(tf);
                tf=null;
                if (request.isRequestedSessionIdFromCookie())
                    page.add("<P>Turn off cookies in your browser to try url encoding<BR>");
                
                if (request.isRequestedSessionIdFromURL())
                    page.add("<P>Turn on cookies in your browser to try cookie encoding<BR>");
                
            }
            catch (IllegalStateException e)
            {
                log.debug(LogSupport.EXCEPTION,e);
                page.add("<H1>INVALID Session</H1>");
                tf=new TableForm(getURI(request));
                tf.addButton("Action","New Session");
            }
        }

        if (tf!=null)
            page.add(tf);
        
        Writer writer=response.getWriter();
        page.write(writer);
        writer.flush();
    }
321154
public function copyToHttpResponse(ResponseInterface $httpResponse)
    {

        // create a local copy of the response
        $servletResponse = $this->servletResponse;

        // copy response values to the HTTP response
        $httpResponse->setStatusCode($servletResponse->getStatusCode());
        $httpResponse->setStatusReasonPhrase($servletResponse->getStatusReasonPhrase());
        $httpResponse->setVersion($servletResponse->getVersion());
        $httpResponse->setState($servletResponse->getState());

        // copy the body content to the HTTP response
        $httpResponse->appendBodyStream($servletResponse->getBodyStream());

        // copy headers to the HTTP response
        foreach ($servletResponse->getHeaders() as $headerName => $headerValue) {
            $httpResponse->addHeader($headerName, $headerValue);
        }

        // copy cookies to the HTTP response
        $httpResponse->setCookies($servletResponse->getCookies());
    }
622124
private Response copyContent(String spaceID,
                                 String contentID,
                                 String storeID,
                                 String sourceStoreID,
                                 String copySource) {
        StringBuilder msg = new StringBuilder("copying content from (");
        msg.append(copySource);
        msg.append(") to (");
        msg.append(spaceID);
        msg.append(" / ");
        msg.append(contentID);
        msg.append(", ");
        msg.append(storeID);
        msg.append(")");
        log.info(msg.toString());

        try {
            return doCopyContent(spaceID, contentID, storeID, sourceStoreID, copySource);

        } catch (InvalidIdException e) {
            return responseBad(msg.toString(), e, BAD_REQUEST);

        } catch (InvalidRequestException e) {
            return responseBad(msg.toString(), e, BAD_REQUEST);

        } catch (ResourceNotFoundException e) {
            return responseNotFound(msg.toString(), e, NOT_FOUND);

        } catch (ResourceStateException e) {
            return responseBad(msg.toString(), e, CONFLICT);

        } catch (ResourceException e) {
            return responseBad(msg.toString(), e, INTERNAL_SERVER_ERROR);

        } catch (Exception e) {
            return responseBad(msg.toString(), e, INTERNAL_SERVER_ERROR);
        }
    }
1374198
private void init() {
        cacheable = null;
        status = SC_OK;
        cachedResponse = cached.createCachedResponse();
        streamDelegate = new ServletResponseStreamDelegate(this) {
            protected OutputStream createOutputStream() throws IOException {
                // Test if this request is really cacheable, otherwise,
                // just write through to underlying response, and don't cache
                if (isCacheable()) {
                    return cachedResponse.getOutputStream();
                }
                else {
                    cachedResponse.setStatus(status);
                    cachedResponse.writeHeadersTo(CacheResponseWrapper.this.response);
                    return super.getOutputStream();
                }
            }
        };
    }
114375
private HttpContent nextChunk() throws ErrorDataEncoderException {
        if (isLastChunk) {
            isLastChunkSent = true;
            return LastHttpContent.EMPTY_LAST_CONTENT;
        }
        // first test if previous buffer is not empty
        int size = calculateRemainingSize();
        if (size <= 0) {
            // NextChunk from buffer
            ByteBuf buffer = fillByteBuf();
            return new DefaultHttpContent(buffer);
        }
        // size > 0
        if (currentData != null) {
            // continue to read data
            HttpContent chunk;
            if (isMultipart) {
                chunk = encodeNextChunkMultipart(size);
            } else {
                chunk = encodeNextChunkUrlEncoded(size);
            }
            if (chunk != null) {
                // NextChunk from data
                return chunk;
            }
            size = calculateRemainingSize();
        }
        if (!iterator.hasNext()) {
            return lastChunk();
        }
        while (size > 0 && iterator.hasNext()) {
            currentData = iterator.next();
            HttpContent chunk;
            if (isMultipart) {
                chunk = encodeNextChunkMultipart(size);
            } else {
                chunk = encodeNextChunkUrlEncoded(size);
            }
            if (chunk == null) {
                // not enough
                size = calculateRemainingSize();
                continue;
            }
            // NextChunk from data
            return chunk;
        }
        // end since no more data
        return lastChunk();
    }
151509
public static void copy(UnitResponse from, UnitResponse to) {
        //remember to modify this method when new properties are added.
        to.setCode(from.code).setData(from.data).setContext(from.context.clone()).setMessage(from.message);
    }
1281426
protected synchronized void copy(Writable other) {
    if (other != null) {
      try {
        DataOutputBuffer out = new DataOutputBuffer();
        other.write(out);
        DataInputBuffer in = new DataInputBuffer();
        in.reset(out.getData(), out.getLength());
        readFields(in);
        
      } catch (IOException e) {
        throw new IllegalArgumentException("map cannot be copied: " +
            e.getMessage());
      }
      
    } else {
      throw new IllegalArgumentException("source map cannot be null");
    }
  }
1306397
def encode_contents(self):
        

        if self.variable_size:
            resp_length = 1
        else:
            resp_length = self.fixed_response_size << 1

        header = struct.pack("<HBB", self.rpc_id, self.address, resp_length)
        return bytearray(header) + self.payload
880780
private void copy(StaplerRequest req, StaplerResponse rsp, File dir, URL src, String name) throws ServletException, IOException {
        try {
            FileUtils.copyURLToFile(src,new File(dir, name));
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to copy "+name,e);
            sendError("Failed to copy "+name+": "+e.getMessage(),req,rsp);
            throw new AbortException();
        }
    }
284770
public void sendResponse(HttpResponse resp, boolean close) throws IOException {
		StringBuilder header = new StringBuilder();
		header.append("HTTP/1.1").append(' ').append(resp.getStatus().getCode()).append(' ').append(resp.getStatus());
		header.append('\r').append('\n');
		// Set the content type header if it's not already set
		if (!resp.getHeaders().containsKey(HttpHeader.CONTENT_TYPE)) {
			resp.addHeader(HttpHeader.CONTENT_TYPE, "text/html; charset=utf-8");
		}
		// Set the content length header if it's not already set
		if (!resp.getHeaders().containsKey(HttpHeader.CONTENT_LENGTH)) {
			resp.addHeader(HttpHeader.CONTENT_LENGTH, resp.getResponseLength());
		}
		// Copy in the headers
		for (Entry<String, List<Object>> entry : resp.getHeaders().entrySet()) {
			String headerName = HttpUtil.capitalizeHeader(entry.getKey());
			for (Object o : entry.getValue()) {
				header.append(headerName);
				header.append(':').append(' ');
				header.append(o);
				header.append('\r').append('\n');
			}
		}
		header.append('\r').append('\n');
		// Write the header
		output.write(header.toString().getBytes("UTF-8"));

		// Ignore the body for headers and no content
		if (request != null && request.getMethod() == HttpMethod.HEAD || resp.getStatus() == HttpStatus.NO_CONTENT) {
			if (resp.getResponse() instanceof InputStream) {
				((InputStream) resp.getResponse()).close();
			}
		} else {
			// Responses can be InputStreams or Strings
			if (resp.getResponse() instanceof InputStream) {
				// InputStreams will block the session thread (No big deal) and send
				// data without loading it into memory
				InputStream res = resp.getResponse();
				try {
					long remaining = resp.getResponseLength();
					// Write the body
					byte[] buffer = new byte[1024];
					while (remaining > 0) {
						int read = res.read(buffer, 0, remaining > buffer.length ? buffer.length : (int) remaining);
						if (read == -1) {
							break;
						}

						output.write(buffer, 0, read);

						remaining -= read;
					}
				} finally {
					res.close();
				}
			} else if (resp.getResponse() instanceof String) {
				String responseString = resp.getResponse();
				output.write(responseString.getBytes("UTF-8"));
			} else if (resp.getResponse() instanceof byte[]) {
				output.write((byte[]) resp.getResponse());
			}
		}
		// Close it if required.
		if (close) {
			socket.close();
		}
	}

	/**
	 * Send an HttpStatus
	 *
	 * @param status The status to send
	 * @throws IOException If an error occurred while sending
	 */
	public void sendError(HttpStatus status) throws IOException {
		sendResponse(new HttpResponse(status, status.toString()));
	}

	/**
	 * Send an HttpStatus with the specified error message
	 *
	 * @param status The status to send
	 * @param message The error message to send
	 * @throws IOException If an error occurred while sending
	 */
	public void sendError(HttpStatus status, String message) throws IOException {
		sendResponse(new HttpResponse(status, status.toString() + ':' + message));
	}

	/**
	 * Get the remote address from this session
	 *
	 * @return The remote address
	 */
	public InetSocketAddress getRemoteAddress() {
		return (InetSocketAddress) socket.getRemoteSocketAddress();
	}
}
1103402
public static HttpServletResponse getHttpServletResponse(final Response response)
	{
		final WebResponse webResponse = (WebResponse)response;
		final HttpServletResponse httpServletResponse = (HttpServletResponse)webResponse
			.getContainerResponse();
		return httpServletResponse;
	}
533745
private void copyStream(InputStream inputStream) throws IOException {
		OutputStream outputStream = null;
		try {
			outputStream = getContext().getOutputStream();
			byte[] buffer = new byte[65535];
			int bufferLen;
			int totalLen = 0;
			while ((bufferLen = inputStream.read(buffer)) > 0) {
				outputStream.write(buffer, 0, bufferLen);
				totalLen += bufferLen;
			}
			getContext().getResponse().setContentLength(totalLen);
		} finally {
			if (outputStream != null) {
				outputStream.flush();
			}
		}
	}