We ignore the iostream even though we get one, we're gonna
 read from a Horizon DB!
 Requires marc4j and jtds, and java_import's some classes.
343184
def require_jars!
        require 'jruby'

        # ask marc-marc4j gem to load the marc4j jars
        MARC::MARC4J.new(:jardir => settings['marc4j_reader.jar_dir'])

        # For some reason we seem to need to java_import it, and use
        # a string like this. can't just refer to it by full
        # qualified name, not sure why, but this seems to work.
        java_import "org.marc4j.converter.impl.AnselToUnicode"

        unless defined? Java::net.sourceforge.jtds.jdbc.Driver
          jtds_jar_dir = settings["jtds.jar_path"] || File.expand_path("../../vendor/jtds", File.dirname(__FILE__))

          Dir.glob("#{jtds_jar_dir}/*.jar") do |x|
            require x
          end

          # For confusing reasons, in normal Java need to
          # Class.forName("net.sourceforge.jtds.jdbc.Driver")
          # to get the jtds driver to actually be recognized by JDBC.
          #
          # In Jruby, Class.forName doesn't work, but this seems
          # to do the same thing:
          Java::net.sourceforge.jtds.jdbc.Driver
        end

        # So we can refer to these classes as just ResultSet, etc.
        java_import java.sql.ResultSet, java.sql.PreparedStatement, java.sql.Driver
    end
484300
function readableStream(stream) {
  return new Promise(function(resolve, reject) {
    var chunks = {
      data: []
    };

    function onData(chunk) {
      if (!chunks.type) {
        chunks.type = chunkTypes[typeof chunk];
      }

      chunks.data.push(chunk);
    }

    function onEnd() {
      if (chunks.type === chunkTypes.object) {
        resolve(Buffer.concat(chunks.data));
      }
      else {
        resolve(chunks.data.join(""));
      }
    }

    function onError(error) {
      reject(error);
    }

    stream
      .on("error", onError)
      .on("data", onData)
      .on("end", onEnd);
  });
}
986782
private static InputStream inputStreamFromAssets(GraphicFactory graphicFactory, String relativePathPrefix, String src) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = graphicFactory.platformSpecificSources(relativePathPrefix, src);
        } catch (IOException e) {
        }
        if (inputStream != null) {
            return inputStream;
        }
        return null;
    }
534621
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
		// Read in size, and any hidden stuff
		s.defaultReadObject();
		
		this.stringDecoder = new Utf8();
		this.in = null;
	}
1336633
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
    {
        try
        {
            in.defaultReadObject();

            // p113380 - start of change
            // Read in eye catcher.
            byte[] ec = new byte[EYECATCHER_LENGTH];

            //d164415 start
            int bytesRead = 0;
            for (int offset = 0; offset < EYECATCHER_LENGTH; offset += bytesRead)
            {
                bytesRead = in.read(ec, offset, EYECATCHER_LENGTH - offset);
                if (bytesRead == -1)
                {
                    throw new IOException("end of input stream while reading eye catcher");
                }
            }
            //d164415 end

            // Validate that the eyecatcher matches
            for (int i = 0; i < EYECATCHER_LENGTH; i++)
            {
                if (EYECATCHER[i] != ec[i])
                {
                    String eyeCatcherString = new String(ec);
                    throw new IOException("Invalid eye catcher '" + eyeCatcherString + "' in EJBMetaData input stream");
                }
            }

            // read in the rest of the header.
            in.readShort(); // platform
            in.readShort(); // version
            // p113380 - end of change

            // Read in the common data
            if (DEBUG_ON)
            {
                System.out.println("EJBMetaDataImpl.readObject entry");
            }

            ivSession = in.readBoolean();
            if (DEBUG_ON)
            {
                System.out.println("EJBMetaDataImpl.readObject: ivSession = " + ivSession);
            }

            ivStatelessSession = in.readBoolean();
            if (DEBUG_ON)
            {
                System.out.println("EJBMetaDataImpl.readObject: ivStatelessSession = " + ivStatelessSession);
            }

            ClassLoader loader = (ClassLoader) AccessController.doPrivileged( // 363037
            new PrivilegedAction() {
                public java.lang.Object run() {
                    return Thread.currentThread().getContextClassLoader();
                }
            }
                            );

            ivBeanClassName = in.readUTF();//184994
            if (DEBUG_ON)
            {
                System.out.println("EJBMetaDataImpl.readObject: ivBeanClass is " + ivBeanClassName);//184994
            }

            ivHomeClass = loader.loadClass(in.readUTF());
            if (DEBUG_ON)
            {
                System.out.println("EJBMetaDataImpl.readObject: ivHomeClass is " + ivHomeClass);
            }

            ivRemoteClass = loader.loadClass(in.readUTF());
            if (ivSession == false)
            {
                ivPKClass = loader.loadClass(in.readUTF());
                if (DEBUG_ON)
                {
                    System.out.println("EJBMetaDataImpl.readObject loading PKEY class");
                    System.out.println("EJBMetaDataImpl.readObject: ivPKClass is " + ivPKClass);
                }
            }

            ivHomeHandle = (HomeHandle) in.readObject();
            if (DEBUG_ON)
            {
                System.out.println("EJBMetaDataImpl.readObject: read HomeHandle");
            }

            EJBHome ejbHomeStub = ivHomeHandle.getEJBHome();
            if (DEBUG_ON)
            {
                System.out.println("EJBMetaDataImpl.readObject: got EJBHome, doing narrow");
            }

            ivEjbHome = (EJBHome) PortableRemoteObject.narrow(ejbHomeStub, ivHomeClass);
            if (DEBUG_ON)
            {
                System.out.println("EJBMetaDataImpl.readObject normal exit");
            }
        } catch (IOException e)
        {
            // FFDCFilter.processException(e, CLASS_NAME + ".readObject", "346", this);
            if (DEBUG_ON)
            {
                System.out.println("***ERROR**** EJBMetaDataImpl.readObject caught unexpected exception");
                e.printStackTrace();
            }
            throw e;
        } catch (ClassNotFoundException e)
        {
            // FFDCFilter.processException(e, CLASS_NAME + ".readObject", "356", this);
            if (DEBUG_ON)
            {
                System.out.println("***ERROR**** EJBMetaDataImpl.readObject caught unexpected exception");
                e.printStackTrace();
            }
            throw e;
        }
    }
977768
private ProjectFile handleByteOrderMark(InputStream stream, int length, Charset charset) throws Exception
   {
      UniversalProjectReader reader = new UniversalProjectReader();
      reader.setSkipBytes(length);
      reader.setCharset(charset);
      return reader.read(stream);
   }
972235
boolean processSelf(Collection<String> classes) throws IOException {
        options.add("--add-modules");
        options.add("java.se.ee,jdk.xml.bind"); // TODO why jdk.xml.bind?

        if (classes.isEmpty()) {
            Path modules = FileSystems.getFileSystem(URI.create("jrt:/"))
                                      .getPath("/modules");

            // names are /modules/<modulename>/pkg/.../Classname.class
            try (Stream<Path> paths = Files.walk(modules)) {
                Stream<String> files =
                    paths.filter(p -> p.getNameCount() > 2)
                         .map(p -> p.subpath(1, p.getNameCount()))
                         .map(Path::toString);
                return doModularFileNames(files);
            }
        } else {
            return doClassNames(classes);
        }
    }
5782
private void processFile(InputStream is) throws MPXJException
   {
      int line = 1;

      try
      {
         //
         // Test the header and extract the separator. If this is successful,
         // we reset the stream back as far as we can. The design of the
         // BufferedInputStream class means that we can't get back to character
         // zero, so the first record we will read will get "RMHDR" rather than
         // "ERMHDR" in the first field position.
         //
         BufferedInputStream bis = new BufferedInputStream(is);
         byte[] data = new byte[6];
         data[0] = (byte) bis.read();
         bis.mark(1024);
         bis.read(data, 1, 5);

         if (!new String(data).equals("ERMHDR"))
         {
            throw new MPXJException(MPXJException.INVALID_FILE);
         }

         bis.reset();

         InputStreamReader reader = new InputStreamReader(bis, getCharset());
         Tokenizer tk = new ReaderTokenizer(reader);
         tk.setDelimiter('\t');
         List<String> record = new ArrayList<String>();

         while (tk.getType() != Tokenizer.TT_EOF)
         {
            readRecord(tk, record);
            if (!record.isEmpty())
            {
               if (processRecord(record))
               {
                  break;
               }
            }
            ++line;
         }
      }

      catch (Exception ex)
      {
         throw new MPXJException(MPXJException.READ_ERROR + " (failed at line " + line + ")", ex);
      }
   }
1147249
private void parsePackageClasses(String name,
            List<JavaFileObject> files,
            ListBuffer<JCCompilationUnit> trees,
            List<String> excludedPackages)
            throws IOException {
        if (excludedPackages.contains(name)) {
            return;
        }

        docenv.notice("main.Loading_source_files_for_package", name);

        if (files == null) {
            Location location = docenv.fileManager.hasLocation(StandardLocation.SOURCE_PATH)
                    ? StandardLocation.SOURCE_PATH : StandardLocation.CLASS_PATH;
            ListBuffer<JavaFileObject> lb = new ListBuffer<JavaFileObject>();
            for (JavaFileObject fo: docenv.fileManager.list(
                    location, name, EnumSet.of(JavaFileObject.Kind.SOURCE), false)) {
                String binaryName = docenv.fileManager.inferBinaryName(location, fo);
                String simpleName = getSimpleName(binaryName);
                if (isValidClassName(simpleName)) {
                    lb.append(fo);
                }
            }
            files = lb.toList();
        }
        if (files.nonEmpty()) {
            for (JavaFileObject fo : files) {
                parse(fo, trees, false);
            }
        } else {
            messager.warning(Messager.NOPOS, "main.no_source_files_for_package",
                             name.replace(File.separatorChar, '.'));
        }
    }
144810
private ProjectFile readTextFile(InputStream inputStream) throws MPXJException
   {
      ProjectReader reader = new AstaTextFileReader();
      addListeners(reader);
      return reader.read(inputStream);
   }
1157156
public final void mTEXT() throws RecognitionException {
        try {
            int _type = TEXT;
            int _channel = DEFAULT_TOKEN_CHANNEL;
            // C:\\Project\\Obdalib\\obdalib-parent\\obdalib-core\\src\\main\\java\\it\\unibz\\inf\\obda\\gui\\swing\\utils\\MappingFilter.g:116:5: ( ( 'T' | 't' ) ( 'E' | 'e' ) ( 'X' | 'x' ) ( 'T' | 't' ) )
            // C:\\Project\\Obdalib\\obdalib-parent\\obdalib-core\\src\\main\\java\\it\\unibz\\inf\\obda\\gui\\swing\\utils\\MappingFilter.g:116:7: ( 'T' | 't' ) ( 'E' | 'e' ) ( 'X' | 'x' ) ( 'T' | 't' )
            {
            if ( input.LA(1)=='T'||input.LA(1)=='t' ) {
                input.consume();
            }
            else {
                MismatchedSetException mse = new MismatchedSetException(null,input);
                recover(mse);
                throw mse;
            }


            if ( input.LA(1)=='E'||input.LA(1)=='e' ) {
                input.consume();
            }
            else {
                MismatchedSetException mse = new MismatchedSetException(null,input);
                recover(mse);
                throw mse;
            }


            if ( input.LA(1)=='X'||input.LA(1)=='x' ) {
                input.consume();
            }
            else {
                MismatchedSetException mse = new MismatchedSetException(null,input);
                recover(mse);
                throw mse;
            }


            if ( input.LA(1)=='T'||input.LA(1)=='t' ) {
                input.consume();
            }
            else {
                MismatchedSetException mse = new MismatchedSetException(null,input);
                recover(mse);
                throw mse;
            }


            }

            state.type = _type;
            state.channel = _channel;
        }
        finally {
        	// do for sure before leaving
        }
    }
1175879
@SuppressWarnings("unchecked")
  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    int capacity = stream.readInt();
    initialize(capacity);
    int size = stream.readInt();
    for (int i = 0; i < size; i++) {
      addEntry((K) stream.readObject(), (V) stream.readObject());
    }
  }
270202
void read(Manifest.FastInputStream is, byte[] lbuf) throws IOException {
        String name = null, value = null;
        byte[] lastline = null;

        int len;
        while ((len = is.readLine(lbuf)) != -1) {
            boolean lineContinued = false;
            if (lbuf[--len] != '\n') {
                throw new IOException("line too long");
            }
            if (len > 0 && lbuf[len-1] == '\r') {
                --len;
            }
            if (len == 0) {
                break;
            }
            int i = 0;
            if (lbuf[0] == ' ') {
                // continuation of previous line
                if (name == null) {
                    throw new IOException("misplaced continuation line");
                }
                lineContinued = true;
                byte[] buf = new byte[lastline.length + len - 1];
                System.arraycopy(lastline, 0, buf, 0, lastline.length);
                System.arraycopy(lbuf, 1, buf, lastline.length, len - 1);
                if (is.peek() == ' ') {
                    lastline = buf;
                    continue;
                }
                value = new String(buf, 0, buf.length, "UTF8");
                lastline = null;
            } else {
                while (lbuf[i++] != ':') {
                    if (i >= len) {
                        throw new IOException("invalid header field");
                    }
                }
                if (lbuf[i++] != ' ') {
                    throw new IOException("invalid header field");
                }
                name = new String(lbuf, 0, 0, i - 2);
                if (is.peek() == ' ') {
                    lastline = new byte[len - i];
                    System.arraycopy(lbuf, i, lastline, 0, len - i);
                    continue;
                }
                value = new String(lbuf, i, len - i, "UTF8");
            }
            try {
                if ((putValue(name, value) != null) && (!lineContinued)) {
                    PlatformLogger.getLogger("java.util.jar").warning(
                                     "Duplicate name in Manifest: " + name
                                     + ".\n"
                                     + "Ensure that the manifest does not "
                                     + "have duplicate entries, and\n"
                                     + "that blank lines separate "
                                     + "individual sections in both your\n"
                                     + "manifest and in the META-INF/MANIFEST.MF "
                                     + "entry in the jar file.");
                }
            } catch (IllegalArgumentException e) {
                throw new IOException("invalid header field name: " + name);
            }
        }
    }
1114919
private void readObject(ObjectInputStream stream)
        throws IOException, ClassNotFoundException
    {
        stream.defaultReadObject();

        // set transient fields
        setOut( System.out );
        setErr( System.err );
    }
512822
public static ParagraphVectors readParagraphVectors(InputStream stream) throws IOException {
        File tmpFile = DL4JFileUtils.createTempFile("restore", "paravec");
        try {
            FileUtils.copyInputStreamToFile(stream, tmpFile);
            return readParagraphVectors(tmpFile);
        } finally {
            tmpFile.delete();
        }
    }
199544
private void readConstantPoolEntries() throws IOException {
        // Only record class dependency info if inter-class dependencies are enabled
        List<Integer> classNameCpIdxs = null;
        List<Integer> typeSignatureIdxs = null;
        if (scanSpec.enableInterClassDependencies) {
            classNameCpIdxs = new ArrayList<Integer>();
            typeSignatureIdxs = new ArrayList<Integer>();
        }

        // Read size of constant pool
        cpCount = inputStreamOrByteBuffer.readUnsignedShort();

        // Allocate storage for constant pool
        entryOffset = new int[cpCount];
        entryTag = new int[cpCount];
        indirectStringRefs = new int[cpCount];
        Arrays.fill(indirectStringRefs, 0, cpCount, -1);

        // Read constant pool entries
        for (int i = 1, skipSlot = 0; i < cpCount; i++) {
            if (skipSlot == 1) {
                // Skip a slot (keeps Scrutinizer happy -- it doesn't like i++ in case 6)
                skipSlot = 0;
                continue;
            }
            entryTag[i] = inputStreamOrByteBuffer.readUnsignedByte();
            entryOffset[i] = inputStreamOrByteBuffer.curr;
            switch (entryTag[i]) {
            case 0: // Impossible, probably buffer underflow
                throw new ClassfileFormatException("Unknown constant pool tag 0 in classfile " + relativePath
                        + " (possible buffer underflow issue). Please report this at "
                        + "https://github.com/classgraph/classgraph/issues");
            case 1: // Modified UTF8
                final int strLen = inputStreamOrByteBuffer.readUnsignedShort();
                inputStreamOrByteBuffer.skip(strLen);
                break;
            case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER
            case 4: // float
                inputStreamOrByteBuffer.skip(4);
                break;
            case 5: // long
            case 6: // double
                inputStreamOrByteBuffer.skip(8);
                skipSlot = 1; // double slot
                break;
            case 7: // Class reference (format is e.g. "java/lang/String")
                // Forward or backward indirect reference to a modified UTF8 entry
                indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort();
                if (scanSpec.enableInterClassDependencies) {
                    // If this is a class ref, and inter-class dependencies are enabled, record the dependency
                    classNameCpIdxs.add(indirectStringRefs[i]);
                }
                break;
            case 8: // String
                // Forward or backward indirect reference to a modified UTF8 entry
                indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort();
                break;
            case 9: // field ref
                // Refers to a class ref (case 7) and then a name and type (case 12)
                inputStreamOrByteBuffer.skip(4);
                break;
            case 10: // method ref
                // Refers to a class ref (case 7) and then a name and type (case 12)
                inputStreamOrByteBuffer.skip(4);
                break;
            case 11: // interface method ref
                // Refers to a class ref (case 7) and then a name and type (case 12)
                inputStreamOrByteBuffer.skip(4);
                break;
            case 12: // name and type
                final int nameRef = inputStreamOrByteBuffer.readUnsignedShort();
                final int typeRef = inputStreamOrByteBuffer.readUnsignedShort();
                if (scanSpec.enableInterClassDependencies) {
                    typeSignatureIdxs.add(typeRef);
                }
                indirectStringRefs[i] = (nameRef << 16) | typeRef;
                break;
            case 15: // method handle
                inputStreamOrByteBuffer.skip(3);
                break;
            case 16: // method type
                inputStreamOrByteBuffer.skip(2);
                break;
            case 18: // invoke dynamic
                inputStreamOrByteBuffer.skip(4);
                break;
            case 19: // module (for module-info.class in JDK9+)
                // see https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4
                indirectStringRefs[i] = inputStreamOrByteBuffer.readUnsignedShort();
                break;
            case 20: // package (for module-info.class in JDK9+)
                // see https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4
                inputStreamOrByteBuffer.skip(2);
                break;
            default:
                throw new ClassfileFormatException("Unknown constant pool tag " + entryTag[i]
                        + " (element size unknown, cannot continue reading class). Please report this at "
                        + "https://github.com/classgraph/classgraph/issues");
            }
        }

        // Find classes referenced in the constant pool (note that there are some class refs that will not be
        // found this way, e.g. enum classes and class refs in annotation parameter values, since they are
        // referenced as strings (tag 1) rather than classes (tag 7) or type signatures (part of tag 12)).
        if (scanSpec.enableInterClassDependencies) {
            refdClassNames = new HashSet<>();
            // Get class names from direct class references in constant pool
            for (final int cpIdx : classNameCpIdxs) {
                final String refdClassName = getConstantPoolString(cpIdx, /* replaceSlashWithDot = */ true,
                        /* stripLSemicolon = */ false);
                if (refdClassName != null) {
                    if (refdClassName.startsWith("[")) {
                        // Parse array type signature, e.g. "[Ljava.lang.String;" -- uses '.' rather than '/'
                        try {
                            final TypeSignature typeSig = TypeSignature.parse(refdClassName.replace('.', '/'),
                                    /* definingClass = */ null);
                            typeSig.findReferencedClassNames(refdClassNames);
                        } catch (final ParseException e) {
                            // Should not happen
                            throw new ClassfileFormatException("Could not parse class name: " + refdClassName, e);
                        }
                    } else {
                        refdClassNames.add(refdClassName);
                    }
                }
            }
            // Get class names from type signatures in "name and type" entries in constant pool
            for (final int cpIdx : typeSignatureIdxs) {
                final String typeSigStr = getConstantPoolString(cpIdx);
                if (typeSigStr != null) {
                    try {
                        if (typeSigStr.indexOf('(') >= 0 || "<init>".equals(typeSigStr)) {
                            // Parse the type signature
                            final MethodTypeSignature typeSig = MethodTypeSignature.parse(typeSigStr,
                                    /* definingClassName = */ null);
                            // Extract class names from type signature
                            typeSig.findReferencedClassNames(refdClassNames);
                        } else {
                            // Parse the type signature
                            final TypeSignature typeSig = TypeSignature.parse(typeSigStr,
                                    /* definingClassName = */ null);
                            // Extract class names from type signature
                            typeSig.findReferencedClassNames(refdClassNames);
                        }
                    } catch (final ParseException e) {
                        throw new ClassfileFormatException("Could not parse type signature: " + typeSigStr, e);
                    }
                }
            }
        }
    }
805404
public void readExternal(ObjectInput in)
                    throws IOException, ClassNotFoundException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "readExternal");

        try {
            // read magic
            short magic = in.readShort();
            short majorVersion = in.readShort();
            short minorVersion = in.readShort();

            if (!(magic == EXTERNAL_MAGIC)) {

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc,
                             "Magic Number absent, trying default Java deserialization");
                throw new IOException("Bean ID externalized stream format error");

            } else if (!(majorVersion == MAJOR_VERSION) ||
                       !(minorVersion == MINOR_VERSION)) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc,
                             "BeanID Version mismatch", new Object[] { new Short(majorVersion),
                                                                      new Short(minorVersion) });
                throw new IOException("BeanID version mismatch");
            }

            // read the interface type (HOME or REMOTE)
            byte ifType = in.readByte();
            if (ifType == IF_HOME) {
                _isHome = true;
            } else {
                _isHome = false;
            }

            //89554
            // read the bean name
            byte[] j2eeNameBytes = readExternalJ2EEName(in);

            // read the serialized primary key
            pkey = readExternalPKey(in, j2eeNameBytes);

            // TAKE CARE! We don't have a container reference so can't
            // restore transient fields.
            // This is ok as long
            // as rest of container restores BeanIds using the deserialise
            // method. Since readExternal
            // is a new addition
            // this can be no different to the behaviour that would have been
            // observed when using
            // the default serialization.

        } finally {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                Tr.exit(tc, "readExternal");
        }
    }