/*
@see com.ibm.wsspi.tcpchannel.TCPWriteRequestContext#write(long, com.ibm.wsspi.tcpchannel.TCPWriteCompletedCallback, boolean, int)
770712
@Override
    public VirtualConnection write(long numBytes, TCPWriteCompletedCallback userCallback, boolean forceQueue, int timeout) {
        return write(numBytes, userCallback, forceQueue, timeout, false);
    }
65710
@Override
	public void write(byte data[], int offset, int len) throws IOException
    {
        if ((capacity - size) < len)
            flush();
        
        // Do we have enough space ?
        if (capacity >= len)
        {
            System.arraycopy(data, offset, buffer, size, len);
            size += len;
        }
        else
        {
            // Too big, write it directly ...
            out.write(data, offset, len);
        }
    }
402929
@Override
	public void write(byte[] b, int off, int len) {
		this.checkIncreaseArray(len);
		System.arraycopy(b, off, this.buffer, this.pos, len);
		this.pos += len;
	}
472805
public void write(byte []buf, int offset, int length, boolean isEnd)
    throws IOException
  {
    OutputStream os = _os;
    
    if (os != null) {
      os.write(buf, offset, length);
    }
  }
340701
@Override
  public synchronized void write(final int b) {
    BufferPool.Buffer buff = getBuffer(count, false);

    if (buff == null) {
      buff = newBuffer();
    }

    if (!buff.putByte(b)) {
      buff = newBuffer();
      if (!buff.putByte(b)) {
        throw new RuntimeException("Logic error in write(b)");
      }
    }

    count++;
  }
1150480
public static final long write(WritableByteChannel channel, ByteBuffer[] srcs, int offset, int length) throws IOException
    {
        long res = 0;
        for  (int ii=0;ii<length;ii++)
        {
            ByteBuffer bb = srcs[ii+offset];
            if (bb.hasRemaining())
            {
                res += channel.write(bb);
                if (bb.hasRemaining())
                {
                    break;
                }
            }
        }
        return res;
    }
523279
@Override
    public void write(byte[] bts, int st, int end) throws IOException {
        try {
            beforeWrite(end);
            out.write(bts, st, end);
            afterWrite(end);
        } catch (IOException e) {
            handleIOException(e);
        }
    }
868064
@Override
  public void write(byte[] b, int start, int length) throws IOException {
    currentDataSegmentBuffer.write(b, start, length);
    flushIfNeeded();
  }
688554
public void write(int b) throws IOException
	{
		//PK89810, If WCCustomProperties.FINISH_RESPONSE_ON_CLOSE is set and stream is already obtained and closed. 
		// User will not be allowed to write more data if the above case is met, outputstreamClosed will be true and default is false.
		if (!(WCCustomProperties.FINISH_RESPONSE_ON_CLOSE) || !outputstreamClosed ) //PK89810
		{
		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
			logger.logp(Level.FINE, CLASS_NAME,"write", "write --> "+b);
        }
		if (!_hasWritten && obs != null)
		{
			_hasWritten = true;
			if (obsList!=null){
				for (int i=0;i<obsList.size();i++){
					obsList.get(i).alertFirstWrite();
				}
			}
			else {
			obs.alertFirstWrite();
		}
		}
		if (limit > -1)
		{
			if (total >= limit)
			{
				throw new WriteBeyondContentLengthException();
			}
		}
		if (count == buf.length)
		{
			response.setFlushMode(false);
			flushBytes();
			response.setFlushMode(true);
		}
		buf[count++] = (byte) b;
		total++;
	}
		else
		{//PK89810 start
			if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
				logger.logp(Level.FINE, CLASS_NAME,"write", " write not allowed, outputstreamClosed value -->" + outputstreamClosed);
			
		}//PK89810 End
	}
1124483
@Override
  public void write(byte[] b, int offset, int len) throws IOException {
    long startTime = System.nanoTime();
    out.write(b, offset, len);
    statistics.incrementBytesWritten(len);
    long duration = System.nanoTime() - startTime;
    ghfs.increment(GoogleHadoopFileSystemBase.Counter.WRITE);
    ghfs.increment(GoogleHadoopFileSystemBase.Counter.WRITE_TIME, duration);
  }
994863
public void write(DataOutput out) throws IOException {
    out.writeLong(blockId);
    out.writeLong(blockGenStamp);
    super.write(out);
  }
778183
protected VirtualConnection write(long _numBytes, TCPWriteCompletedCallback userCallback,
                                      boolean forceQueue, int timeout, boolean fromQueue) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "writeAsync, numBytes=" + _numBytes + ", timeout=" + timeout
                         + ", fromQueue=" + fromQueue + ", vc=" + getVCHash());
        }
        VirtualConnection vc = null;
        try {
            long numBytes = _numBytes;

            // Handle timing out of former read request.
            if (timeout == IMMED_TIMEOUT || timeout == ABORT_TIMEOUT) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Requested to timeout former request.  Calling device side.");
                }
                getConnLink().getDeviceWriteInterface().write(numBytes, this, forceQueue, timeout);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                    Tr.exit(tc, "writeAsync: " + getVC());
                }
                return getVC();
            }

            // Look for errors in the request.
            IOException exceptionInRequest = checkForErrors(numBytes, true);
            if (exceptionInRequest != null) {
                // Found an error.
                boolean fireHere = true;
                if (forceQueue) {
                    // Error must be returned on a separate thread.
                    queuedWork.setErrorParameters(getConnLink().getVirtualConnection(),
                                                this, userCallback, exceptionInRequest);

                    EventEngine events = SSLChannelProvider.getEventService();
                    if (null == events) {
                        Exception e = new Exception("missing event admin");
                        FFDCFilter.processException(e, getClass().getName(), "172", this);
                        // fall-thru below and use callback here regardless
                    } else {
                        // fire an event to continue this queued work
                        Event event = events.createEvent(SSLEventHandler.TOPIC_QUEUED_WORK);
                        event.setProperty(SSLEventHandler.KEY_RUNNABLE, this.queuedWork);
                        events.postEvent(event);
                        fireHere = false;
                    }
                }
                if (fireHere) {
                    // Call the callback on this thread.
                    userCallback.error(getConnLink().getVirtualConnection(), this, exceptionInRequest);
                }
                // Return null indicating that the callback will handle the response.
                return null;
            }

            // Get the work on another thread if queuing is being forced.
            if (forceQueue) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Forcing write request to another thread, vc=" + getVCHash());
                }
                queuedWork.setWriteParameters(numBytes, userCallback, timeout);

                EventEngine events = SSLChannelProvider.getEventService();
                if (null == events) {
                    IOException e = new IOException("missing event admin");
                    FFDCFilter.processException(e, getClass().getName(), "471", this);
                    userCallback.error(getConnLink().getVirtualConnection(), this, e);
                } else {
                    // fire an event to continue this queued work
                    Event event = events.createEvent(SSLEventHandler.TOPIC_QUEUED_WORK);
                    event.setProperty(SSLEventHandler.KEY_RUNNABLE, this.queuedWork);
                    events.postEvent(event);
                }
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                    Tr.exit(tc, "writeAsync: null");
                }
                return null;
            }

            callback = userCallback;

            // Adjust size of numBytes if all data is requested to be written (-1).
            if (numBytes == TCPWriteRequestContext.WRITE_ALL_DATA) {
                numBytes = WsByteBufferUtils.lengthOf(getBuffers());
            }

            SSLEngineResult sslResult = null;

            // Check if a handshake is needed.
            if (SSLUtils.isHandshaking(getConnLink().getSSLEngine())) {
                // A handshake is needed. Set the write parameters.
                handshakeCallback.setWriteParameters(numBytes, timeout);
                try {
                    sslResult = doHandshake(handshakeCallback);
                } catch (IOException e) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Caught exception during SSL handshake, " + e);
                    }
                    callback.error(getConnLink().getVirtualConnection(), this, e);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                        Tr.exit(tc, "writeAsynch: null");
                    }
                    return null;
                }
                // Check to see if handshake was done synchronously.
                if (sslResult != null) {
                    // Handshake was done synchronously. Verify results.
                    if (sslResult.getHandshakeStatus() != HandshakeStatus.FINISHED) {
                        IOException e = new IOException("Unable to complete SSLhandshake");
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Unable to complete SSLhandshake, " + e);
                        }
                        callback.error(getConnLink().getVirtualConnection(), this, e);
                            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                            Tr.exit(tc, "writeAsynch: null");
                        }
                        return null;
                    }
                } else {
                    // Handshake is being handled asynchronously.
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                        Tr.exit(tc, "writeAsynch: null");
                    }
                    return null;
                }
            }

            // Code can only get here if handshake wasn't needed or was done sync with valid return code.
            // Encrypt the data and write it to the network.
            vc = encryptAndWriteAsync(numBytes, false, timeout);

            // If data is ready, but this was from a formerly queued request, call the callback.
            if (vc != null && fromQueue) {
                callback.complete(vc, this);
                vc = null;
            }
        } catch (Exception original) {
            synchronized (closeSync) {
                // if close has been called then assume this exception was due to a race condition
                // with the close logic. so no FFDC here.
                if (closeCalled) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Cannot write, the link was already closed; vc=" +this.getVCHash());
                    }
                    return null;
                } else {
                    IOException ioe;
                    if (original instanceof IOException) {
                        ioe = (IOException) original;
                    }
                    ioe = new IOException("writeAsynch failed with exception: " +original.getMessage());
                    boolean fireHere = true;
                    if (forceQueue) {
                        // Error must be returned on a separate thread.
                        queuedWork.setErrorParameters(getConnLink().getVirtualConnection(),
                                                    this, userCallback, ioe);
                        EventEngine events = SSLChannelProvider.getEventService();
                        if (null != events) {
                            // fire an event to continue this queued work
                            Event event = events.createEvent(SSLEventHandler.TOPIC_QUEUED_WORK);
                            event.setProperty(SSLEventHandler.KEY_RUNNABLE, this.queuedWork);
                            events.postEvent(event);
                            fireHere = false;
                        }
                    }
                    if (fireHere) {
                        // Call the callback on this thread.
                        userCallback.error(getConnLink().getVirtualConnection(), this, ioe);
                    }
                    return null;
                }
            }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "writeAsynch: " + vc);
        }
        return vc;
    }
1363364
@Override
  public void write(int b) throws IOException
  {
    if(!bytesBuffer.hasRemaining()) {
      processBytesBuffer(false);
    }
    bytesBuffer.put((byte)b);
  }
531665
@Override
    public void write(long offset, ByteBuffer sourceBuffer) throws IOException {
        offset += contentStart;
        sourceBuffer.position(0);

        long newFilePosition = offset + sourceBuffer.limit();
        if (newFilePosition > contentEnd) {
            logger.debug("Filesize exceeded (contendEnd: {},size: {})", contentEnd, size);
            if (AUTO_ENLARGE) {
                // if the incrementSize is not large enough
                // if (offset + sourceBuffer.limit() > contentEnd + incrementSize) {
                // incrementSize = (int) (offset + sourceBuffer.limit() - contentEnd + incrementSize);
                // }
                this.enlargeFile(newFilePosition - contentEnd);
            } else {
                throw new IOException("Filesize exceeded (" + size
                        + ") and automatic enlargement is disabled. You have to enlarge file manually.");
            }
        }

        if (offset + sourceBuffer.limit() > filledUpTo) {
            filledUpTo = offset + sourceBuffer.limit();
        }
        channel.write(sourceBuffer, offset);
        writeHeader();
    }
994829
@Override
	protected synchronized void write(long offset, byte[] b) throws IOException {
		if (byteBuffer != null) {
			byteBuffer.position((int) offset);
			byteBuffer.put(b);
		} else {
			throw new IOException("Write failed, file " + getPath() + " not mapped for I/O");
		}
	}
168141
@Override
    public int write(ByteBuffer outAppBuf, Callback callback) throws IOException {
        if (!initialHSComplete) {
            IllegalStateException ex = new IllegalStateException("The initial handshake is not complete.");
            callback.failed(ex);
            throw ex;
        }

        int ret = 0;
        if (!outAppBuf.hasRemaining()) {
            callback.succeeded();
            return ret;
        }

        final int remain = outAppBuf.remaining();
        int packetBufferSize = sslEngine.getSession().getPacketBufferSize();
        List<ByteBuffer> pocketBuffers = new ArrayList<>();
        boolean closeOutput = false;

        outer:
        while (ret < remain) {
            ByteBuffer packetBuffer = newBuffer(packetBufferSize);

            wrap:
            while (true) {
                SSLEngineResult result = wrap(outAppBuf, packetBuffer);
                ret += result.bytesConsumed();

                switch (result.getStatus()) {
                    case OK: {
                        if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                            doTasks();
                        }

                        packetBuffer.flip();
                        if (packetBuffer.hasRemaining()) {
                            pocketBuffers.add(packetBuffer);
                        }
                    }
                    break wrap;

                    case BUFFER_OVERFLOW: {
                        packetBufferSize = sslEngine.getSession().getPacketBufferSize();
                        ByteBuffer b = newBuffer(packetBuffer.position() + packetBufferSize);
                        packetBuffer.flip();
                        b.put(packetBuffer);
                        packetBuffer = b;
                    }
                    break; // retry the operation.

                    case CLOSED: {
                        log.info("Session {} SSLEngine will close", session.getSessionId());
                        packetBuffer.flip();
                        if (packetBuffer.hasRemaining()) {
                            pocketBuffers.add(packetBuffer);
                        }
                        closeOutput = true;
                    }
                    break outer;

                    default: {
                        SecureNetException ex = new SecureNetException(StringUtils.replace("Session {} SSLEngine writes data exception. status -> {}", session.getSessionId(), result.getStatus()));
                        callback.failed(ex);
                        throw ex;
                    }
                }
            }
        }

        session.write(pocketBuffers, callback);
        if (closeOutput) {
            closeOutbound();
        }
        return ret;
    }
611221
void write(ByteCodeWriter out)
    throws IOException
  {
    out.write(ConstantPool.CP_LONG);
    out.writeLong(_value);
  }