/*
@see com.ibm.ws.tcpchannel.internal.TCPWriteRequestContextImpl#
processSyncWriteRequest(long, int)
435826
@Override
    public long processSyncWriteRequest(long numBytes, int timeout) throws IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "processSyncRequest(" + numBytes + "," + timeout + ")");
        }

        long numUserBytesWritten = 0; // no. of user bytes written

        if (numBytes != 0) {
            if (this.blockWait == null) {
                this.blockWait = new SimpleSync();
            }
            this.blockingIOError = null;

            // before we write, signal that we want to do the write ourselves
            // and not the worker threads.
            this.blockedThread = true;

            VirtualConnection vc = writeInternal(numBytes, null, false, timeout);

            while (vc == null) {
                // block until we are told to write
                this.blockWait.simpleWait();

                if (this.blockingIOError == null) {
                    vc = ((NioTCPChannel) getTCPConnLink().getTCPChannel()).getWorkQueueManager().processWork(this, 1);
                } else {
                    break;
                }
            }

            this.blockedThread = false;
            if (this.blockingIOError != null) {
                throw this.blockingIOError;
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "getIOCompleteAmount() -->" + String.valueOf(getIOCompleteAmount()));
            }
            numUserBytesWritten = getIOCompleteAmount();
        } else {
            WsByteBuffer buffers[] = getBuffers();
            NioSocketIOChannel channel = (NioSocketIOChannel) getTCPConnLink().getSocketIOChannel();
            if (buffers.length == 1) {
                numUserBytesWritten = channel.write(buffers[0].getWrappedByteBufferNonSafe());
            } else {
                numUserBytesWritten = channel.write(getByteBufferArray());
            }
        }

        // return the number of bytes written
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "processSyncRequest", Long.valueOf(numUserBytesWritten));
        }
        return (numUserBytesWritten);
    }
611221
void write(ByteCodeWriter out)
    throws IOException
  {
    out.write(ConstantPool.CP_LONG);
    out.writeLong(_value);
  }
282627
@Override
    public void filterWrite(final NextFilter nextFilter,
            final IoSession session, final WriteRequest writeRequest) {
        writeData(nextFilter, session, writeRequest, false);
    }
106989
@Override
    public void complete(com.ibm.wsspi.channelfw.VirtualConnection vc, com.ibm.wsspi.tcpchannel.TCPWriteRequestContext wsc) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())  
            Tr.debug(tc, "complete called : " + vc + "WriteListener enabled: " + this._wl);

        synchronized(_upgradeOut) {

            if (null == vc) {
                return;
            }

            if (_upgradeOut.getBufferHelper().isOutputStream_closed()) {

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "complete , outputStream closed ignoring complete : " + vc);

                return;
            }

            // clean up any request state we had on this thread.
            WebContainerRequestState reqState = WebContainerRequestState.getInstance(true);
            reqState.init();
            try{    
                _upgradeOut.getBufferHelper().writeRemainingToBuffers();                 

            } catch (Exception e) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){  
                    Tr.debug(tc, "exception during writeBuffers" + e.toString());
                }
                this.error(vc, e);
                return;
            }


            // rest must be written now ,
            // this case will only be true if write which went aysnc was
            // from println, now we have to write crlf
            if ( _upgradeOut.getBufferHelper().isInternalReady() && _upgradeOut.getBufferHelper().write_crlf_pending) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "write CRLF bytes  , WriteListener enabled: " + this._wl);
                try {
                    reqState.setAttribute("com.ibm.ws.webcontainer.upgrade.WriteAllowedonThisThread", true);
                    reqState.setAttribute("com.ibm.ws.webcontainer.upgrade.CRLFWriteinPorgress", true);
                    _upgradeOut.getBufferHelper().writeCRLFIfNeeded();
                } catch (IOException e) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) 
                        Tr.debug(tc, " Exception during write CRLF bytes: " + e);

                    _upgradeOut.getBufferHelper().write_crlf_pending = false;
                    this.error(vc, e);
                    return;
                }
            }

            if( _upgradeOut.getBufferHelper().isInternalReady()){
                WebContainerRequestState.getInstance(true).setAttribute("com.ibm.ws.webcontainer.upgrade.WriteAllowedonThisThread", true);

                _upgradeOut.getBufferHelper().setReadyForApp(true);

                // if close was in progress
                if(_upgradeOut.getBufferHelper().isOutputStream_close_initiated_but_not_Flush_ready()){
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){
                        Tr.debug(tc, "complete , In process of closing outputStream, no more data is left to write, call close");
                    }
                    try {
                        if(_upCon.isOutputStream_CloseStartedFromWC()){
                            //at this point inputstream and handler are already closed
                            _upCon.closeOutputandConnection();
                        }
                        else{
                            _upgradeOut.close();
                        }
                    } catch (Exception e) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                            Tr.debug(tc, "complete , stack exception" + e.toString());

                        this.error(vc, e);
                    }

                }// no close in progress now check if onWP needs to be called.
                else{
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){  
                        Tr.debug(tc, "WriteListener enabled: " + this._wl + " ,status_not_ready_checked -->" + _upgradeOut.getBufferHelper().status_not_ready_checked);
                    }
                    if (_upgradeOut.getBufferHelper().status_not_ready_checked) {
                        try{
                            _upgradeOut.getBufferHelper().status_not_ready_checked = false;

                            // Push the original thread's context onto the current thread,
                            // also save off the current thread's context
                            _contextManager.pushContextData();
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){  
                                Tr.debug(tc, "Calling user's WriteListener onWritePossible");
                            }
                            // Call into the user's WriteListener to indicate more data cane
                            // be written
                            _wl.onWritePossible();
                        } catch (Exception e) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){  
                                Tr.debug(tc, "stack exception" + e.toString());
                            }
                            this.error(vc, e);
                        } finally {
                            // Revert back to the thread's current context
                            _contextManager.popContextData();
                        }
                    }
                    else{
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){  
                            Tr.debug(tc, "WriteListener enabled: " 
                                            + this._wl + " .onWritePossible will be skipped as isReady has not been checked since write went async.");
                        }
                    }
                }
            }
        }
    }
542734
@Override
    public void onProcessUnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd) {
//        NetworkIdState networkIdState = this.mapStack.getMAPProvider().getNetworkIdState(0);
//        if (!(networkIdState == null || networkIdState.isAvailavle() && networkIdState.getCongLevel() == 0)) {
//            // congestion or unavailable
//            logger.warn("onProcessUnstructuredSSRequest Congestion - onUnstructuredSSRequest: networkIdState=" + networkIdState);
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("onProcessUnstructuredSSRequestIndication for DialogId=%d", procUnstrReqInd
                    .getMAPDialog().getLocalDialogId()));
        }
        try {
            long invokeId = procUnstrReqInd.getInvokeId();

            USSDString ussdStrObj = this.mapProvider.getMAPParameterFactory().createUSSDString(
                    "USSD String : Hello World <CR> 1. Balance <CR> 2. Texts Remaining");
            CBSDataCodingScheme ussdDataCodingScheme = new CBSDataCodingSchemeImpl(0x0F);
            MAPDialogSupplementary dialog = procUnstrReqInd.getMAPDialog();

            dialog.setUserObject(invokeId);

            ISDNAddressString msisdn = this.mapProvider.getMAPParameterFactory().createISDNAddressString(
                    AddressNature.international_number, NumberingPlan.ISDN, "31628838002");

            dialog.addUnstructuredSSRequest(ussdDataCodingScheme, ussdStrObj, null, msisdn);
            dialog.send();
        } catch (MAPException e) {
            logger.error("Error while sending UnstructuredSSRequest ", e);
        }
    }
137802
public void writeDataMessage(WriteRequest request, DataBuffer buffer) {
    if (buffer == null) {
      write(request);
      return;
    }
    Preconditions.checkState(!request.hasCommand(),
        "write request command should not come with data buffer");
    Preconditions.checkState(buffer.readableBytes() > 0,
        "invalid data size from write request message");
    if (!tryAcquireSemaphore()) {
      return;
    }
    mSerializingExecutor.execute(() -> {
      try {
        writeData(buffer);
      } finally {
        mSemaphore.release();
      }
    });
  }
638697
public void writeTo(HttpServletResponse response) {
		long time = System.currentTimeMillis();
		long processTime = time - contextTsCurrent.get();
		long processTimeTotal = contextMsProcess.get() + processTime;
		long networkTimeTotal = contextMsNetwork.get();
		
		StringBuilder cookiesDump = new StringBuilder();
		for (Entry<String, Cookie> entry : responseCookies.get().entrySet()) {
			javax.servlet.http.Cookie c = buildServletCookie(entry.getKey(), entry.getValue());
			response.addCookie(c);
			cookiesDump.append(c.toString()).append(";");
		}
		
		if (verbose) log.info("<<< Time total " + String.valueOf(time - contextTsStart.get()) + " (+" + processTime + "p " + processTimeTotal + "p " + networkTimeTotal + "n)" + " [" + contextUrl.get() + "]" + ". Set-Cookie to client: " + cookiesDump.toString());
	}
1010439
public void write(long pos, Buffer source, long byteCount) throws IOException {
    if (byteCount < 0 || byteCount > source.size()) throw new IndexOutOfBoundsException();

    while (byteCount > 0L) {
      long bytesWritten = fileChannel.transferFrom(source, pos, byteCount);
      pos += bytesWritten;
      byteCount -= bytesWritten;
    }
  }
797620
def process_request(self, request, client_address):
        """"""
        if not self._parallel:
            self._process_request(request, client_address)
            return
        t = self._thread_factory(
            target=self._process_request, args=(request, client_address))
        t.daemon = True
        t.start()
657435
protected void processRequest(String requestedPath, HttpServletRequest request, HttpServletResponse response,
			BundleHashcodeType bundleHashcodeType) throws IOException {

		boolean writeResponseHeader = false;
		boolean validBundle = true;
		if (!jawrConfig.isDebugModeOn() && jawrConfig.isStrictMode()
				&& bundleHashcodeType.equals(BundleHashcodeType.INVALID_HASHCODE)) {
			validBundle = false;
		}

		if (this.jawrConfig.isDebugModeOn() && null != request.getParameter(GENERATION_PARAM))
			requestedPath = request.getParameter(GENERATION_PARAM);

		// If debug mode is off, check for If-Modified-Since and If-none-match
		// headers and set response caching headers.
		if (!this.jawrConfig.isDebugModeOn()) {
			// If a browser checks for changes, always respond 'no changes'.
			if (validBundle && (null != request.getHeader(IF_MODIFIED_SINCE_HEADER)
					|| null != request.getHeader(IF_NONE_MATCH_HEADER))) {
				response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
				if (LOGGER.isDebugEnabled())
					LOGGER.debug("Returning 'not modified' header. ");
				return;
			}

			if (validBundle) {
				// Add caching headers
				setResponseHeaders(response);
			} else {

				writeResponseHeader = illegalBundleRequestHandler.writeResponseHeader(requestedPath, request, response);
				if (!writeResponseHeader) {
					// Add caching headers
					setResponseHeaders(response);
				}
			}
		}

		try {
			if (validBundle || illegalBundleRequestHandler.canWriteContent(requestedPath, request)) {

				// By setting content type, the response writer will use
				// appropriate encoding
				response.setContentType(getContentType(requestedPath, request));
				writeContent(requestedPath, request, response);
				if (LOGGER.isDebugEnabled())
					LOGGER.debug("request succesfully attended");
			} else {
				if (!writeResponseHeader) {
					logBundleNotFound(requestedPath);
					response.sendError(HttpServletResponse.SC_NOT_FOUND);
				}
			}

		} catch (EOFException eofex) {
			LOGGER.info("Browser cut off response", eofex);
		} catch (IOException e) {
			if (ClientAbortExceptionResolver.isClientAbortException(e)) {
				LOGGER.debug("Browser cut off response", e);
			} else {
				throw e;
			}
		} catch (ResourceNotFoundException e) {
			logBundleNotFound(requestedPath);
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
		}
	}
1287874
@Override
    protected void process(@NotNull WireIn inWire,
                           @NotNull WireOut outWire,
                           @NotNull SessionDetailsProvider sd) {

        inWire.readDocument(m -> {
            long tid = inWire.read(() -> "tid").int64();
            outWire.writeDocument(true, meta -> meta.write(() -> "tid")
                    .int64(tid));

        }, d -> {
            outWire.writeDocument(false, data -> data.write(() -> "payloadResponse")
                    .text(inWire.read(() -> "payload").text()));
        });
    }
810414
@Override
    public Boolean process(final AciResponseInputStream aciResponse) {
        try {
            IOUtils.copy(aciResponse, outputStream);

            outputStream.flush();

            return true;
        }
        catch(final IOException e) {
            throw new ProcessorException(e);
        }
    }
622854
public final static void writeLong(BytesRef dst, long i) {
    writeInt(dst, (int) (i >> 32));
    writeInt(dst, (int) i);
  }
57613
void writeLong(long value) throws IOException {
        if (value < MIN_FIX_INT) {
            // large negative
            if (value >= Byte.MIN_VALUE) {
                output.writeByte(SINT_8);
                output.writeByte((byte) value);
            } else if (value >= Short.MIN_VALUE) {
                output.writeByte(SINT_16);
                output.writeShort((short) value);
            } else if (value >= Integer.MIN_VALUE) {
                output.writeByte(SINT_32);
                output.writeInt((int) value);
            } else {
                output.writeByte(SINT_64);
                output.writeLong(value);
            }
        } else if (value < MAX_FIX_INT) {
            // in range -64 to 127
            output.writeByte((byte) value);
        } else {
            // large positive
            if (value < 0xFF) {
                output.writeByte(UINT_8);
                output.writeByte((byte) value);
            } else if (value < 0xFFFF) {
                output.writeByte(UINT_16);
                output.writeShort((short) value);
            } else if (value < 0xFFFFFFFFL) {
                output.writeByte(UINT_32);
                output.writeInt((int) value);
            } else {
                output.writeByte(UINT_64);
                output.writeLong(value);
            }
        }
    }
721283
public synchronized void writeHeader(long timestamp) throws IOException {
		if (writer == null && headerBytes != null) {
			writer = createNewWriter(manager.startNewFile(timestamp));
			writer.write(headerBytes);
			manager.notifyOfFileAction(LogEventListener.EVENTTYPEROLL) ;
		}
	}
739288
private void writeLong(long value)
		throws IOException
	{
		if(value < 0)
		{
			out.write(TAG_NEGATIVE_LONG);
			writeLongNoTag(- value);
		}
		else
		{
			out.write(TAG_POSITIVE_LONG);
			writeLongNoTag(value);
		}
	}
645532
public static String writeLong(Long value) {
		if (value==null) return null;
		
		return Long.toString(value);			
	}