Reads an NBT {@link Tag} from the stream.

@param depth The depth of this tag.
@return The tag that was read.
@throws java.io.IOException if an I/O error occurs.
778490
private Tag readTag(int depth) throws IOException {
        int typeId = is.readByte() & 0xFF;
        TagType type = TagType.getById(typeId);

        String name;
        if (type != TagType.TAG_END) {
            int nameLength = is.readShort() & 0xFFFF;
            byte[] nameBytes = new byte[nameLength];
            is.readFully(nameBytes);
            name = new String(nameBytes, NBTConstants.CHARSET.name());
        } else {
            name = "";
        }

        return readTagPayload(type, name, depth);
    }
945036
public int read() throws KNXMLException
	{
		while (canRead()) {
			// init line counter on first read
			if (line == 0)
				line = 1;

			read('<');
			String str = read('>');
			// if no comment and no closing tag
			if (str.length() == 0 || skipComment(str) || skipInstruction(str))
				continue;
			final StringBuffer buf = new StringBuffer();
			if (readCDATASection(str, buf)) {
				elem = new DefaultElement((String) openElems.peek());
				elem.setCharacterData(buf.toString());
				pos = CHAR_DATA;
				return pos;
			}
			str = str.trim();
			// extract element name
			final String name = splitOnSpace(str);
			if (name.charAt(0) == '/') {
				if (!name.substring(1).equals(openElems.peek()))
					throw new KNXMLException("element end tag does not match start tag",
						name.substring(1), line);
				elem = new DefaultElement((String) openElems.pop());
				pos = END_TAG;
				return pos;
			}
			elem = new DefaultElement(name);
			extractAttributes(str.substring(name.length()));
			if (!elem.isEmptyElementTag())
				openElems.push(name);
			pos = START_TAG;
			return pos;
		}
		if (!openElems.empty())
			throw new KNXMLException("end of XML input with elements left open");
		pos = END_DOC;
		return pos;
	}
86201
private void readTag() throws XMLException, IOException {
		try {
			char c;
			if ((c = stream.read()) == '!') {
				readTagExclamation();
			} else if (c == '?') {
				readProcessingInstruction();
			} else if (c == '/') {
				readEndTag();
			} else if (isNameStartChar(c)) {
				readStartTag(c);
			} else {
				throw new XMLException(getPosition(), "Unexpected character", Character.valueOf(c));
			}
		} catch (EOFException e) {
			throw new XMLException(getPosition(), new LocalizableString("lc.xml.error", "Unexpected end"),
					new LocalizableString("lc.xml.error", "in XML document"));
		}
	}
1131593
private int[] readDimension(ByteBuffer buf ) throws IOException
    {
        
        ISMatTag tag = new ISMatTag(buf);
        int[] dims = tag.readToIntArray();
        return dims;
        
    }
375771
public boolean readBoolean()
        throws IOException
    {
        int tag = is.read();

        switch (tag) {
            case 'T':
                return true;
            case 'F':
                return false;
            default:
                throw expect("boolean", tag);
        }
    }
674432
def read_tag
      tag = @stream.decode_tag
      if tag
        # When we shift from group 0002 to another group we need to update our endian/explicitness variables:
        if tag.group != META_GROUP and @switched == false
          switch_syntax_on_read
          # We may need to read our tag again if endian has switched (in which case it has been misread):
          if @switched_endian
            @stream.skip(-4)
            tag = @stream.decode_tag
          end
        end
      end
      return tag
    end
294761
public int readBytes(byte[] buffer, int offset, int length)
        throws IOException
    {
        int readLength = 0;

        if (_chunkLength == END_OF_DATA) {
            _chunkLength = 0;
            return -1;
        }
        else if (_chunkLength == 0) {
            int tag = read();

            switch (tag) {
                case 'N':
                    return -1;

                case 'B':
                case 'b':
                    _isLastChunk = tag == 'B';
                    _chunkLength = (read() << 8) + read();
                    break;

                default:
                    throw new IOException("expected 'B' at " + (char) tag);
            }
        }

        while (length > 0) {
            if (_chunkLength > 0) {
                buffer[offset++] = (byte) read();
                _chunkLength--;
                length--;
                readLength++;
            }
            else if (_isLastChunk) {
                if (readLength == 0)
                    return -1;
                else {
                    _chunkLength = END_OF_DATA;
                    return readLength;
                }
            }
            else {
                int tag = read();

                switch (tag) {
                    case 'B':
                    case 'b':
                        _isLastChunk = tag == 'B';
                        _chunkLength = (read() << 8) + read();
                        break;

                    default:
                        throw new IOException("expected 'B' at " + (char) tag);
                }
            }
        }

        if (readLength == 0)
            return -1;
        else if (_chunkLength > 0 || !_isLastChunk)
            return readLength;
        else {
            _chunkLength = END_OF_DATA;
            return readLength;
        }
    }
415745
@Override
	public int nextTag() throws KriptonRuntimeException, IOException {
		next();
		if (type == TEXT && isWhitespace) {
			next();
		}

		if (type != END_TAG && type != START_TAG) {
			throw new KriptonRuntimeException("unexpected type", true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), null);
		}

		return type;
	}
1235767
public ScenarioNode<?> build(final Scenario scenario, final Set<String> inheritedTags, int depth) {

        if (parameters.isRunnable(scenario)) {

            return buildRunnableScenarioNode(scenario, inheritedTags, depth);

        } else {

            log.debug("scenario not runnable: " + scenario.toString());
            return null;
        }
    }
142196
public Tag getTag(Factory f, Position start, Position end) throws TagLibException {
	if (StringUtil.isEmpty(tttCD)) return new TagOther(f, start, end);
	try {
	    return _getTag(f, start, end);
	}
	catch (ClassException e) {
	    throw new TagLibException(e.getMessage());
	}
	catch (NoSuchMethodException e) {
	    throw new TagLibException(e.getMessage());
	}
	catch (Throwable e) {
	    ExceptionUtil.rethrowIfNecessary(e);
	    throw new TagLibException(e);
	}
    }
577631
@Override
    public ITag readTag() {
        ITag tag = null;
        if (log.isTraceEnabled()) {
            log.trace("Read tag - prevFrameSize {} audio: {} video: {}", new Object[] { prevFrameSize, audioCount, videoCount });
        }
        // ensure there are frames before proceeding
        if (!frames.isEmpty()) {
            try {
                lock.acquire();
                //log.debug("Read tag");
                //empty-out the pre-streaming tags first
                if (!firstTags.isEmpty()) {
                    //log.debug("Returning pre-tag");
                    // Return first tags before media data
                    return firstTags.removeFirst();
                }
                //get the current frame
                MP4Frame frame = frames.get(currentFrame);
                if (frame != null) {
                    log.debug("Playback #{} {}", currentFrame, frame);
                    int sampleSize = frame.getSize();
                    int time = (int) Math.round(frame.getTime() * 1000.0);
                    //log.debug("Read tag - dst: {} base: {} time: {}", new Object[]{frameTs, baseTs, time});
                    long samplePos = frame.getOffset();
                    //log.debug("Read tag - samplePos {}", samplePos);
                    //determine frame type and packet body padding
                    byte type = frame.getType();
                    //assume video type
                    int pad = 5;
                    if (type == TYPE_AUDIO) {
                        pad = 2;
                    }
                    //create a byte buffer of the size of the sample
                    ByteBuffer data = ByteBuffer.allocate(sampleSize + pad);
                    try {
                        //prefix is different for keyframes
                        if (type == TYPE_VIDEO) {
                            if (frame.isKeyFrame()) {
                                //log.debug("Writing keyframe prefix");
                                data.put(PREFIX_VIDEO_KEYFRAME);
                            } else {
                                //log.debug("Writing interframe prefix");
                                data.put(PREFIX_VIDEO_FRAME);
                            }
                            // match the sample with its ctts / mdhd adjustment time
                            int timeOffset = prevVideoTS != -1 ? time - prevVideoTS : 0;
                            data.put((byte) ((timeOffset >>> 16) & 0xff));
                            data.put((byte) ((timeOffset >>> 8) & 0xff));
                            data.put((byte) (timeOffset & 0xff));
                            if (log.isTraceEnabled()) {
                                byte[] prefix = new byte[5];
                                int p = data.position();
                                data.position(0);
                                data.get(prefix);
                                data.position(p);
                                log.trace("{}", prefix);
                            }
                            // track video frame count
                            videoCount++;
                            prevVideoTS = time;
                        } else {
                            //log.debug("Writing audio prefix");
                            data.put(PREFIX_AUDIO_FRAME);
                            // track audio frame count
                            audioCount++;
                        }
                        // do we need to add the mdat offset to the sample position?
                        dataSource.position(samplePos);
                        // read from the channel
                        dataSource.read(data);
                    } catch (IOException e) {
                        log.error("Error on channel position / read", e);
                    }
                    // chunk the data
                    IoBuffer payload = IoBuffer.wrap(data.array());
                    // create the tag
                    tag = new Tag(type, time, payload.limit(), payload, prevFrameSize);
                    //log.debug("Read tag - type: {} body size: {}", (type == TYPE_AUDIO ? "Audio" : "Video"), tag.getBodySize());
                    // increment the frame number
                    currentFrame++;
                    // set the frame / tag size
                    prevFrameSize = tag.getBodySize();
                }
            } catch (InterruptedException e) {
                log.warn("Exception acquiring lock", e);
            } finally {
                lock.release();
            }
        } else {
            log.warn("No frames are available for the requested item");
        }
        //log.debug("Tag: {}", tag);
        return tag;
    }
184441
public byte[] read_integer_byte_array() throws OtpErlangDecodeException {
        int tag;
        byte[] nb;

        tag = read1skip_version();

        switch (tag) {
        case OtpExternal.smallIntTag:
            nb = new byte[2];
            nb[0] = 0;
            nb[1] = (byte) read1();
            break;

        case OtpExternal.intTag:
            nb = new byte[4];
            if (this.readN(nb) != 4) { // Big endian
                throw new OtpErlangDecodeException(
                        "Cannot read from intput stream");
            }
            break;

        case OtpExternal.smallBigTag:
        case OtpExternal.largeBigTag:
            int arity;
            int sign;
            if (tag == OtpExternal.smallBigTag) {
                arity = read1();
                sign = read1();
            } else {
                arity = read4BE();
                sign = read1();
                if (arity + 1 < 0) {
                    throw new OtpErlangDecodeException(
                            "Value of largeBig does not fit in BigInteger, arity "
                                    + arity + " sign " + sign);
                }
            }
            nb = new byte[arity + 1];
            // Value is read as little endian. The big end is augumented
            // with one zero byte to make the value 2's complement positive.
            if (this.readN(nb, 0, arity) != arity) {
                throw new OtpErlangDecodeException(
                        "Cannot read from intput stream");
            }
            // Reverse the array to make it big endian.
            for (int i = 0, j = nb.length; i < j--; i++) {
                // Swap [i] with [j]
                final byte b = nb[i];
                nb[i] = nb[j];
                nb[j] = b;
            }
            if (sign != 0) {
                // 2's complement negate the big endian value in the array
                int c = 1; // Carry
                for (int j = nb.length; j-- > 0;) {
                    c = (~nb[j] & 0xFF) + c;
                    nb[j] = (byte) c;
                    c >>= 8;
                }
            }
            break;

        default:
            throw new OtpErlangDecodeException("Not valid integer tag: " + tag);
        }

        return nb;
    }
763141
private ITag readTagHeader() throws UnsupportedDataTypeException {
        // previous tag size (4 bytes) + flv tag header size (11 bytes)
        fillBuffer(15);
        // previous tag's size
        int previousTagSize = in.getInt();
        // start of the flv tag
        byte dataType = in.get();
        if (log.isTraceEnabled()) {
            log.trace("Bits: {}", Integer.toBinaryString(dataType));
        }
        dataType = (byte) (dataType & 31);
        byte filter = (byte) ((dataType & 63) >> 5);
        byte reserved = (byte) ((dataType & 127) >> 6);
        log.debug("Reserved: {}, Filter: {}, Datatype: {}", reserved, filter, dataType);
        switch (dataType) {
            case 8: // audio
                log.debug("Found audio");
                break;
            case 9: // video
                log.debug("Found video");
                break;
            case 15: // special fms undocumented type?
            case 18: // meta / script data
                log.debug("Found meta/script data");
                break;
            default:
                log.debug("Invalid data type detected ({}), reading ahead\n current position: {} limit: {}", dataType, in.position(), in.limit());
                throw new UnsupportedDataTypeException("Invalid data type detected (" + dataType + ")");
        }
        int bodySize = IOUtils.readUnsignedMediumInt(in);
        int timestamp = IOUtils.readExtendedMediumInt(in);
        int streamId = IOUtils.readUnsignedMediumInt(in);
        if (log.isDebugEnabled()) {
            log.debug("Data type: {} timestamp: {} stream id: {} body size: {} previous tag size: {}", new Object[] { dataType, timestamp, streamId, bodySize, previousTagSize });
        }
        return new Tag(dataType, timestamp, bodySize, null, previousTagSize);
    }
110684
public byte[] readBytes()
        throws IOException
    {
        int tag = is.read();

        if (tag == 'N')
            return null;

        if (tag != 'B')
            throw expect("bytes", tag);

        int b16 = is.read();
        int b8 = is.read();

        int len = (b16 << 8) + b8;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        for (int i = 0; i < len; i++)
            bos.write(is.read());

        return bos.toByteArray();
    }
13816
long readTagAndSet(long bucketIndex, int posInBucket, long newTag) {
		long tagStartIdx = getTagOffset(bucketIndex, posInBucket);
		long tag = 0;
		long tagEndIdx = tagStartIdx + bitsPerTag;
		int tagPos = 0;
		for (long i = tagStartIdx; i < tagEndIdx; i++) {
			if ((newTag & (1L << tagPos)) != 0) {
				if (memBlock.getAndSet(i)) {
					tag |= 1 << tagPos;
				}
			} else {
				if (memBlock.getAndClear(i)) {
					tag |= 1 << tagPos;
				}
			}
			tagPos++;
		}
		return tag;
	}
536389
@Override
  public int read(byte[] b, int start, int length) throws IOException {
    if (!readMetaDataIfNeeded()) {
      return -1;
    }
    int toRead = (int)Math.min(length, getCompleteBlockSize() - rawBlockOffset);
    int read = in.read(b, start, toRead);
    if (read >= 0) {
      moveForward(read);
    } else {
      eofReached = true;
    }
    return read;
  }
534518
public XMLSerializer startTag(String namespace, String name) throws IOException {
		if (startTagIncomplete) {
			closeStartTag();
		}
		seenBracket = seenBracketBracket = false;
		++depth;
		if (doIndent && depth > 0 && seenTag) {
			writeIndent();
		}
		seenTag = true;
		setPrefixCalled = false;
		startTagIncomplete = true;
		if ((depth + 1) >= elName.length) {
			ensureElementsCapacity();
		}
		//// assert namespace != null;

		if (checkNamesInterned && namesInterned)
			checkInterning(namespace);
		elNamespace[depth] = (namesInterned || namespace == null) ? namespace : namespace.intern();
		// assert name != null;
		// elName[ depth ] = name;
		if (checkNamesInterned && namesInterned)
			checkInterning(name);
		elName[depth] = (namesInterned || name == null) ? name : name.intern();
		if (out == null) {
			throw new IllegalStateException("setOutput() must called set before serialization can start");
		}
		out.write('<');
		if (namespace != null) {
			if (namespace.length() > 0) {
				// ALEK: in future make this algo a feature on serializer
				String prefix = null;
				if (depth > 0 && (namespaceEnd - elNamespaceCount[depth - 1]) == 1) {
					// if only one prefix was declared un-declare it if the
					// prefix is already declared on parent el with the same URI
					String uri = namespaceUri[namespaceEnd - 1];
					if (uri == namespace || uri.equals(namespace)) {
						String elPfx = namespacePrefix[namespaceEnd - 1];
						// 2 == to skip predefined namesapces (xml and xmlns
						// ...)
						for (int pos = elNamespaceCount[depth - 1] - 1; pos >= 2; --pos) {
							String pf = namespacePrefix[pos];
							if (pf == elPfx || pf.equals(elPfx)) {
								String n = namespaceUri[pos];
								if (n == uri || n.equals(uri)) {
									--namespaceEnd; // un-declare namespace:
													// this is kludge!
									prefix = elPfx;
								}
								break;
							}
						}
					}
				}
				if (prefix == null) {
					prefix = lookupOrDeclarePrefix(namespace);
				}
				// assert prefix != null;
				// make sure that default ("") namespace to not print ":"
				if (prefix.length() > 0) {
					elPrefix[depth] = prefix;
					out.write(prefix);
					out.write(':');
				} else {
					elPrefix[depth] = "";
				}
			} else {
				// make sure that default namespace can be declared
				for (int i = namespaceEnd - 1; i >= 0; --i) {
					if ("".equals(namespacePrefix[i])) {
						final String uri = namespaceUri[i];
						if (uri == null) {
							// declare default namespace
							setPrefix("", "");
						} else if (uri.length() > 0) {
							throw new IllegalStateException("start tag can not be written in empty default namespace " + "as default namespace is currently bound to '" + uri + "'" + getLocation());
						}
						break;
					}
				}
				elPrefix[depth] = "";
			}
		} else {
			elPrefix[depth] = "";
		}
		out.write(name);
		return this;
	}