Example usage for java.io ByteArrayInputStream close

List of usage examples for java.io ByteArrayInputStream close

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayInputStream has no effect.

Usage

From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore.java

private void loadRMDelegationKeyState(RMState rmState) throws Exception {
    List<String> childNodes = getChildrenWithRetries(dtMasterKeysRootPath, false);
    for (String childNodeName : childNodes) {
        String childNodePath = getNodePath(dtMasterKeysRootPath, childNodeName);
        byte[] childData = getDataWithRetries(childNodePath, false);

        if (childData == null) {
            LOG.warn("Content of " + childNodePath + " is broken.");
            continue;
        }//from   w  w  w.java 2 s .c  o  m

        ByteArrayInputStream is = new ByteArrayInputStream(childData);
        DataInputStream fsIn = new DataInputStream(is);

        try {
            if (childNodeName.startsWith(DELEGATION_KEY_PREFIX)) {
                DelegationKey key = new DelegationKey();
                key.readFields(fsIn);
                rmState.rmSecretManagerState.masterKeyState.add(key);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Loaded delegation key: keyId=" + key.getKeyId() + ", expirationDate="
                            + key.getExpiryDate());
                }
            }
        } finally {
            is.close();
        }
    }
}

From source file:XmldapCertsAndKeys.java

/**
 * Decodes data from Base64 notation, automatically detecting
 * gzip-compressed data and decompressing it.
 * /*from  ww w  .java 2 s . co  m*/
 * @param s
 *            the string to decode
 * @return the decoded data
 * @since 1.4
 */
public static byte[] decode(String s) {
    byte[] bytes;
    try {
        bytes = s.getBytes(PREFERRED_ENCODING);
    } // end try
    catch (java.io.UnsupportedEncodingException uee) {
        bytes = s.getBytes();
    } // end catch
      // </change>

    // Decode
    bytes = decode(bytes, 0, bytes.length);

    // Check to see if it's gzip-compressed
    // GZIP Magic Two-Byte Number: 0x8b1f (35615)
    if (bytes != null && bytes.length >= 4) {

        int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
        if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
            java.io.ByteArrayInputStream bais = null;
            java.util.zip.GZIPInputStream gzis = null;
            java.io.ByteArrayOutputStream baos = null;
            byte[] buffer = new byte[2048];
            int length = 0;

            try {
                baos = new java.io.ByteArrayOutputStream();
                bais = new java.io.ByteArrayInputStream(bytes);
                gzis = new java.util.zip.GZIPInputStream(bais);

                while ((length = gzis.read(buffer)) >= 0) {
                    baos.write(buffer, 0, length);
                } // end while: reading input

                // No error? Get new bytes.
                bytes = baos.toByteArray();

            } // end try
            catch (java.io.IOException e) {
                // Just return originally-decoded bytes
            } // end catch
            finally {
                try {
                    baos.close();
                } catch (Exception e) {
                }
                try {
                    gzis.close();
                } catch (Exception e) {
                }
                try {
                    bais.close();
                } catch (Exception e) {
                }
            } // end finally

        } // end if: gzipped
    } // end if: bytes.length >= 2

    return bytes;
}

From source file:com.eviware.soapui.impl.wsdl.monitor.JProxyServletWsdlMonitorMessageExchange.java

private void parseRequestData(IncomingWss incomingRequestWss) {
    ByteArrayInputStream in = request == null ? new ByteArrayInputStream(new byte[0])
            : new ByteArrayInputStream(request);
    try {//w ww  .  j av  a2s  .co  m
        requestContentType = requestHeaders.get("Content-Type", "");
        if (requestContentType != null && requestContentType.toUpperCase().startsWith("MULTIPART")) {
            StringToStringMap values = StringToStringMap.fromHttpHeader(requestContentType);
            requestMmSupport = new MultipartMessageSupport(
                    new MonitorMessageExchangeDataSource("monitor request", in, requestContentType),
                    values.get("start"), null, true, false);
            requestContentType = requestMmSupport.getRootPart() != null
                    ? requestMmSupport.getRootPart().getContentType()
                    : null;
        } else {
            String charset = getCharset(requestHeaders);
            this.requestContent = charset == null ? Tools.readAll(in, 0).toString()
                    : Tools.readAll(in, 0).toString(charset);
        }

        processRequestWss(incomingRequestWss);

        if (checkParse()) {
            operation = findOperation();
        }
    } catch (Exception e) {
        SoapUI.logError(e);
    } finally {
        try {
            in.close();
        } catch (IOException e1) {
            SoapUI.logError(e1);
        }
    }
}

From source file:com.microfocus.application.automation.tools.results.RunResultRecorder.java

/**
 * Copy Summary Html reports created by LoadRunner
 *
 * @param reportFolder/* ww w .  j  a  v a  2  s. co m*/
 * @param testFolderPath
 * @param artifactsDir
 * @param reportNames
 * @param testResult
 * @throws IOException
 * @throws InterruptedException
 */
@SuppressWarnings("squid:S134")
private void createHtmlReport(FilePath reportFolder, String testFolderPath, File artifactsDir,
        List<String> reportNames, TestResult testResult) throws IOException, InterruptedException {
    String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode();
    boolean createReport = archiveTestResultMode
            .equals(ResultsPublisherModel.CreateHtmlReportResults.getValue());

    if (createReport) {
        File testFolderPathFile = new File(testFolderPath);
        FilePath srcDirectoryFilePath = new FilePath(reportFolder, HTML_REPORT_FOLDER);
        if (srcDirectoryFilePath.exists()) {
            FilePath srcFilePath = new FilePath(srcDirectoryFilePath, IE_REPORT_FOLDER);
            if (srcFilePath.exists()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                srcFilePath.zip(baos);
                File reportDirectory = new File(artifactsDir.getParent(), PERFORMANCE_REPORT_FOLDER);
                if (!reportDirectory.exists()) {
                    reportDirectory.mkdir();
                }
                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                FilePath reportDirectoryFilePath = new FilePath(reportDirectory);
                FilePath tmpZipFile = new FilePath(reportDirectoryFilePath, "tmp.zip");
                tmpZipFile.copyFrom(bais);
                bais.close();
                baos.close();
                tmpZipFile.unzip(reportDirectoryFilePath);
                String newFolderName = org.apache.commons.io.FilenameUtils
                        .getName(testFolderPathFile.getPath());
                FileUtils.moveDirectory(new File(reportDirectory, IE_REPORT_FOLDER),
                        new File(reportDirectory, newFolderName));
                tmpZipFile.delete();
                outputReportFiles(reportNames, reportDirectory, testResult, "Performance Report",
                        HTML_REPORT_FOLDER);
            }
        }
    }
}

From source file:org.apache.oodt.security.sso.opensso.SSOProxy.java

private UserDetails parseUserDetails(String serviceResponse) {
    ByteArrayInputStream is = new ByteArrayInputStream(serviceResponse.getBytes());
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    UserDetails details = new UserDetails();
    String line = null, lastAttrKeyRead = null;

    try {//w  ww .  ja v a  2s . c  om
        while ((line = br.readLine()) != null) {
            String key, val;
            if (line.startsWith(USER_DETAILS_ROLE)) {
                // can't parse by splitting, parse by using substring
                key = line.substring(0, USER_DETAILS_ROLE.length());
                val = line.substring(USER_DETAILS_ROLE.length() + 1);
            } else {
                String[] lineToks = line.split("=");
                key = lineToks[0];
                val = lineToks[1];
            }

            if (key.equals(USER_DETAILS_TOKEN)) {
                details.setToken(val);
            } else if (key.equals(USER_DETAILS_ROLE)) {
                details.getRoles().add(val);
            } else if (key.equals(USER_DETAILS_ATTR_NAME)) {
                lastAttrKeyRead = val;
            } else if (key.equals(USER_DETAILS_ATTR_VALUE)) {
                details.getAttributes().addMetadata(lastAttrKeyRead, val);
            }
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, e.getMessage());
        LOG.log(Level.WARNING,
                "Error reading service response line: [" + line + "]: Message: " + e.getMessage());
    } finally {
        try {
            is.close();
        } catch (Exception ignore) {
        }

        try {
            br.close();
        } catch (Exception ignore) {
        }

    }

    return details;
}

From source file:de.berlios.jedi.common.jisp.JispStoredWrapper.java

/**
 * Returns the icondef.xml file in the stored Jisp as a JDOM Document.
 * /*  w w w .ja v  a 2  s  .com*/
 * @return The icondef.xml file as a JDOM Document.
 * @throws JispInvalidIcondefException
 *             If the icondef.xml file is not valid or not well-formed.
 * @throws UnsupportedOperationException
 *             If there's no support for the icondef.xml file encoding.
 */
public Document getIcondef() throws JispInvalidIcondefException, UnsupportedOperationException {
    Document icondef = null;

    SAXBuilder builder = getSAXBuilder();

    ByteArrayInputStream in = null;
    try {
        icondef = builder.build(in = new ByteArrayInputStream((byte[]) contents.get("icondef.xml")));
    } catch (JDOMException e) {
        LogFactory.getLog(JispPackageStorer.class).error("The icondef.xml file is not valid: " + e.getMessage(),
                e);
        throw new JispInvalidIcondefException("The icondef.xml file is not valid: " + e.getMessage());
    } catch (UTFDataFormatException e) {
        LogFactory.getLog(JispPackageStorer.class)
                .error("The icondef.xml file is not valid: " + "UTF-8 encoding error", e);
        throw new JispInvalidIcondefException("The icondef.xml file is not valid: " + "UTF-8 encoding error");
    } catch (UnsupportedEncodingException e) {
        LogFactory.getLog(JispPackageStorer.class).error(
                "The server doesn't support icondef.xml file encoding!!!" + " No jisp processing can be made!!",
                e);
        throw new UnsupportedOperationException("The server doesn't support icondef.xml file encoding!!!"
                + " No jisp processing can be made!!");
    } catch (IOException e) {
        LogFactory.getLog(JispPackageStorer.class)
                .error("The icondef.xml file is not valid: IOException: " + e.getMessage(), e);
        throw new JispInvalidIcondefException(
                "The icondef.xml file is not valid: IOException: " + e.getMessage());
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
    }
    return icondef;
}

From source file:org.kontalk.crypto.Coder.java

/**
 * Creates encrypted and signed message body.
 * Errors that may occur are saved to the message.
 * @param message// w  w w .  j  a  v  a2  s . c  o  m
 * @return the encrypted and signed text.
 */
public static Optional<byte[]> processOutMessage(OutMessage message) {
    if (message.getCoderStatus().getEncryption() != Encryption.DECRYPTED) {
        LOGGER.warning("message does not want to be encrypted");
        return Optional.empty();
    }

    LOGGER.info("encrypting message...");

    // get keys
    KeysResult keys = getKeys(message.getUser());
    if (keys.myKey == null || keys.otherKey == null) {
        message.setSecurityErrors(keys.errors);
        return Optional.empty();
    }

    // secure the message against the most basic attacks using Message/CPIM
    String from = keys.myKey.getUserId();
    String to = keys.otherKey.userID + "; ";
    String mime = "text/plain";
    // TODO encrypt more possible content
    String text = message.getContent().getPlainText();
    CPIMMessage cpim = new CPIMMessage(from, to, new Date(), mime, text);
    byte[] plainText;
    try {
        plainText = cpim.toByteArray();
    } catch (UnsupportedEncodingException ex) {
        LOGGER.log(Level.WARNING, "UTF-8 not supported", ex);
        plainText = cpim.toString().getBytes();
    }

    // setup data encryptor & generator
    BcPGPDataEncryptorBuilder encryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_192);
    encryptor.setWithIntegrityPacket(true);
    encryptor.setSecureRandom(new SecureRandom());

    // add public key recipients
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptor);
    //for (PGPPublicKey rcpt : mRecipients)
    encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(keys.otherKey.encryptKey));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(plainText);
    try { // catch all io and pgp exceptions

        OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]);

        // setup compressed data generator
        PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        OutputStream compressedOut = compGen.open(encryptedOut, new byte[BUFFER_SIZE]);

        // setup signature generator
        int algo = keys.myKey.getPublicEncryptionKey().getAlgorithm();
        PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
                new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA1));
        sigGen.init(PGPSignature.BINARY_DOCUMENT, keys.myKey.getPrivateEncryptionKey());

        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, keys.myKey.getUserId());
        sigGen.setUnhashedSubpackets(spGen.generate());

        sigGen.generateOnePassVersion(false).encode(compressedOut);

        // Initialize literal data generator
        PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalGen.open(compressedOut, PGPLiteralData.BINARY, "", new Date(),
                new byte[BUFFER_SIZE]);

        // read the "in" stream, compress, encrypt and write to the "out" stream
        // this must be done if clear data is bigger than the buffer size
        // but there are other ways to optimize...
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = in.read(buf)) > 0) {
            literalOut.write(buf, 0, len);
            try {
                sigGen.update(buf, 0, len);
            } catch (SignatureException ex) {
                LOGGER.log(Level.WARNING, "can't read data for signature", ex);
                message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA));
                return Optional.empty();
            }
        }

        in.close();
        literalGen.close();

        // generate the signature, compress, encrypt and write to the "out" stream
        try {
            sigGen.generate().encode(compressedOut);
        } catch (SignatureException ex) {
            LOGGER.log(Level.WARNING, "can't create signature", ex);
            message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA));
            return Optional.empty();
        }
        compGen.close();
        encGen.close();

    } catch (IOException | PGPException ex) {
        LOGGER.log(Level.WARNING, "can't encrypt message", ex);
        message.setSecurityErrors(EnumSet.of(Error.UNKNOWN_ERROR));
        return Optional.empty();
    }

    LOGGER.info("encryption successful");
    return Optional.of(out.toByteArray());
}

From source file:org.apache.manifoldcf.crawler.connectors.generic.GenericConnector.java

@Override
public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec,
        IProcessActivity activities, int jobMode, boolean usesDefaultAuthority)
        throws ManifoldCFException, ServiceInterruption {

    // Forced acls
    String[] acls = getAcls(spec);
    // Sort it,//from  w w  w  .ja va  2 s .co m
    java.util.Arrays.sort(acls);
    String rights = java.util.Arrays.toString(acls);

    String genericAuthMode = "provided";
    for (int i = 0; i < spec.getChildCount(); i++) {
        SpecificationNode sn = spec.getChild(i);
        if (sn.getType().equals("genericAuthMode")) {
            genericAuthMode = sn.getValue();
            break;
        }
    }

    HttpClient client = getClient();
    StringBuilder url = new StringBuilder(genericEntryPoint);

    url.append("?").append(ACTION_PARAM_NAME).append("=").append(ACTION_ITEMS);
    for (int i = 0; i < documentIdentifiers.length; i++) {
        url.append("&id[]=").append(URLEncoder.encode(documentIdentifiers[i]));
    }
    for (int i = 0; i < spec.getChildCount(); i++) {
        SpecificationNode sn = spec.getChild(i);
        if (sn.getType().equals("param")) {
            String paramName = sn.getAttributeValue("name");
            String paramValue = sn.getValue();
            url.append("&").append(URLEncoder.encode(paramName)).append("=")
                    .append(URLEncoder.encode(paramValue));
        }
    }

    String[] versions = null;
    try {
        DocumentVersionThread versioningThread = new DocumentVersionThread(client, url.toString(),
                documentIdentifiers, genericAuthMode, rights, documentCache);
        versioningThread.start();
        try {
            versions = versioningThread.finishUp();
        } catch (IOException ex) {
            handleIOException((IOException) ex);
        } catch (InterruptedException ex) {
            throw new ManifoldCFException(ex.getMessage(), ex, ManifoldCFException.INTERRUPTED);
        }

        // Figure out which ones we need to process, and which we should delete
        for (int i = 0; i < documentIdentifiers.length; i++) {
            String documentIdentifier = documentIdentifiers[i];
            String versionString = versions[i];
            if (versionString == null) {
                activities.deleteDocument(documentIdentifier);
                continue;
            }
            Item item = documentCache.get(documentIdentifier);
            if (item == null) {
                throw new ManifoldCFException(
                        "processDocuments error - no cache entry for: " + documentIdentifier);
            }

            if (item.related != null) {
                for (String rel : item.related) {
                    activities.addDocumentReference(rel, documentIdentifier, RELATIONSHIP_RELATED);
                }
            }
            if (versionString.length() == 0
                    || activities.checkDocumentNeedsReindexing(documentIdentifier, versionString)) {

                // Process the document
                RepositoryDocument doc = new RepositoryDocument();
                if (item.mimeType != null) {
                    doc.setMimeType(item.mimeType);
                }
                if (item.created != null) {
                    doc.setCreatedDate(item.created);
                }
                if (item.updated != null) {
                    doc.setModifiedDate(item.updated);
                }
                if (item.fileName != null) {
                    doc.setFileName(item.fileName);
                }
                if (item.metadata != null) {
                    HashMap<String, List<String>> meta = new HashMap<String, List<String>>();
                    for (Meta m : item.metadata) {
                        if (meta.containsKey(m.name)) {
                            meta.get(m.name).add(m.value);
                        } else {
                            List<String> list = new ArrayList<String>(1);
                            list.add(m.value);
                            meta.put(m.name, list);
                        }
                    }
                    for (String name : meta.keySet()) {
                        List<String> values = meta.get(name);
                        if (values.size() > 1) {
                            String[] svals = new String[values.size()];
                            for (int j = 0; j < values.size(); j++) {
                                svals[j] = values.get(j);
                            }
                            doc.addField(name, svals);
                        } else {
                            doc.addField(name, values.get(0));
                        }
                    }
                }
                if ("provided".equals(genericAuthMode)) {
                    if (item.auth != null) {
                        String[] acl = new String[item.auth.size()];
                        for (int j = 0; j < item.auth.size(); j++) {
                            acl[j] = item.auth.get(j);
                        }
                        doc.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT, acl,
                                new String[] { defaultAuthorityDenyToken });
                    }
                } else {
                    if (acls.length > 0) {
                        doc.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT, acls,
                                new String[] { defaultAuthorityDenyToken });
                    }
                }
                if (item.content != null) {
                    try {
                        byte[] content = item.content.getBytes(StandardCharsets.UTF_8);
                        ByteArrayInputStream is = new ByteArrayInputStream(content);
                        try {
                            doc.setBinary(is, content.length);
                            activities.ingestDocumentWithException(documentIdentifier, versionString, item.url,
                                    doc);
                            is.close();
                        } finally {
                            is.close();
                        }
                    } catch (IOException ex) {
                        handleIOException(ex);
                    }
                } else {
                    url = new StringBuilder(genericEntryPoint);

                    url.append("?").append(ACTION_PARAM_NAME).append("=").append(ACTION_ITEM);
                    url.append("&id=").append(URLEncoder.encode(documentIdentifier));
                    for (int j = 0; j < spec.getChildCount(); j++) {
                        SpecificationNode sn = spec.getChild(j);
                        if (sn.getType().equals("param")) {
                            String paramName = sn.getAttributeValue("name");
                            String paramValue = sn.getValue();
                            url.append("&").append(URLEncoder.encode(paramName)).append("=")
                                    .append(URLEncoder.encode(paramValue));
                        }
                    }

                    ExecuteProcessThread t = new ExecuteProcessThread(client, url.toString());
                    try {
                        t.start();
                        boolean wasInterrupted = false;
                        try {
                            InputStream is = t.getSafeInputStream();
                            long fileLength = t.getStreamLength();
                            try {
                                // Can only index while background thread is running!
                                doc.setBinary(is, fileLength);
                                activities.ingestDocumentWithException(documentIdentifier, versionString,
                                        item.url, doc);
                            } finally {
                                is.close();
                            }
                        } catch (ManifoldCFException e) {
                            if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) {
                                wasInterrupted = true;
                            }
                            throw e;
                        } catch (java.net.SocketTimeoutException e) {
                            throw e;
                        } catch (InterruptedIOException e) {
                            wasInterrupted = true;
                            throw e;
                        } finally {
                            if (!wasInterrupted) {
                                t.finishUp();
                            }
                        }
                    } catch (InterruptedException e) {
                        t.interrupt();
                        throw new ManifoldCFException("Interrupted: " + e.getMessage(), e,
                                ManifoldCFException.INTERRUPTED);
                    } catch (InterruptedIOException e) {
                        t.interrupt();
                        throw new ManifoldCFException("Interrupted: " + e.getMessage(), e,
                                ManifoldCFException.INTERRUPTED);
                    } catch (IOException e) {
                        handleIOException(e);
                    }
                }
            }
        }

    } finally {
        for (String documentIdentifier : documentIdentifiers) {
            if (documentCache.containsKey(documentIdentifier)) {
                documentCache.remove(documentIdentifier);
            }
        }
    }
}