This gets an input stream to the specified attachment in the zip.
13333
@Override
    public InputStream getAttachment(final Asset asset, final Attachment attachment) throws IOException, BadVersionException, RequestFailureException {
        final ZipFile repoZip = createZipFile();

        if (null == repoZip) {
            return null;
        }

        InputStream retInputStream = null;
        String attachmentId = attachment.get_id();

        try {
            if (attachmentId.contains("#")) {
                String assetId = asset.get_id();
                // new funky code to get an input stream to the license *inside* the main attachment. The start of
                // the assetId will point to the main attachment file.
                ZipEntry entry = createFromRelative(assetId);

                // If the entry wasn't found return null
                if (null == entry) {
                    return null;
                }

                // Get zip input stream to the asset inside the zip
                ZipInputStream zis = new ZipInputStream(repoZip.getInputStream(entry));

                // Get the input stream to the attachment inside the zip
                retInputStream = getInputStreamToLicenseInsideZip(zis, assetId, attachmentId);

            } else {
                // Get input stream to the attachment
                ZipEntry entry = createFromRelative(attachmentId);
                retInputStream = repoZip.getInputStream(entry);
            }
        } finally {
            // If we are throwing an exception the InputStream is never created so the logic below
            // to close the ZipFile when the InputStream is closed will never be called. So lets close
            // the ZipFile now as there is no InputStream to read from.
            if (retInputStream == null) {
                repoZip.close();
            }
        }

        // When the input stream gets closed we also need to close the ZipFile, however
        // the caller only has the input stream. So lets wrap the input stream and close
        // both the inputStream and the ZipFile when the caller calls close on the wrapped
        // input stream
        final InputStream is = retInputStream;
        InputStream wrappedIs = new InputStream() {

            /** {@inheritDoc} */
            @Override
            public int read(byte[] b) throws IOException {
                return is.read(b);
            }

            /** {@inheritDoc} */
            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                return is.read(b, off, len);
            }

            /** {@inheritDoc} */
            @Override
            public long skip(long n) throws IOException {
                return is.skip(n);
            }

            /** {@inheritDoc} */
            @Override
            public int available() throws IOException {
                return is.available();
            }

            /** {@inheritDoc} */
            @Override
            public synchronized void mark(int readlimit) {
                is.mark(readlimit);
            }

            /** {@inheritDoc} */
            @Override
            public synchronized void reset() throws IOException {
                is.reset();
            }

            /** {@inheritDoc} */
            @Override
            public boolean markSupported() {
                return is.markSupported();
            }

            /** {@inheritDoc} */
            @Override
            public int read() throws IOException {
                return is.read();
            }

            /** {@inheritDoc} */
            @Override
            public void close() throws IOException {
                // When the input stream is closed, also close the zip file
                is.close();
                repoZip.close();
            }
        };
        return wrappedIs;
    }
1359889
def FromStream(cls, stream, mime_type, total_size=None, auto_transfer=True,
                   gzip_encoded=False, **kwds):
        """"""
        if mime_type is None:
            raise exceptions.InvalidUserInputError(
                'No mime_type specified for stream')
        return cls(stream, mime_type, total_size=total_size,
                   close_stream=False, auto_transfer=auto_transfer,
                   gzip_encoded=gzip_encoded, **kwds)
1102414
def downloadArchiveAction(self, request, queryset):
        '''
        
        '''
        output = io.BytesIO()
        z = zipfile.ZipFile(output, 'w')

        for sub in queryset:
            sub.add_to_zipfile(z)

        z.close()
        # go back to start in ZIP file so that Django can deliver it
        output.seek(0)
        response = HttpResponse(
            output, content_type="application/x-zip-compressed")
        response['Content-Disposition'] = 'attachment; filename=submissions.zip'
        return response
156833
public synchronized InputStream getInputStream() throws IOException {
        if (!connected) {
            connect();
        }

        // Nothing to return
        if (responseCode == HTTP_NOT_FOUND) {
            throw new FileNotFoundException(url.toString());
        }
        int length;

        if (inputStream == null) {
            return null;
        }

        // "De-chunk" the output stream
        else if ("chunked".equalsIgnoreCase(getHeaderField("Transfer-Encoding"))) {
            if (!(inputStream instanceof ChunkedInputStream)) {
                inputStream = new ChunkedInputStream(inputStream);
            }
        }

        // Make sure we don't wait forever, if the content-length is known
        else if ((length = getHeaderFieldInt("Content-Length", -1)) >= 0) {
            if (!(inputStream instanceof FixedLengthInputStream)) {
                inputStream = new FixedLengthInputStream(inputStream, length);
            }
        }
        return inputStream;
    }
1072956
InputStream getInputStream() throws IOException {
        switch (filetype) {
            case GZ:
                LOG.debug("Decompressing .gz file");
                return new GzipCompressorInputStream(new FileInputStream(compressedFile));
            case BZ2:
                LOG.debug("Decompressing .bz2 file");
                return new BZip2CompressorInputStream(new FileInputStream(compressedFile));
        }
        return null;
    }
465110
def to_email_attachment(self, filename, filedata, **kw):
        
        maintype = "application"
        subtype = "octet-stream"

        mime_type = mimetypes.guess_type(filename)[0]
        if mime_type is not None:
            maintype, subtype = mime_type.split("/")

        attachment = MIMEBase(maintype, subtype, **kw)
        attachment.set_payload(filedata)
        encoders.encode_base64(attachment)
        attachment.add_header("Content-Disposition",
                              "attachment; filename=%s" % filename)
        return attachment
1114602
static ZipInputStream createZipInputStream(InputStream inStream, Charset charset) {
    if (charset == null)
      return new ZipInputStream(inStream);

    try {
      Constructor<ZipInputStream> constructor = ZipInputStream.class.getConstructor(new Class[] { InputStream.class, Charset.class });
      return (ZipInputStream) constructor.newInstance(new Object[] { inStream, charset });
    }
    catch (NoSuchMethodException e) {
      throw new IllegalStateException(MISSING_METHOD_PLEASE_UPGRADE, e);
    }
    catch (InstantiationException e) {
      throw new IllegalStateException(CONSTRUCTOR_MESSAGE_FOR_INPUT + e.getMessage(), e);
    }
    catch (IllegalAccessException e) {
      throw new IllegalStateException(CONSTRUCTOR_MESSAGE_FOR_INPUT + e.getMessage(), e);
    }
    catch (IllegalArgumentException e) {
      throw new IllegalStateException(CONSTRUCTOR_MESSAGE_FOR_INPUT + e.getMessage(), e);
    }
    catch (InvocationTargetException e) {
      throw new IllegalStateException(CONSTRUCTOR_MESSAGE_FOR_INPUT + e.getMessage(), e);
    }
  }
1138660
private InputStream getResourceInputStream(String path) {
		InputStream is = config.getContext().getResourceAsStream(path);
		if (is == null) {
			try {
				is = ClassLoaderResourceUtils.getResourceAsStream(path, this);
			} catch (FileNotFoundException e) {
				throw new BundlingProcessException(e);
			}
		}

		return is;
	}
980926
public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {
        return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );
    }
1115694
public static InputStream getResourceInputStreamForZip(File zip,
            String entryName) {
        return Optional.ofNullable(zip).map(JMResources::newZipFile)
                .map(zipFile -> getResourceInputStreamForZip(zipFile,
                        entryName)).orElse(null);
    }
841958
private byte[] getBytes(ZipEntry ze) throws IOException {
        try (InputStream is = super.getInputStream(ze)) {
            return IOUtils.readFully(is, (int)ze.getSize(), true);
        }
    }
459820
private static InputStream inputStreamFromFile(URL resourceUrl)
      throws IOException, URISyntaxException {
    File resourceFile = new File(resourceUrl.toURI());
    return new FileInputStream(resourceFile);
  }
5723
private void getNextFile(final InputStream is) throws IOException {
    if (is instanceof  java.util.zip.ZipInputStream) {
      ZipEntry ze = ((ZipInputStream) is).getNextEntry();
      while (ze != null && ze.isDirectory())
        ze = ((ZipInputStream) is).getNextEntry();
    }
  }
1073242
public static InputStream getFileInputStream(String filename) throws IOException {
    InputStream in = new FileInputStream(filename);
    if (filename.endsWith(".gz")) {
      in = new GZIPInputStream(in);
    } else if (filename.endsWith(".bz2")) {
      //in = new CBZip2InputStream(in);
      in = getBZip2PipedInputStream(filename);
    }
    return in;
  }
1144054
private InputStream getAttachment(URI uri) {
        HttpConnection connection = Http.GET(uri);
        couchDbClient.execute(connection);
        try {
            return connection.responseAsInputStream();
        } catch (IOException e) {
            throw new CouchDbException("Error retrieving response input stream.", e);
        }
    }
552882
def extract_file_from_zip(bytes_io, expected_file):
    """"""
    zipf = zipfile.ZipFile(bytes_io) 
    return zipf.read(expected_file)
451523
private static void addAttachments(Map<String, ? extends Attachment> attachments,
                                   Map<String, Object> outMap,
                                   boolean shouldInline,
                                   int minRevPos) {
        // Use a LinkedHashMap which has "predictable iteration order" - this means that the
        // serializer will output the _attachments entries in the same order as the multipart bodies
        // Note that we have already sorted entries by their key (see below where a TreeMap is used)
        // se we only need *this* map to have an iteration order which is in the insertion order
        LinkedHashMap<String, Object> attsMap = new LinkedHashMap<String, Object>();
        outMap.put("_attachments", attsMap);

        // first sort by attachment name - this means that the
        // entries in the _attachments dictionary are in the same
        // order as the multiparts
        attachments = new TreeMap<String, Attachment>(attachments);
        for (Map.Entry<String, ? extends Attachment> att : attachments.entrySet()) {
            // we need to cast down to SavedAttachment, which we know is what the AttachmentManager gives us
            SavedAttachment savedAtt = (SavedAttachment) att.getValue();
            HashMap<String, Object> theAtt = new HashMap<String, Object>();
            try {
                // add the attachment if it's newer than the minimum revpos
                if (savedAtt.revpos > minRevPos) {
                    if (!shouldInline) {
                        theAtt.put("follows", true);
                    } else {
                        theAtt.put("follows", false);
                        // base64 encode this attachment
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        OutputStream bos = Base64OutputStreamFactory.get(baos);
                        InputStream fis = savedAtt.getInputStream();
                        try {
                            int bufSiz = 1024;
                            byte[] buf = new byte[bufSiz];
                            int n = 0;
                            do {
                                n = fis.read(buf);
                                if (n > 0) {
                                    bos.write(buf, 0, n);
                                }
                            } while (n > 0);
                            // out of paranoia, close and flush - docs don't say what you have to
                            // do to

                            // ensure all base64 is written, but close seems to do the right
                            // thing with
                            // the apache codec implementation
                            bos.flush();
                            bos.close();
                            theAtt.put("data", new String(baos.toByteArray(), "UTF-8")); //base64 of data
                        } finally {
                            IOUtils.closeQuietly(fis);
                        }
                    }
                    theAtt.put("length", savedAtt.length);
                    theAtt.put("encoded_length", savedAtt.encodedLength);
                    theAtt.put("content_type", savedAtt.type);
                    theAtt.put("revpos", savedAtt.revpos);
                    if (savedAtt.encoding != Attachment.Encoding.Plain) {
                        theAtt.put("encoding", savedAtt.encoding.toString().toLowerCase(Locale.ENGLISH));
                    }
                } else {
                    // if the revpos of the attachment is higher than the minimum, it's a stub
                    theAtt.put("stub", true);
                }
            } catch (IOException ioe) {
                // if we can't read the file containing the attachment then skip it
                // (this should only occur if someone tampered with the attachments directory
                // or something went seriously wrong)
                logger.log(Level.WARNING,String.format("Error reading attachment %s",att),ioe);
                continue;
            }
            // now we are done, add the attachment to the map
            attsMap.put(att.getKey(), theAtt);
        }
    }