Handle "end of data" situations

@param context the encoder context
@param buffer  the buffer with the remaining encoded characters
2000
void handleEOD(EncoderContext context, StringBuilder buffer) {
    int unwritten = (buffer.length() / 3) * 2;
    int rest = buffer.length() % 3;

    int curCodewordCount = context.getCodewordCount() + unwritten;
    context.updateSymbolInfo(curCodewordCount);
    int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;

    if (rest == 2) {
      buffer.append('\0'); //Shift 1
      while (buffer.length() >= 3) {
        writeNextTriplet(context, buffer);
      }
      if (context.hasMoreCharacters()) {
        context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
      }
    } else if (available == 1 && rest == 1) {
      while (buffer.length() >= 3) {
        writeNextTriplet(context, buffer);
      }
      if (context.hasMoreCharacters()) {
        context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
      }
      // else no unlatch
      context.pos--;
    } else if (rest == 0) {
      while (buffer.length() >= 3) {
        writeNextTriplet(context, buffer);
      }
      if (available > 0 || context.hasMoreCharacters()) {
        context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
      }
    } else {
      throw new IllegalStateException("Unexpected case. Please report!");
    }
    context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION);
  }
34303
public String decodePPM(byte[] data, int context) {
    try {
      BitInputStream in = new BitInputStream(new ByteArrayInputStream(data));
      StringBuilder out = new StringBuilder();
      String contextStr = "";
      while (true) {
        TrieNode fromNode = inner.matchPredictor(getRight(contextStr, context));
        if (0 == fromNode.getNumberOfChildren()) return "";
        long seek = in.peekLongCoord(fromNode.getCursorCount());
        TrieNode toNode = fromNode.traverse(seek + fromNode.getCursorIndex());
        String newSegment = toNode.getString(fromNode);
        Interval interval = fromNode.intervalTo(toNode);
        Bits bits = interval.toBits();
        if (verbose) {
          System.out.println(String.format(
            "Using prefix \"%s\", seek to %s pos, path \"%s\" run %s -> %s, input buffer = %s",
            fromNode.getDebugString(), seek, toNode.getDebugString(fromNode), interval, bits, in.peek(24)));
        }
        in.expect(bits);
        if (toNode.isStringTerminal()) {
          if (verbose) System.out.println("Inserting null char to terminate string");
          newSegment += END_OF_STRING;
        }
        if (!newSegment.isEmpty()) {
          if (newSegment.endsWith("\u0000")) {
            out.append(newSegment.substring(0, newSegment.length() - 1));
            if (verbose) System.out.println(String.format("Null char reached"));
            break;
          }
          else {
            contextStr += newSegment;
            out.append(newSegment);
          }
        }
        else if (in.availible() == 0) {
          if (verbose) System.out.println(String.format("No More Data"));
          break;
        }
        else if (toNode.getChar() == END_OF_STRING) {
          if (verbose) System.out.println(String.format("End code"));
          break;
          //throw new RuntimeException("Cannot decode text");
        }
        else if (toNode.getChar() == FALLBACK) {
          contextStr = fromNode.getString().substring(1);
        }
        else if (toNode.getChar() == ESCAPE) {
          Bits charBits = in.read(16);
          char exotic = (char) charBits.toLong();
          out.append(new String(new char[]{exotic}));
          if (verbose) {
            System.out.println(String.format(
              "Read exotic byte %s -> %s, input buffer = %s", exotic, charBits, in.peek(24)));
          }
        }
        else {
          if (verbose) System.out.println(String.format("Cannot decode text"));
          break;
          //throw new RuntimeException("Cannot decode text");
        }
      }
      return out.toString();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
1145143
protected void encode(ByteBuffer txBuffer) {

        txBuffer.position(4); // Length int
        txBuffer.put(data);

        int length = txBuffer.position();

        txBuffer.rewind();

        txBuffer.putInt(length);

        txBuffer.position(length);
    }
582434
protected void finishSendError(Exception e) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "finishSendError(exception): " + getVC());
        }
        WsByteBuffer[] body = (WsByteBuffer[]) getVC().getStateMap().remove(EPS_KEY);
        if (null != body) {
            for (int i = 0; i < body.length && null != body[i]; i++) {
                body[i].release();
            }
        }
        this.myLink.close(getVC(), e);
    }
122544
function handleEnd(context) {
    var shape = context.shape,
        canExecute = context.canExecute,
        newBounds = context.newBounds;

    if (canExecute) {
      // ensure we have actual pixel values for new bounds
      // (important when zoom level was > 1 during move)
      newBounds = roundBounds(newBounds);

      // perform the actual resize
      modeling.resizeShape(shape, newBounds);
    }
  }
170463
public void __setBuffer(StringBuilder buffer) {
        if (null != __caller) ((TextBuilder) __caller).__setBuffer(buffer);
        else __buffer = buffer;
    }
1296983
void parseDocument(
            final char[] buffer, final int offset, final int len,
            final IMarkupHandler handler, final ParseStatus status)
            throws ParseException {


        final long parsingStartTimeNanos = System.nanoTime();

        try {

            handler.handleDocumentStart(parsingStartTimeNanos, 1, 1);

            status.offset = -1;
            status.line = 1;
            status.col = 1;
            status.inStructure = false;
            status.parsingDisabled = true;
            status.parsingDisabledLimitSequence = null;
            status.autoCloseRequired = null;
            status.autoCloseLimits = null;

            parseBuffer(buffer, offset, len, handler, status);

            // First parse done, now it's time to clean up in case we still have some text to be notified

            int lastLine = status.line;
            int lastCol = status.col;

            final int lastStart = status.offset;
            final int lastLen = (offset + len) - lastStart;

            if (lastLen > 0) {

                if (status.inStructure) {
                    throw new ParseException(
                            "Incomplete structure: \"" + new String(buffer, lastStart, lastLen) + "\"", status.line, status.col);
                }

                handler.handleText(buffer, lastStart, lastLen, status.line, status.col);

                // As we have produced an additional text event, we need to fast-forward the
                // lastLine and lastCol position to include the last text structure.
                for (int i = lastStart; i < (lastStart + lastLen); i++) {
                    final char c = buffer[i];
                    if (c == '\n') {
                        lastLine++;
                        lastCol = 1;
                    } else {
                        lastCol++;
                    }

                }

            }

            final long parsingEndTimeNanos = System.nanoTime();
            handler.handleDocumentEnd(parsingEndTimeNanos, (parsingEndTimeNanos - parsingStartTimeNanos), lastLine, lastCol);

        } catch (final ParseException e) {
            throw e;
        } catch (final Exception e) {
            throw new ParseException(e);
        }

    }
158449
private void handleEndOfStream() throws StreamIntegrityException {
    if (endOfStreamHandled) {
      return;
    }

    endOfStreamHandled = true;

    byte[] originalHMAC = trailerIn.getTrailer();
    byte[] calculateHMAC = mac.doFinal();

    if (! AES256JNCryptor.arraysEqual(originalHMAC, calculateHMAC)) {
      throw new StreamIntegrityException("MAC validation failed.");
    }
  }
932217
private void handleEnd(GuacamoleInstruction instruction) {

        // Verify all required arguments are present
        List<String> args = instruction.getArgs();
        if (args.size() < 1)
            return;

        // Terminate stream
        closeInterceptedStream(args.get(0));

    }
135743
protected void transportDataReceived(ReadableBuffer frame, boolean endOfStream) {
    if (transportError != null) {
      // We've already detected a transport error and now we're just accumulating more detail
      // for it.
      transportError = transportError.augmentDescription("DATA-----------------------------\n"
          + ReadableBuffers.readAsString(frame, errorCharset));
      frame.close();
      if (transportError.getDescription().length() > 1000 || endOfStream) {
        http2ProcessingFailed(transportError, false, transportErrorMetadata);
      }
    } else {
      if (!headersReceived) {
        http2ProcessingFailed(
            Status.INTERNAL.withDescription("headers not received before payload"),
            false,
            new Metadata());
        return;
      }
      inboundDataReceived(frame);
      if (endOfStream) {
        // This is a protocol violation as we expect to receive trailers.
        transportError =
            Status.INTERNAL.withDescription("Received unexpected EOS on DATA frame from server.");
        transportErrorMetadata = new Metadata();
        transportReportStatus(transportError, false, transportErrorMetadata);
      }
    }
  }
432775
@Override
    protected void handleTransliterate(Replaceable text,
                                       Position offsets, boolean isIncremental) {

        int maxLen = UCharacterName.INSTANCE.getMaxCharNameLength() + 1; // allow for temporary trailing space

        StringBuffer name = new StringBuffer(maxLen);

        // Get the legal character set
        UnicodeSet legal = new UnicodeSet();
        UCharacterName.INSTANCE.getCharNameCharacters(legal);

        int cursor = offsets.start;
        int limit = offsets.limit;

        // Modes:
        // 0 - looking for open delimiter
        // 1 - after open delimiter
        int mode = 0;
        int openPos = -1; // open delim candidate pos

        int c;
        while (cursor < limit) {
            c = text.char32At(cursor);

            switch (mode) {
            case 0: // looking for open delimiter
                if (c == OPEN_DELIM) { // quick check first
                    openPos = cursor;
                    int i = Utility.parsePattern(OPEN_PAT, text, cursor, limit);
                    if (i >= 0 && i < limit) {
                        mode = 1;
                        name.setLength(0);
                        cursor = i;
                        continue; // *** reprocess char32At(cursor)
                    }
                }
                break;

            case 1: // after open delimiter
                // Look for legal chars.  If \s+ is found, convert it
                // to a single space.  If closeDelimiter is found, exit
                // the loop.  If any other character is found, exit the
                // loop.  If the limit is reached, exit the loop.

                // Convert \s+ => SPACE.  This assumes there are no
                // runs of >1 space characters in names.
                if (PatternProps.isWhiteSpace(c)) {
                    // Ignore leading whitespace
                    if (name.length() > 0 &&
                        name.charAt(name.length()-1) != SPACE) {
                        name.append(SPACE);
                        // If we are too long then abort.  maxLen includes
                        // temporary trailing space, so use '>'.
                        if (name.length() > maxLen) {
                            mode = 0;
                        }
                    }
                    break;
                }

                if (c == CLOSE_DELIM) {

                    int len = name.length();

                    // Delete trailing space, if any
                    if (len > 0 &&
                        name.charAt(len-1) == SPACE) {
                        name.setLength(--len);
                    }

                    c = UCharacter.getCharFromExtendedName(name.toString());
                    if (c != -1) {
                        // Lookup succeeded

                        // assert(UTF16.getCharCount(CLOSE_DELIM) == 1);
                        cursor++; // advance over CLOSE_DELIM

                        String str = UTF16.valueOf(c);
                        text.replace(openPos, cursor, str);

                        // Adjust indices for the change in the length of
                        // the string.  Do not assume that str.length() ==
                        // 1, in case of surrogates.
                        int delta = cursor - openPos - str.length();
                        cursor -= delta;
                        limit -= delta;
                        // assert(cursor == openPos + str.length());
                    }
                    // If the lookup failed, we leave things as-is and
                    // still switch to mode 0 and continue.
                    mode = 0;
                    openPos = -1; // close off candidate
                    continue; // *** reprocess char32At(cursor)
                }

                if (legal.contains(c)) {
                    UTF16.append(name, c);
                    // If we go past the longest possible name then abort.
                    // maxLen includes temporary trailing space, so use '>='.
                    if (name.length() >= maxLen) {
                        mode = 0;
                    }
                }

                // Invalid character
                else {
                    --cursor; // Backup and reprocess this character
                    mode = 0;
                }

                break;
            }

            cursor += UTF16.getCharCount(c);
        }

        offsets.contextLimit += limit - offsets.limit;
        offsets.limit = limit;
        // In incremental mode, only advance the cursor up to the last
        // open delimiter candidate.
        offsets.start = (isIncremental && openPos >= 0) ? openPos : cursor;
    }
970371
private void processInput(boolean endOfInput) throws IOException {
        // Prepare decoderIn for reading
        decoderIn.flip();
        CoderResult coderResult;
        while (true) {
            coderResult = decoder.decode(decoderIn, decoderOut, endOfInput);
            if (coderResult.isOverflow()) {
                flushOutput();
            } else if (coderResult.isUnderflow()) {
                break;
            } else {
                // The decoder is configured to replace malformed input and unmappable characters,
                // so we should not get here.
                throw new IOException("Unexpected coder result");
            }
        }
        // Discard the bytes that have been read
        decoderIn.compact();
    }
1362560
private static final <T extends Appendable> void encodeRun(T buffer, short value, int length) {
        try {
            char valueChar = (char) value;
            if (length < 4) {
                for (int j=0; j<length; ++j) {
                    if (valueChar == ESCAPE) {
                        buffer.append(ESCAPE);
                    }
                    buffer.append(valueChar);
                }
            }
            else {
                if (length == ESCAPE) {
                    if (valueChar == ESCAPE) {
                        buffer.append(ESCAPE);
                    }
                    buffer.append(valueChar);
                    --length;
                }
                buffer.append(ESCAPE);
                buffer.append((char) length);
                buffer.append(valueChar); // Don't need to escape this value
            }
        } catch (IOException e) {
            throw new IllegalIcuArgumentException(e);
        }
    }
1283461
protected final void closeContext(GenerationContext context) {
		boolean runPostElements = false;
		GenerationContext selectedContext = null;
		synchronized (this) {
			final Iterator<GenerationContext> iterator = this.bufferedContexes.iterator();
			while (selectedContext == null && iterator.hasNext()) {
				final GenerationContext candidate = iterator.next();
				if (Objects.equal(candidate.getTypeIdentifier(), context.getTypeIdentifier())) {
					runPostElements = candidate.getParentContext() == null;
					selectedContext = candidate;
				}
			}
		}
		if (selectedContext == null) {
			throw new IllegalStateException("Not same contexts when closing"); //$NON-NLS-1$
		}
		if (runPostElements) {
			for (final Runnable handler : selectedContext.getPostFinalizationElements()) {
				handler.run();
			}
		}
		synchronized (this) {
			final Iterator<GenerationContext> iterator = this.bufferedContexes.iterator();
			while (iterator.hasNext()) {
				final GenerationContext candidate = iterator.next();
				if (selectedContext == candidate) {
					candidate.setParentContext(null);
					iterator.remove();
					return;
				}
			}
		}
	}
540005
public void endDTD() throws SAXException
  {

    if (DEBUG)
      System.out.println("TransformerHandlerImpl#endDTD");

    if (null != m_lexicalHandler)
    {
      m_lexicalHandler.endDTD();
    }
  }
274288
public void onResume(final Context context) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                checkLocaleChange(context);
                checkAfterLocaleChanging();
            }
        });
    }
887910
public final void append( StringBuilder buffer, Map<String, String> configuration, Tree<Appender> context )
    {
        // Create context if needed
        Tree<Appender> currentContext = context == null ? new Tree<Appender>( this ) : context.addLeaf( this );

        // Check recursion
        if ( currentContext.inAncestors( this ) )
        {
            // For the moment just log a warning, and stop the resolving by appending original chunk
            buffer.append( chunk );

            logger.warning( format( "Recursion detected within variable resolving:%n%s", currentContext.getRoot() ) );
        }
        // Process real appending
        else
        {
            doAppend( buffer, configuration, currentContext );
            // Dump some info on resolution if this is a root appender
            if ( currentContext.isRoot() && logger.isLoggable( FINEST ) )
            {
                logger.finest( format( "Resolving variables:%n%s", currentContext ) );
            }
        }
    }