Copy the acroform for an input document. Note that you can only have one,
we make no effort to merge them.
@param reader The reader of the input file that is being copied
@throws IOException, BadPdfFormatException
483679
public void copyAcroForm(PdfReader reader) throws IOException, BadPdfFormatException {
        setFromReader(reader);
        
        PdfDictionary catalog = reader.getCatalog();
        PRIndirectReference hisRef = null;
        PdfObject o = catalog.get(PdfName.ACROFORM);
        if (o != null && o.type() == PdfObject.INDIRECT)
            hisRef = (PRIndirectReference)o;
        if (hisRef == null) return; // bugfix by John Englar
        RefKey key = new RefKey(hisRef);
        PdfIndirectReference myRef;
        IndirectReferences iRef = (IndirectReferences)indirects.get(key);
        if (iRef != null) {
            acroForm = myRef = iRef.getRef();
        }
        else {
            acroForm = myRef = body.getPdfIndirectReference();
            iRef = new IndirectReferences(myRef);
            indirects.put(key, iRef);
        }
        if (! iRef.getCopied()) {
            iRef.setCopied();
            PdfDictionary theForm = copyDictionary((PdfDictionary)PdfReader.getPdfObject(hisRef));
            addToBody(theForm, myRef);
        }
    }
218137
private static String reader2String(final Reader reader) throws IOException {

        final StringBuilder stringBuilder = new StringBuilder();

        try (BufferedReader bufferedReader = new BufferedReader(reader)) {
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append("\n"); // I know, if the original data
                                            // stream has no ending line feed,
                                            // this will add one...
            }
        }
        return stringBuilder.toString();
    }
610263
public void add(Reader reader) throws IOException
    {
        BufferedReader buffered = new BufferedReader(reader);
        String line = buffered.readLine();
        while (line != null)
        {
            String[] split = line.split(delimiter);
            if (split.length != 2)
                throw new IllegalArgumentException();
            add(split[0].trim(), MentionType.getType(split[1].trim()));
            line = buffered.readLine();
        }
        // System.out.println("Size is now " + entities.size());
    }
285491
@Override
    public void read(final Reader reader) throws ConfigurationException, IOException {
        Preconditions.checkNotNull(reader);

        final HashMap<String, Object> settings = this.mapper.readValue(reader, HASH_MAP_TYPE_REFERENCE);
        final ImmutableNode rootNode = toNode(new Builder(), settings);
        this.getSubConfigurationParentModel().mergeRoot(rootNode, null, null, null, this);
    }
1101606
public static GTRPublicData read(final Reader reader) throws IOException {
        checkNotNull(reader);
        try {
            // todo:  may want to cache some of this for performance reasons
            JAXBContext context = JAXBContext.newInstance(GTRPublicData.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            URL schemaURL = GtrReader.class.getResource("/org/nmdp/ngs/gtr/xsd/GTRPublicData.xsd");
            Schema schema = schemaFactory.newSchema(schemaURL);
            unmarshaller.setSchema(schema);
            return (GTRPublicData) unmarshaller.unmarshal(reader);
        }
        catch (JAXBException | SAXException e) {
            throw new IOException("could not unmarshal GTRPublicData", e);
        }
    }
328919
public void write(Writer out)
         throws IOException
    {
        if (reader==null)
            return;
        
        try{
            IO.copy(reader,out);
        }
        finally
        {
            reader.close();
            reader=null;
        }
    }
621326
public HalResource read(final Reader reader)
    {
        final ContentRepresentation readableRepresentation = representationFactory.readRepresentation(RepresentationFactory.HAL_JSON, reader);

        return new HalResource(objectMapper, readableRepresentation);
    }
932043
public static void copy(final InputStream inputStream, final OutputStream outputStream)
      throws IOException {
    new ByteSource() {
      @Override
      public InputStream openStream() {
        return inputStream;
      }
    }.copyTo(new ByteSink() {
      @Override
      public OutputStream openStream() {
        return outputStream;
      }
    });
  }
1140157
public static Document buildDocument(DocumentBuilder withBuilder,
                                         Reader fromReader) throws SAXException, IOException {
        return buildDocument(withBuilder, new InputSource(fromReader));
    }
1268969
public static void copy(Reader in,
                            Writer out,
                            long byteCount)
         throws IOException
    {  
        char buffer[] = new char[bufferSize];
        int len=bufferSize;
        
        if (byteCount>=0)
        {
            while (byteCount>0)
            {
                if (byteCount<bufferSize)
                    len=in.read(buffer,0,(int)byteCount);
                else
                    len=in.read(buffer,0,bufferSize);                   
                
                if (len==-1)
                    break;
                
                byteCount -= len;
                out.write(buffer,0,len);
            }
        }
        else
        {
            while (true)
            {
                len=in.read(buffer,0,bufferSize);
                if (len==-1)
                    break;
                out.write(buffer,0,len);
            }
        }
    }
428762
public static Document createDocument(InputStream input) throws IOException
    {
        Check.notNull(input);

        try
        {
            return getDocumentFactory().parse(input);
        }
        catch (final SAXException exception)
        {
            throw new IOException(exception);
        }
    }
377385
public static Config fromJSON(Reader reader) throws IOException {
        ConfigSupport support = new ConfigSupport();
        return support.fromJSON(reader, Config.class);
    }
942452
public Document createDOM(PDDocument doc) throws IOException
    {
        /* We call the original PDFTextStripper.writeText but nothing should
           be printed actually because our processing methods produce no output.
           They create the DOM structures instead */
        super.writeText(doc, new OutputStreamWriter(System.out));
        return this.doc;
    }
673942
def setup_output_document(input_doc, tmp_input_doc, metadata_info,
                                                    copy_document_catalog=True):
    """"""
    # NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters
    # seems to cause problems (writer can hang on write), so only one is used.
    # This is why the tmp_input_doc file was created earlier, to get copies of
    # the page objects which are independent of those in input_doc.  An ugly
    # hack for a nasty bug to track down.

    # NOTE: You can get the _root_object attribute (dict for the document
    # catalog) from the output document after calling cloneReaderDocumentRoot
    # or else you can just directly get it from the input_doc.trailer dict, as
    # below (which is from the code for cloneReaderDocumentRoot), but you
    # CANNOT set the full _root_object to be the _root_object attribute for the
    # actual output_doc or else only blank pages show up in acroread (whether
    # or not there is any attempt to explicitly copy the pages over).  The same
    # is true for using cloneDocumentFromReader (which just calls
    # cloneReaderDocumentRoot followed by appendPagesFromReader).  At least the
    # '/Pages' key and value in _root_object cause problems, so they are
    # skipped in the partial copy.  Probably a bug in PyPDF2.  See the original
    # code for the routines on the github pages below.
    #
    # https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/pdf.py
    # https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/generic.py
    #
    # Files still can change zoom mode on clicking outline links, but that is
    # an Adobe implementation problem, and happens even in the uncropped files:
    # https://superuser.com/questions/278302/

    output_doc = PdfFileWriter()

    def root_objects_not_indirect(input_doc, root_object):
        """This can expand some of the `IndirectObject` objects in  a root object to
        see the actual values.  Currently only used for debugging.  May mess up the
        input doc and require a temporary one."""
        if isinstance(root_object, dict):
            return {root_objects_not_indirect(input_doc, key):
                    root_objects_not_indirect(input_doc, value) for
                                                  key, value in root_object.items()}
        elif isinstance(root_object, list):
            return [root_objects_not_indirect(input_doc, item) for item in root_object]
        elif isinstance(root_object, IndirectObject):
            return input_doc.getObject(root_object)
        else:
            return root_object

    doc_cat_whitelist = args.docCatWhitelist.split()
    if "ALL" in doc_cat_whitelist:
        doc_cat_whitelist = ["ALL"]

    doc_cat_blacklist = args.docCatBlacklist.split()
    if "ALL" in doc_cat_blacklist:
        doc_cat_blacklist = ["ALL"]

    # Partially copy over document catalog data from input_doc to output_doc.
    if not copy_document_catalog or (
            not doc_cat_whitelist and doc_cat_blacklist == ["ALL"]):
        # Check this first, to completely skip the possibly problematic code getting
        # document catalog items when possible.  Does not print a skipped list, though.
        if args.verbose:
            print("\nNot copying any document catalog items to the cropped document.")
    else:
        try:
            root_object = input_doc.trailer["/Root"]

            copied_items = []
            skipped_items = []
            for key, value in root_object.items():
                # Some possible keys can be:
                #
                # /Type -- required, must have value /Catalog
                # /Pages -- required, indirect ref to page tree; skip, will change
                # /PageMode -- set to /UseNone, /UseOutlines, /UseThumbs, /Fullscreen,
                #              /UseOC, or /UseAttachments, with /UseNone default.
                # /OpenAction -- action to take when document is opened, like zooming
                # /PageLayout -- set to /SinglePage, /OneColumn, /TwoColumnLeft,
                #                /TwoColumnRight, /TwoPageLeft, /TwoPageRight
                # /Names -- a name dictionary to avoid having to use object numbers
                # /Outlines -- indirect ref to document outline, i.e., bookmarks
                # /Dests -- a dict of destinations in the PDF
                # /ViewerPreferences -- a viewer preferences dict
                # /MetaData -- XMP metadata, as opposed to other metadata
                # /PageLabels -- alternate numbering for pages, only affect PDF viewers
                if key == "/Pages":
                    skipped_items.append(key)
                    continue
                if doc_cat_whitelist != ["ALL"] and key not in doc_cat_whitelist:
                    if doc_cat_blacklist == ["ALL"] or key in doc_cat_blacklist:
                        skipped_items.append(key)
                        continue
                copied_items.append(key)
                output_doc._root_object[NameObject(key)] = value

            if args.verbose:
                print("\nCopied these items from the document catalog:\n   ", end="")
                print(*copied_items)
                print("Skipped copy of these items from the document catalog:\n   ", end="")
                print(*skipped_items)

        except (KeyboardInterrupt, EOFError):
            raise
        except: # Just catch any errors here; don't know which might be raised.
            # On exception just warn and get a new PdfFileWriter object, to be safe.
            print("\nWarning: The document catalog data could not be copied to the"
                  "\nnew, cropped document.  Try fixing the PDF document using"
                  "\n'--gsFix' if you have Ghostscript installed.", file=sys.stderr)
            output_doc = PdfFileWriter()

    #output_doc.appendPagesFromReader(input_doc) # Works, but wait and test more.
    for page in [input_doc.getPage(i) for i in range(input_doc.getNumPages())]:
        output_doc.addPage(page)

    tmp_output_doc = PdfFileWriter()
    #tmp_output_doc.appendPagesFromReader(tmp_input_doc)  # Works, but test more.
    for page in [tmp_input_doc.getPage(i) for i in range(tmp_input_doc.getNumPages())]:
        tmp_output_doc.addPage(page)

    ##
    ## Copy the metadata from input_doc to output_doc, modifying the Producer string
    ## if this program didn't already set it.  Get bool for whether this program
    ## cropped the document already.
    ##

    already_cropped_by_this_program = set_cropped_metadata(input_doc, output_doc,
                                                           metadata_info)
    return output_doc, tmp_output_doc, already_cropped_by_this_program
622800
public static void writeFile(BufferedInputStream reader,
			BufferedOutputStream writer) throws IOException {
		byte[] buff = new byte[8192];
		int numChars;
		while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
			writer.write(buff, 0, numChars);
		}
	}
707106
public static MtasConfiguration readConfiguration(InputStream reader)
      throws IOException {
    MtasConfiguration currentConfig = null;
    // parse xml
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
      XMLStreamReader streamReader = factory.createXMLStreamReader(reader);
      QName qname;
      try {
        int event = streamReader.getEventType();
        while (true) {
          switch (event) {
          case XMLStreamConstants.START_DOCUMENT:
            if (!streamReader.getCharacterEncodingScheme().equals("UTF-8")) {
              throw new IOException("XML not UTF-8 encoded");
            }
            break;
          case XMLStreamConstants.END_DOCUMENT:
          case XMLStreamConstants.SPACE:
            break;
          case XMLStreamConstants.START_ELEMENT:
            // get data
            qname = streamReader.getName();
            if (currentConfig == null) {
              if (qname.getLocalPart().equals("mtas")) {
                currentConfig = new MtasConfiguration();
              } else {
                throw new IOException("no Mtas Configuration");
              }
            } else {
              MtasConfiguration parentConfig = currentConfig;
              currentConfig = new MtasConfiguration();
              parentConfig.children.add(currentConfig);
              currentConfig.parent = parentConfig;
              currentConfig.name = qname.getLocalPart();
              for (int i = 0; i < streamReader.getAttributeCount(); i++) {
                currentConfig.attributes.put(
                    streamReader.getAttributeLocalName(i),
                    streamReader.getAttributeValue(i));
              }
            }
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (currentConfig.parent == null) {
              return currentConfig;
            } else {
              currentConfig = currentConfig.parent;
            }
            break;
          case XMLStreamConstants.CHARACTERS:
            break;
          }
          if (!streamReader.hasNext()) {
            break;
          }
          event = streamReader.next();
        }
      } finally {
        streamReader.close();
      }
    } catch (XMLStreamException e) {
      log.debug(e);
    }
    return null;
  }
1143999
public static void copy(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException {
        copy(reader, writer, false, false);
    }