Java Examples for javax.annotation.WillNotClose

The following java examples will help you to understand the usage of javax.annotation.WillNotClose. These source code samples are taken from different open source projects.

Example 1
Project: hideyoshi-master  File: Downloader.java View source code
protected final void copyToLocal(File to, String fileName, @WillNotClose InputStream in, final long fileSize) throws FileNotFoundException, IOException {
    @Cleanup BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(to));
    BufferedInputStream buffer = new BufferedInputStream(in);
    byte data[] = new byte[BUFFER_SIZE];
    int count, percentNew = 0, percentOld = 0;
    long totalDataRead = 0;
    while ((count = buffer.read(data, 0, BUFFER_SIZE)) >= 0) {
        totalDataRead += count;
        out.write(data, 0, count);
        percentNew = (int) ((totalDataRead * 100) / fileSize);
        if (percentNew >= percentOld + 5) {
            log.info("{} {}% Done", fileName, percentNew);
            percentOld = percentNew;
        }
    }
    out.flush();
    log.info("{} Download Complete!", fileName);
}
Example 2
Project: as2-lib-master  File: AS2HttpResponseHandlerSocket.java View source code
public void sendHttpResponse(@Nonnegative final int nHttpResponseCode, @Nonnull final InternetHeaders aHeaders, @Nonnull @WillNotClose final IWriteToStream aData) throws IOException {
    ValueEnforcer.isGT0(nHttpResponseCode, "HttpResponseCode");
    ValueEnforcer.notNull(aHeaders, "Headers");
    ValueEnforcer.notNull(aData, "Data");
    try (final OutputStream aOS = createOutputStream()) {
        // Send HTTP version and response code
        final String sHttpStatusLine = getHTTPVersion().getName() + " " + Integer.toString(nHttpResponseCode) + " " + HTTPHelper.getHTTPResponseMessage(nHttpResponseCode) + HTTPHelper.EOL;
        aOS.write(sHttpStatusLine.getBytes(StandardCharsets.ISO_8859_1));
        // Add response headers
        final Enumeration<?> aHeaderLines = aHeaders.getAllHeaderLines();
        while (aHeaderLines.hasMoreElements()) {
            final String sHeader = (String) aHeaderLines.nextElement() + HTTPHelper.EOL;
            aOS.write(sHeader.getBytes(StandardCharsets.ISO_8859_1));
        }
        // Empty line as separator
        aOS.write(HTTPHelper.EOL.getBytes(StandardCharsets.ISO_8859_1));
        // Write body
        aData.writeTo(aOS);
        // Done
        aOS.flush();
    }
}
Example 3
Project: plexus-archiver-master  File: Streams.java View source code
public static void copyFullyDontCloseOutput(@WillClose InputStream zIn, @WillNotClose OutputStream out, String gzip) throws ArchiverException {
    // There must be 1 million libs out there that do this
    try {
        byte[] buffer = cacheBuffer();
        int count = 0;
        do {
            try {
                out.write(buffer, 0, count);
            } catch (IOException e) {
                throw new ArchiverException("Problem writing to output in " + gzip + " operation " + e.getMessage());
            }
            count = zIn.read(buffer, 0, buffer.length);
        } while (count != -1);
    } catch (IOException e) {
        throw new ArchiverException("Problem reading from source file in " + gzip + " operation " + e.getMessage());
    } finally {
        IOUtil.close(zIn);
    }
}
Example 4
Project: ph-css-master  File: CSSTokenizer.java View source code
@Nonnull
private Charset _determineCharset(@Nonnull @WillNotClose final CSSInputStream aIS) throws IOException, CSSTokenizeException {
    // Determine charset
    // https://www.w3.org/TR/css-syntax-3/#input-byte-stream
    final int nMaxHeader = Math.min(1024, aIS.available());
    if (nMaxHeader > 11) {
        final byte[] aBuffer = new byte[nMaxHeader];
        aIS.read(aBuffer);
        aIS.unread(aBuffer);
        final String sPrefix = new String(aBuffer, 0, CHARSET.length(), StandardCharsets.US_ASCII);
        if (m_bStrictMode ? CHARSET.equals(sPrefix) : CHARSET.equalsIgnoreCase(sPrefix)) {
            int nEnd = CHARSET.length();
            while (nEnd < nMaxHeader && aBuffer[nEnd] != '"') nEnd++;
            if (nEnd == nMaxHeader)
                throw new CSSTokenizeException("Unexpected end of @charset declaration");
            String sCharset = new String(aBuffer, CHARSET.length(), nEnd - CHARSET.length(), StandardCharsets.US_ASCII);
            if ("utf-16be".equalsIgnoreCase(sCharset) || "utf-16le".equalsIgnoreCase(sCharset))
                sCharset = "utf-8";
            final Charset aCharset = CharsetManager.getCharsetFromName(sCharset);
            if (aCharset == null)
                throw new CSSTokenizeException("Unsupported charset '" + sCharset + "' provided!");
            return aCharset;
        }
    }
    return m_aFallbackEncoding;
}
Example 5
Project: nifty-gui-master  File: TGAImageLoader.java View source code
// Internal implementations
// TODO Refactor.
@SuppressWarnings("ConstantConditions")
@Nonnull
private ByteBuffer loadImage(@Nonnull @WillNotClose final InputStream imageStream, final boolean shouldFlipVertically, final boolean shouldForceAlpha, @Nullable final int[] transparency) throws IOException {
    this.shouldFlipVertically = shouldFlipVertically;
    this.shouldForceAlpha = shouldForceAlpha;
    if (transparency != null) {
        this.shouldForceAlpha = true;
    }
    byte red;
    byte green;
    byte blue;
    byte alpha;
    BufferedInputStream bis = new BufferedInputStream(imageStream, 100000);
    DataInputStream dis = new DataInputStream(bis);
    // Read in the Header
    short idLength = (short) dis.read();
    dis.skipBytes(11);
    imageWidth = flipEndian(dis.readShort());
    imageHeight = flipEndian(dis.readShort());
    imageBitDepth = (short) dis.read();
    if (imageBitDepth == 32) {
        this.shouldForceAlpha = false;
    }
    textureWidth = get2Fold(imageWidth);
    textureHeight = get2Fold(imageHeight);
    short imageDescriptor = (short) dis.read();
    if ((imageDescriptor & 0x0020) == 0) {
        this.shouldFlipVertically = !this.shouldFlipVertically;
    }
    // Skip image ID
    if (idLength > 0) {
        long skipped = 0;
        while (skipped < idLength) {
            skipped += bis.skip(idLength);
        }
    }
    byte[] rawData;
    if ((imageBitDepth == 32) || (this.shouldForceAlpha)) {
        imageBitDepth = 32;
        rawData = new byte[textureWidth * textureHeight * 4];
    } else if (imageBitDepth == 24) {
        rawData = new byte[textureWidth * textureHeight * 3];
    } else {
        throw new RuntimeException("Only 24 and 32 bit TGAs are supported");
    }
    if (imageBitDepth == 24) {
        if (this.shouldFlipVertically) {
            for (int i = imageHeight - 1; i >= 0; i--) {
                for (int j = 0; j < imageWidth; j++) {
                    blue = dis.readByte();
                    green = dis.readByte();
                    red = dis.readByte();
                    int ofs = ((j + (i * textureWidth)) * 3);
                    rawData[ofs] = red;
                    rawData[ofs + 1] = green;
                    rawData[ofs + 2] = blue;
                }
            }
        } else {
            for (int i = 0; i < imageHeight; i++) {
                for (int j = 0; j < imageWidth; j++) {
                    blue = dis.readByte();
                    green = dis.readByte();
                    red = dis.readByte();
                    int ofs = ((j + (i * textureWidth)) * 3);
                    rawData[ofs] = red;
                    rawData[ofs + 1] = green;
                    rawData[ofs + 2] = blue;
                }
            }
        }
    } else if (imageBitDepth == 32) {
        if (this.shouldFlipVertically) {
            for (int i = imageHeight - 1; i >= 0; i--) {
                for (int j = 0; j < imageWidth; j++) {
                    blue = dis.readByte();
                    green = dis.readByte();
                    red = dis.readByte();
                    if (this.shouldForceAlpha) {
                        alpha = (byte) 255;
                    } else {
                        alpha = dis.readByte();
                    }
                    int ofs = ((j + (i * textureWidth)) * 4);
                    rawData[ofs] = red;
                    rawData[ofs + 1] = green;
                    rawData[ofs + 2] = blue;
                    rawData[ofs + 3] = alpha;
                    if (alpha == 0) {
                        rawData[ofs + 2] = (byte) 0;
                        rawData[ofs + 1] = (byte) 0;
                        rawData[ofs] = (byte) 0;
                    }
                }
            }
        } else {
            for (int i = 0; i < imageHeight; i++) {
                for (int j = 0; j < imageWidth; j++) {
                    blue = dis.readByte();
                    green = dis.readByte();
                    red = dis.readByte();
                    if (this.shouldForceAlpha) {
                        alpha = (byte) 255;
                    } else {
                        alpha = dis.readByte();
                    }
                    int ofs = ((j + (i * textureWidth)) * 4);
                    if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) {
                        rawData[ofs] = red;
                        rawData[ofs + 1] = green;
                        rawData[ofs + 2] = blue;
                        rawData[ofs + 3] = alpha;
                    } else {
                        rawData[ofs] = red;
                        rawData[ofs + 1] = green;
                        rawData[ofs + 2] = blue;
                        rawData[ofs + 3] = alpha;
                    }
                    if (alpha == 0) {
                        rawData[ofs + 2] = 0;
                        rawData[ofs + 1] = 0;
                        rawData[ofs] = 0;
                    }
                }
            }
        }
    }
    imageStream.close();
    if (transparency != null) {
        for (int i = 0; i < rawData.length; i += 4) {
            boolean match = true;
            for (int c = 0; c < 3; c++) {
                if (rawData[i + c] != transparency[c]) {
                    match = false;
                }
            }
            if (match) {
                rawData[i + 3] = 0;
            }
        }
    }
    // Get a pointer to the image memory
    ByteBuffer scratch = createNativeOrderedByteBuffer(rawData.length);
    scratch.put(rawData);
    int perPixel = imageBitDepth / 8;
    if (imageHeight < textureHeight - 1) {
        int topOffset = (textureHeight - 1) * (textureWidth * perPixel);
        int bottomOffset = (imageHeight - 1) * (textureWidth * perPixel);
        for (int x = 0; x < textureWidth * perPixel; x++) {
            scratch.put(topOffset + x, scratch.get(x));
            scratch.put(bottomOffset + (textureWidth * perPixel) + x, scratch.get((textureWidth * perPixel) + x));
        }
    }
    if (imageWidth < textureWidth - 1) {
        for (int y = 0; y < textureHeight; y++) {
            for (int i = 0; i < perPixel; i++) {
                scratch.put(((y + 1) * (textureWidth * perPixel)) - perPixel + i, scratch.get(y * (textureWidth * perPixel) + i));
                scratch.put((y * (textureWidth * perPixel)) + (imageWidth * perPixel) + i, scratch.get((y * (textureWidth * perPixel)) + ((imageWidth - 1) * perPixel) + i));
            }
        }
    }
    scratch.flip();
    return scratch;
}
Example 6
Project: Illarion-Java-master  File: Crypto.java View source code
/**
     * Get a stream that delivers the decrypted data.
     *
     * @param src the stream that delivers the encryted data
     * @return the stream that provides the decrypted data
     * @throws CryptoException
     */
@Nonnull
public InputStream getDecryptedStream(@Nonnull @WillNotClose InputStream src) throws CryptoException {
    if (!hasPublicKey()) {
        throw new IllegalStateException("No keys loaded");
    }
    try {
        //noinspection IOResourceOpenedButNotSafelyClosed,resource
        DataInputStream dIn = new DataInputStream(src);
        int keyLength = dIn.readInt();
        byte[] wrappedKey = new byte[keyLength];
        int n = 0;
        while (n < keyLength) {
            n += dIn.read(wrappedKey, n, keyLength - n);
        }
        @Nonnull Cipher wrappingCipher = Cipher.getInstance(KEY_ALGORITHM);
        wrappingCipher.init(Cipher.UNWRAP_MODE, publicKey);
        Key encryptionKey = wrappingCipher.unwrap(wrappedKey, "DES", Cipher.SECRET_KEY);
        @Nonnull Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, encryptionKey);
        return new CipherInputStream(src, cipher);
    } catch (@Nonnull Exception e) {
        throw new CryptoException(e);
    }
}
Example 7
Project: FindBug-for-Domino-Designer-master  File: SortedBugCollection.java View source code
private static void checkInputStream(@WillNotClose InputStream in) throws IOException {
    if (!in.markSupported())
        return;
    byte[] buf = new byte[200];
    in.mark(buf.length);
    int numRead = 0;
    boolean isEOF = false;
    while (numRead < buf.length && !isEOF) {
        int n = in.read(buf, numRead, buf.length - numRead);
        if (n < 0) {
            isEOF = true;
        } else {
            numRead += n;
        }
    }
    in.reset();
    BufferedReader reader = new BufferedReader(Util.getReader(new ByteArrayInputStream(buf)));
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("<BugCollection")) {
                return;
            }
        }
    } finally {
        reader.close();
    }
    throw new IOException("XML does not contain saved bug data");
}
Example 8
Project: nomulus-master  File: Ghostryde.java View source code
/**
   * Opens a new {@link Encryptor} (Writing Step 1/3)
   *
   * <p>This is the first step in creating a ghostryde file. After this method, you'll want to
   * call {@link #openCompressor(Encryptor)}.
   *
   * @param os is the upstream {@link OutputStream} to which the result is written.
   * @param publicKey is the public encryption key of the recipient.
   * @throws IOException
   * @throws PGPException
   */
@CheckReturnValue
public Encryptor openEncryptor(@WillNotClose OutputStream os, PGPPublicKey publicKey) throws IOException, PGPException {
    PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(CIPHER).setWithIntegrityPacket(USE_INTEGRITY_PACKET).setSecureRandom(getRandom()).setProvider(PROVIDER_NAME));
    encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
    return new Encryptor(encryptor.open(os, new byte[bufferSize]));
}
Example 9
Project: Diorite-master  File: ConfigInvocationHandler.java View source code
private void loadImpl(@WillNotClose Reader reader) {
    Config fromYaml = Serialization.getGlobal().fromYaml(reader, this.template.getConfigType());
    ConfigInvocationHandler invocationHandler = (ConfigInvocationHandler) Proxy.getInvocationHandler(fromYaml);
    this.predefinedValues.putAll(invocationHandler.predefinedValues);
    this.dynamicValues.putAll(invocationHandler.dynamicValues);
    this.simpleDynamicValues.putAll(invocationHandler.simpleDynamicValues);
}
Example 10
Project: org.revisionfilter-master  File: BuildObligationPolicyDatabase.java View source code
public void visitClass(ClassDescriptor classDescriptor) throws CheckedAnalysisException {
    XClass xclass = Global.getAnalysisCache().getClassAnalysis(XClass.class, classDescriptor);
    // Is this class an obligation type?
    Obligation thisClassObligation = database.getFactory().getObligationByType(xclass.getClassDescriptor());
    // Scan methods for uses of obligation-related annotations
    for (XMethod xmethod : xclass.getXMethods()) {
        // Is this method marked with @CreatesObligation?
        if (thisClassObligation != null) {
            if (xmethod.getAnnotation(createsObligation) != null) {
                database.addEntry(new MatchMethodEntry(xmethod, ObligationPolicyDatabaseActionType.ADD, ObligationPolicyDatabaseEntryType.STRONG, thisClassObligation));
            }
            // Is this method marked with @DischargesObligation?
            if (xmethod.getAnnotation(dischargesObligation) != null) {
                database.addEntry(new MatchMethodEntry(xmethod, ObligationPolicyDatabaseActionType.DEL, ObligationPolicyDatabaseEntryType.STRONG, thisClassObligation));
            }
        }
        // See what obligation parameters there are
        Obligation[] paramObligationTypes = database.getFactory().getParameterObligationTypes(xmethod);
        //
        // Check for @WillCloseWhenClosed, @WillClose, @WillNotClose, or other
        // indications of how obligation parameters are handled.
        //
        boolean methodHasCloseInName = false;
        if (INFER_CLOSE_METHODS) {
            SplitCamelCaseIdentifier splitter = new SplitCamelCaseIdentifier(xmethod.getName());
            methodHasCloseInName = splitter.split().contains("close");
        }
        for (int i = 0; i < xmethod.getNumParams(); i++) if (paramObligationTypes[i] != null) {
            if (xmethod.getParameterAnnotation(i, willCloseWhenClosed) != null) {
                //
                // Calling this method deletes a parameter obligation and
                // creates a new obligation for the object returned by
                // the method.
                //
                handleWillCloseWhenClosed(xmethod, paramObligationTypes[i]);
            } else if (xmethod.getParameterAnnotation(i, willClose) != null) {
                if (paramObligationTypes[i] == null) {
                    // Hmm...
                    if (DEBUG_ANNOTATIONS) {
                        System.out.println("Method " + xmethod.toString() + " has param " + i + " annotated @WillClose, " + "but its type is not an obligation type");
                    }
                } else {
                    addParameterDeletesObligationDatabaseEntry(xmethod, paramObligationTypes[i], ObligationPolicyDatabaseEntryType.STRONG);
                }
                sawAnnotationsInApplicationCode = true;
            } else if (xmethod.getParameterAnnotation(i, willNotClose) != null) {
                // No database entry needs to be added
                sawAnnotationsInApplicationCode = true;
            } else if (paramObligationTypes[i] != null) {
                if (INFER_CLOSE_METHODS && methodHasCloseInName) {
                    // Method has "close" in its name.
                    // Assume that it deletes the obligation.
                    addParameterDeletesObligationDatabaseEntry(xmethod, paramObligationTypes[i], ObligationPolicyDatabaseEntryType.STRONG);
                } else {
                    /*
						// Interesting case: we have a parameter which is
						// an Obligation type, but no annotation or other indication
						// what is done by the method with the obligation.
						// We'll create a "weak" database entry deleting the
						// obligation.  If strict checking is performed,
						// weak entries are ignored.
						*/
                    if (xmethod.getName().equals("<init>") || xmethod.isStatic() || xmethod.getName().toLowerCase().indexOf("close") >= 0 || xmethod.getSignature().toLowerCase().indexOf("Closeable") >= 0)
                        addParameterDeletesObligationDatabaseEntry(xmethod, paramObligationTypes[i], ObligationPolicyDatabaseEntryType.WEAK);
                }
            }
        }
    }
}
Example 11
Project: findbugs-rcp-master  File: SortedBugCollection.java View source code
private void checkInputStream(@WillNotClose InputStream in) throws IOException {
    if (!in.markSupported())
        return;
    byte[] buf = new byte[200];
    in.mark(buf.length);
    int numRead = 0;
    boolean isEOF = false;
    while (numRead < buf.length && !isEOF) {
        int n = in.read(buf, numRead, buf.length - numRead);
        if (n < 0) {
            isEOF = true;
        } else {
            numRead += n;
        }
    }
    in.reset();
    BufferedReader reader = new BufferedReader(Util.getReader(new ByteArrayInputStream(buf)));
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("<BugCollection")) {
                return;
            }
        }
    } finally {
        reader.close();
    }
    throw new IOException("XML does not contain saved bug data");
}
Example 12
Project: bazel-master  File: DownloaderTestUtils.java View source code
static void sendLines(@WillNotClose Socket socket, String... data) throws IOException {
    ByteStreams.copy(new ByteArrayInputStream(Joiner.on("\r\n").join(data).getBytes(ISO_8859_1)), socket.getOutputStream());
}
Example 13
Project: lenskit-master  File: TableWriters.java View source code
/**
     * Create a table writer that writes data with common leading columns to an
     * underlying table writer.  The underlying writer will not be closed when the prefixed writer
     * is closed.
     *
     * @param base   The base table writer for output.
     * @param prefix The values of the leading columns in this table writer.
     * @return A table writer with
     *         {@code base.getColumnCount() - prefix.size()} columns. Each
     *         row is prefixed with the values in <var>prefix</var>.
     * @since 1.1
     */
public static TableWriter prefixed(@WillNotClose TableWriter base, List<?> prefix) {
    return new PrefixedTableWriter(base, prefix);
}
Example 14
Project: com.cedarsoft.serialization-master  File: AbstractJacksonSerializer.java View source code
@Override
public void serialize(@Nonnull T object, @WillNotClose @Nonnull OutputStream out) throws IOException {
    JsonFactory jsonFactory = JacksonSupport.getJsonFactory();
    JsonGenerator generator = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
    serialize(object, generator);
    generator.flush();
}
Example 15
Project: test-master  File: DownloaderTestUtils.java View source code
static void sendLines(@WillNotClose Socket socket, String... data) throws IOException {
    ByteStreams.copy(new ByteArrayInputStream(Joiner.on("\r\n").join(data).getBytes(ISO_8859_1)), socket.getOutputStream());
}
Example 16
Project: Correct-master  File: DownloaderTestUtils.java View source code
static void sendLines(@WillNotClose Socket socket, String... data) throws IOException {
    ByteStreams.copy(new ByteArrayInputStream(Joiner.on("\r\n").join(data).getBytes(ISO_8859_1)), socket.getOutputStream());
}
Example 17
Project: jarjar-master  File: IoUtil.java View source code
public static void copy(@Nonnull @WillNotClose InputStream is, @Nonnull @WillNotClose OutputStream out, @Nonnull byte[] buf) throws IOException {
    for (; ; ) {
        int amt = is.read(buf);
        if (amt < 0)
            break;
        out.write(buf, 0, amt);
    }
}
Example 18
Project: recommender-master  File: TableWriters.java View source code
/**
     * Create a table writer that writes data with common leading columns to an
     * underlying table writer.  The underlying writer will not be closed when the prefixed writer
     * is closed.
     *
     * @param base   The base table writer for output.
     * @param prefix The values of the leading columns in this table writer.
     * @return A table writer with
     *         {@code base.getColumnCount() - prefix.size()} columns. Each
     *         row is prefixed with the values in <var>prefix</var>.
     * @since 1.1
     */
public static TableWriter prefixed(@WillNotClose TableWriter base, List<?> prefix) {
    return new PrefixedTableWriter(base, prefix);
}