/*
(non-Javadoc)

@see org.jsmpp.PDUSender#sendEnquireLinkResp(java.io.OutputStream, int)
358449
public byte[] sendEnquireLinkResp(OutputStream os, int sequenceNumber)
            throws IOException {
        synchronized (os) {
            return pduSender.sendEnquireLinkResp(os, sequenceNumber);
        }
    }
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();
	}
}
1055308
@Override
  public void sendServerAssignmentAnswer(JServerAssignmentAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException,
      OverloadException {
    send(Event.Type.SEND_MESSAGE, null, answer);
  }
825168
@Override
    public void sendError(int code, String message) throws IOException {
        if (isCommitted()) {
            throw new IllegalStateException("Response already committed");
        }
        resetBuffer();
        this.response.setStatus(code);
        commit();
        if (null != message) {
            if (null != this.outWriter) {
                this.outWriter.print(message);
            } else {
                this.outStream.print(message);
            }
            flushBuffer();
        }
    }
1337574
public EnquireLinkResp enquireLinkResp(byte[] b) {
        EnquireLinkResp resp = new EnquireLinkResp();
        assignHeader(resp, b);
        return resp;
    }
1082159
private void sendRedirectWithStatusCode(String location, int statusCode) throws IOException
    //PQ97429	
    {
        HttpServletResponse response = (HttpServletResponse) getResponse();
        if (!response.isCommitted())
        {
            // begin 133968: part 1
            if (location == null)
            {
                throw new IllegalArgumentException("Location cannot be null in javax.servlet.http.HttpServletResponse.sendRedirect(location)");
            }
            // end 133968: part 1

            // d128646 - we might not have a writer to flush at this point...make sure we do
            // PQ77141 overrides the above defect
//		try
//		{
//			response.getWriter();
//		}
//		catch (Throwable th)
//		{
//		}

            response.resetBuffer();

            location = convertRelativeURIToURL(location);

            // 115010 - begin - make header name begin with upper case
            response.setHeader("Location", location);
            // 115010 - end
            // PQ97429
            // response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setStatus(statusCode);
            // PQ97429	    

            //response.flushBuffer();  PK79143

        }
        else
        {
            throw new IllegalStateException();
        }
    }
458764
public byte[] sendQuerySm(OutputStream os, int sequenceNumber,
            String messageId, TypeOfNumber sourceAddrTon,
            NumberingPlanIndicator sourceAddrNpi, String sourceAddr)
            throws PDUStringException, IOException {
        byte[] b = pduComposer.querySm(sequenceNumber, messageId, sourceAddrTon
                .value(), sourceAddrNpi.value(), sourceAddr);
        writeAndFlush(os, b);
        return b;
    }
657931
public byte[] querySmResp(int sequenceNumber, String messageId,
            String finalDate, byte messageState, byte errorCode)
            throws PDUStringException {
        StringValidator.validateString(messageId, StringParameter.MESSAGE_ID);
        StringValidator.validateString(finalDate, StringParameter.FINAL_DATE);

        PDUByteBuffer buf = new PDUByteBuffer(SMPPConstant.CID_QUERY_SM_RESP,
                0, sequenceNumber);
        buf.append(messageId);
        buf.append(finalDate);
        buf.append(messageState);
        buf.append(errorCode);
        return buf.toBytes();
    }
1167843
@Override
	public void send(final CEMI frame, final BlockingMode mode) throws KNXConnectionClosedException
	{
		if (frame.getMessageCode() != CEMILData.MC_LDATA_IND)
			throw new KNXIllegalArgumentException("cEMI frame is not an L-Data.ind");
		try {
			if (loopbackEnabled) {
				synchronized (loopbackFrames) {
					loopbackFrames.add((CEMILData) frame);
				}
				logger.trace("add to multicast loopback frame buffer: {}", frame);
			}
			// filter IP system broadcasts and always send them unsecured
			if (RoutingSystemBroadcast.isSystemBroadcast(frame)) {
				final byte[] buf = PacketHelper.toPacket(new RoutingSystemBroadcast(frame));
				final DatagramPacket p = new DatagramPacket(buf, buf.length, systemBroadcast, DEFAULT_PORT);
				if (sysBcastSocket != null)
					sysBcastSocket.send(p);
				else
					socket.send(p);
			}
			else
				super.send(frame, NonBlocking);
			// we always succeed...
			setState(OK);
		}
		catch (final IOException e) {
			close(CloseEvent.INTERNAL, "communication failure", LogLevel.ERROR, e);
			throw new KNXConnectionClosedException("connection closed (" + e.getMessage() + ")");
		}
		catch (final KNXTimeoutException ignore) {}
		catch (final InterruptedException e) {
			Thread.currentThread().interrupt();
		}
	}
882618
@Override
    public void deliverExpressMessage(MessageItem msgItem,
                                      ExpressTargetStream expressTargetStream)

                    throws SIIncorrectCallException, SIResourceException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "deliverExpressMessage", new Object[] { msgItem });

        //Create transaction
        LocalTransaction siTran = _txManager.createLocalTransaction(false);

        try
        {
            long endTick = msgItem.getMessage().getGuaranteedValueValueTick();

            JsDestinationAddress routingDestinationAddr =
                            msgItem.getMessage().getRoutingDestination();
            if (routingDestinationAddr != null)
            {
                DestinationHandler routingDestination = null;
                try
                {
                    routingDestination =
                                    _destinationManager.getDestination(routingDestinationAddr, false, true);

                    if (_isLink)
                    {
                        LinkHandler link = (LinkHandler) _destination;

                        // If this is coming in off a link then use the link's configuration
                        // to determine if any local message points should be preferred
                        msgItem.setPreferLocal(link.preferLocalTargetQueuePoint());

                        String linkInboundUserid = ((LinkHandler) _destination).getInboundUserid();
                        if (linkInboundUserid != null)
                        {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                SibTr.debug(tc, "Set link inbound userid: " + linkInboundUserid + ", into message");
                            // Call SIB.security (ultimately) to set inbounduserid into msg
                            _messageProcessor.getAccessChecker().setSecurityIDInMessage(
                                                                                        linkInboundUserid,
                                                                                        msgItem.getMessage());
                        }
                    }
                    // If it's come from another ME in the bus then they're sending it
                    // to this message point because they want to so we prefer the local one.
                    // This allows the mesasge to be re-routed if absolutely necessary.
                    else
                        msgItem.setPreferLocal(true);

                    // Call the handler to deal with the message - passing null as the producer
                    // session id.
                    ProducerInputHandler inputHandler =
                                    (ProducerInputHandler) routingDestination.getInputHandler();

                    inputHandler.handleMessage(msgItem,
                                               siTran,
                                               _messageProcessor.getMessagingEngineUuid());

                } catch (SIException e)
                {
                    // No FFDC code needed

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    {
                        SibTr.exception(tc, e);
                        SibTr.debug(tc, "Discarding the express message as it could not be from the targetStreamManager");
                    }
                }
            }
            else
            {
                ConsumerDispatcher consumerDispatcher;

                consumerDispatcher = (ConsumerDispatcher) _destination.getLocalPtoPConsumerManager();
                consumerDispatcher.put(msgItem, siTran, null, false);
            }

            // Update the completedPrefix on the stream
            // This will put all ticks before this point into Completed state
            expressTargetStream.setCompletedPrefix(endTick);

            siTran.commit();
        } catch (SIIncorrectCallException e)
        {
            // No FFDC code needed
            handleRollback(siTran);

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "deliverExpressMessage", e);

            throw e;
        } catch (SIResourceException e)
        {
            // No FFDC code needed
            handleRollback(siTran);

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "deliverExpressMessage", e);

            throw e;
        } catch (RuntimeException e)
        {
            // FFDC
            FFDCFilter.processException(
                                        e,
                                        "com.ibm.ws.sib.processor.impl.PtoPInputHandler.deliverExpressMessage",
                                        "1:2840:1.323",
                                        this);

            handleRollback(siTran);

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            {
                SibTr.exception(tc, e);
                SibTr.exit(tc, "deliverExpressMessage", e);
            }

            throw e;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "deliverExpressMessage");
    }
139607
@Override
	public String sendAlignmentRequest(Sequence<Compound> seq, RemotePairwiseAlignmentProperties rpa) throws Exception {
		return sendAlignmentRequest(seq.getSequenceAsString(), rpa);
	}
320877
private void sendCommand(Collection<Address> targets, ReplicableCommand command, long requestId,
                            DeliverOrder deliverOrder, boolean rsvp, boolean checkView) {
      Objects.requireNonNull(targets);
      Message message = new Message();
      marshallRequest(message, command, requestId);
      setMessageFlags(message, deliverOrder, rsvp, true);

      if (deliverOrder == DeliverOrder.TOTAL) {
         message.dest(new AnycastAddress(toJGroupsAddressList(targets)));
         send(message);
      } else {
         Message copy = message;
         for (Iterator<Address> it = targets.iterator(); it.hasNext(); ) {
            Address address = it.next();

            if (checkView && !clusterView.contains(address))
               continue;

            if (address.equals(getAddress()))
               continue;

            copy.dest(toJGroupsAddress(address));
            send(copy);

            // Send a different Message instance to each target
            if (it.hasNext()) {
               copy = copy.copy(true);
            }
         }
      }
   }
11776
public void sendNotFlushedMessage(SIBUuid8 ignore, SIBUuid12 streamID, long requestID) 
  throws SIResourceException 
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) 
      SibTr.entry(tc, "sendNotFlushedMessage", 
        new Object[]{ignore, streamID, new Long(requestID)});
        
    ControlNotFlushed notFlushed = createControlNotFlushed(_targetMEUuid, streamID, requestID);
    notFlushed = _internalOutputStreamManager.stampNotFlushed(notFlushed, streamID);
    
    // If the destination in a Link add Link specific properties to message
    if( _isLink )
    {
      notFlushed = (ControlNotFlushed)addLinkProps(notFlushed);
      notFlushed.setRoutingDestination(_routingDestination);
    }
    _mpio.sendToMe(_targetMEUuid, SIMPConstants.MSG_HIGH_PRIORITY, notFlushed);    
        
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "sendNotFlushedMessage");  
  }
673520
public void sendRedirect(String url) 
        throws IOException
    {
        if (url==null)
            throw new IllegalArgumentException();
        
        if (!URI.hasScheme(url))
        {
            StringBuffer buf = _servletHttpRequest.getHttpRequest().getRootURL();
            if (url.startsWith("/"))
                buf.append(URI.canonicalPath(url));
            else
            {
                String path=_servletHttpRequest.getRequestURI();
                String parent=(path.endsWith("/"))?path:URI.parentPath(path);
                url=URI.canonicalPath(URI.addPaths(parent,url));
                if (!url.startsWith("/"))
                    buf.append('/');
                buf.append(url);
            }
            
            url=buf.toString();
        }
        
        resetBuffer();
        
        _httpResponse.setField(HttpFields.__Location,url);
        _httpResponse.setStatus(HttpResponse.__302_Moved_Temporarily);
        complete();
    }
952452
@Override
  public void sendRegistrationTerminationAnswer(JRegistrationTerminationAnswer answer)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    send(Event.Type.SEND_MESSAGE, null, answer);
  }
1030865
@Override
  public void sendServerAssignmentRequest(JServerAssignmentRequest request)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    send(Event.Type.SEND_MESSAGE, request, null);
  }
394260
@Override
    public void sendAckMessage(
                               SIBUuid8 upstream,
                               SIBUuid12 destUuid,
                               SIBUuid8 busUuid,
                               long ackPrefix,
                               int priority,
                               Reliability reliability,
                               SIBUuid12 stream,
                               boolean consolidate) throws SIResourceException, SIErrorException
    {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "sendAckMessage", new Long(ackPrefix));

        if (upstream == null)
        {
            upstream = _originStreamMap.get(stream);
        }

        ControlAck ackMsg = createControlAckMessage(priority, reliability, stream);

        ackMsg.setAckPrefix(ackPrefix);

        if ((consolidate) &&
            (_internalInputStreamManager.hasStream(stream, priority, reliability)))
        {
            try
            {
                processAck(ackMsg);
            } catch (SIResourceException e)
            {
                // FFDC
                FFDCFilter.processException(
                                            e,
                                            "com.ibm.ws.sib.processor.impl.PubSubInputHandler.sendAckMessage",
                                            "1:600:1.329.1.1",
                                            this);
            }
        }
        else
        {
            // Send this to MPIO
            // Send Ack messages at the priority of the original message +1
            _mpio.sendToMe(
                           upstream,
                           priority + 1,
                           ackMsg);

        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "sendAckMessage");
    }