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 = getChildren(dtMasterKeysRootPath);
    for (String childNodeName : childNodes) {
        String childNodePath = getNodePath(dtMasterKeysRootPath, childNodeName);
        byte[] childData = getData(childNodePath);

        if (childData == null) {
            LOG.warn("Content of " + childNodePath + " is broken.");
            continue;
        }// ww w  .  j  a v  a  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:org.bibalex.wamcp.storage.WAMCPStorage.java

public/* synchronized */void release(Document metadataXml, Element metaAlbum)
        throws BAGException, WAMCPException, WFSVNArtifactLoadingException, WFSVNLockedException {
    this.guardArtifactLoaded();

    // JdbcTemplate locksDBTempl =
    // this.svnClient.getWfProcess().getJdbcTempl();

    String releasedMetaGallUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(),
            BAGGalleryAbstract.FILENAME_GALLERY_METADATA_XML);

    try {/*from   w ww.j a va 2  s  . co  m*/
        XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat().setEncoding("UTF-8"));

        this.svnClient.getWfProcess().lockUrlStr(releasedMetaGallUrlStr, this.sessionBBean.getUserName());

        try {
            SAXBuilder saxBuilder = new SAXBuilder();

            saxBuilder.setFeature("http://xml.org/sax/features/validation", false);
            saxBuilder.setFeature("http://xml.org/sax/features/namespaces", true);
            saxBuilder.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
            // Unsupported:
            // saxBuilder.setFeature("http://xml.org/sax/features/xmlns-uris",
            // false);

            Document metaGalleryXml;

            ByteArrayOutputStream remoteFileOS = new ByteArrayOutputStream();
            ByteArrayInputStream metaGalleryIn = null;
            try {
                BAGStorage.readRemoteFile(releasedMetaGallUrlStr, remoteFileOS);

                metaGalleryIn = new ByteArrayInputStream(remoteFileOS.toByteArray());

                metaGalleryXml = saxBuilder.build(metaGalleryIn);

            } finally {
                try {
                    remoteFileOS.close();
                    metaGalleryIn.close();
                } catch (IOException e) {
                    throw new BAGException(e);
                }
            }
            XPath oldMetaAlbumXP = XPath
                    .newInstance("//album[@name='" + metaAlbum.getAttributeValue("name") + "']");

            Element metaGalleryRoot = metaGalleryXml.getRootElement();
            for (Object oldMetaAlbum : oldMetaAlbumXP.selectNodes(metaGalleryRoot)) {
                ((Element) oldMetaAlbum).detach();
            }

            metaGalleryRoot.addContent(metaAlbum);

            File metaGalleryTempFile = File
                    .createTempFile(FileUtils.makeSafeFileName(this.sessionBBean.getUserName()), "metagallery");
            FileOutputStream metaGalleryOut = new FileOutputStream(metaGalleryTempFile);

            outputter.output(metaGalleryXml, metaGalleryOut);

            metaGalleryOut.flush();
            metaGalleryOut.close();

            String releasedXMLUrlStr = URLPathStrUtils.appendParts(this.galleryBean.getGalleryRootUrlStr(),
                    "XML", filenameForShelfMark(this.artifact.getArtifactName()) + ".tei.xml");

            File msDescTempFile = File.createTempFile(
                    FileUtils.makeSafeFileName(this.sessionBBean.getUserName()), "msDescReleased");
            FileOutputStream msDescOut = new FileOutputStream(msDescTempFile);

            outputter.output(metadataXml, msDescOut);

            msDescOut.flush();
            msDescOut.close();

            // BAGStorage.copyFile(msDescTempFile.toURI().toString(),
            // releasedXMLUrlStr);
            // BAGStorage.copyFile(metaGalleryTempFile.toURI().toString(),
            // releasedMetaGallUrlStr);
            // TODO be DRY

            if (!BAGStorage.putFile(releasedXMLUrlStr, msDescTempFile, null)) {
                throw new WAMCPGeneralCorrectableException("Could not upload tei file to release destination");
            }

            if (!BAGStorage.putFile(releasedMetaGallUrlStr, metaGalleryTempFile, null)) {
                throw new WAMCPGeneralCorrectableException(
                        "Could not upload meta gallery file to release destination");
            }

            generateMARCFile(msDescTempFile, this.artifact.getArtifactName(),
                    this.galleryBean.getGalleryRootUrlStr());

            // generate html file for the manuscript on release
            // both versions are generated (full and DIV)
            // also generate html for metadata print
            // also generate pdf for images of manuscript
            // Yasmine20110508 {
            // Yasmine20110621{

            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                    .getExternalContext().getRequest();
            String uri = request.getRequestURL().toString();
            String[] splited = uri.split("/");
            // host = http://172.16.0.17:80/
            //              String host = splited[0]+"//"+splited[2]+"/";
            String host = splited[0] + "//" + request.getLocalAddr() + ":" + request.getLocalPort() + "/";

            int statusCode = 0;
            BAOAIIDBuilder oaiIdBuilder = new BAOAIIDBuilder();
            String oaiId = oaiIdBuilder.buildId(this.artifact.getArtifactName());
            String url = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=html";
            statusCode = myGetHttp(url);
            System.out.println(url + " ==> status code: " + statusCode);

            String urlDivOpt = host + "BAG-API/rest/desc/" + oaiId + "/transform?divOpt=true&type=html";
            statusCode = myGetHttp(urlDivOpt);
            System.out.println(urlDivOpt + " ==> status code: " + statusCode);

            String urlMetadataHtml = host + "BAG-API/rest/desc/" + oaiId + "/transform?type=meta";
            statusCode = myGetHttp(urlMetadataHtml);
            System.out.println(urlMetadataHtml + " ==> status code: " + statusCode);

            //            String rootUrlStr = this.galleryBean.getGalleryRootUrlStr();
            //            String tempUserName = this.sessionBBean.getUserName();
            //            System.out.println("rootUrlStr: "+rootUrlStr);
            //            System.out.println("tempUserName: "+tempUserName);
            //            transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  filenameForShelfMark(this.artifact.getArtifactName()),
            //                  false);
            //            transformXMLtoHTML(rootUrlStr, tempUserName,
            //                  filenameForShelfMark(this.artifact.getArtifactName()),
            //                  true);
            // } Yasmine20110621
            // } Yasmine20110508
        } finally {
            this.svnClient.getWfProcess().unlockUrlStr(releasedMetaGallUrlStr, this.sessionBBean.getUserName());
        }
    } catch (DataIntegrityViolationException e) {
        throw new WAMCPGeneralCorrectableException(
                "Another user is releasing at the moment, try again in a few seconds");
    } catch (JDOMException e) {
        throw new WAMCPException(e);
    } catch (IOException e) {
        throw new WAMCPException(e);
    }

}

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

private FilePath copyRunReport(FilePath reportFolder, File buildDir, String scenerioName)
        throws IOException, InterruptedException {
    FilePath slaReportFilePath = new FilePath(reportFolder, "RunReport.xml");
    if (slaReportFilePath.exists()) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        slaReportFilePath.zip(baos);//w ww  .j a va2s  .  c o m
        File slaDirectory = new File(buildDir, "RunReport");
        if (!slaDirectory.exists()) {
            slaDirectory.mkdir();
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        FilePath slaDirectoryFilePath = new FilePath(slaDirectory);
        FilePath tmpZipFile = new FilePath(slaDirectoryFilePath, "runReport.zip");
        tmpZipFile.copyFrom(bais);
        bais.close();
        baos.close();
        tmpZipFile.unzip(slaDirectoryFilePath);
        FilePath slaFile = new FilePath(slaDirectoryFilePath, "RunReport.xml");
        slaFile.getBaseName();
        slaFile.renameTo(new FilePath(slaDirectoryFilePath, scenerioName + ".xml"));

        slaFile = new FilePath(slaDirectoryFilePath, scenerioName + ".xml");

        return slaFile;
    }
    throw (new IOException("no RunReport.xml file was created"));
}

From source file:org.apache.pdfbox.filter.FlateFilter.java

/**
 * {@inheritDoc}//from w  w  w  . j  a v a 2  s  .co  m
 */
public void decode(InputStream compressedData, OutputStream result, COSDictionary options, int filterIndex)
        throws IOException {
    COSBase baseObj = options.getDictionaryObject(COSName.DECODE_PARMS, COSName.DP);
    COSDictionary dict = null;
    if (baseObj instanceof COSDictionary) {
        dict = (COSDictionary) baseObj;
    } else if (baseObj instanceof COSArray) {
        COSArray paramArray = (COSArray) baseObj;
        if (filterIndex < paramArray.size()) {
            dict = (COSDictionary) paramArray.getObject(filterIndex);
        }
    } else if (baseObj != null) {
        throw new IOException(
                "Error: Expected COSArray or COSDictionary and not " + baseObj.getClass().getName());
    }

    int predictor = -1;
    int colors = -1;
    int bitsPerPixel = -1;
    int columns = -1;
    ByteArrayInputStream bais = null;
    ByteArrayOutputStream baos = null;
    if (dict != null) {
        predictor = dict.getInt(COSName.PREDICTOR);
        if (predictor > 1) {
            colors = dict.getInt(COSName.COLORS);
            bitsPerPixel = dict.getInt(COSName.BITS_PER_COMPONENT);
            columns = dict.getInt(COSName.COLUMNS);
        }
    }

    try {
        baos = decompress(compressedData);
        // Decode data using given predictor
        if (predictor == -1 || predictor == 1) {
            result.write(baos.toByteArray());
        } else {
            /*
             * Reverting back to default values
             */
            if (colors == -1) {
                colors = 1;
            }
            if (bitsPerPixel == -1) {
                bitsPerPixel = 8;
            }
            if (columns == -1) {
                columns = 1;
            }

            // Copy data to ByteArrayInputStream for reading
            bais = new ByteArrayInputStream(baos.toByteArray());

            byte[] decodedData = decodePredictor(predictor, colors, bitsPerPixel, columns, bais);
            bais.close();
            bais = null;

            result.write(decodedData);
        }
        result.flush();
    } catch (DataFormatException exception) {
        // if the stream is corrupt a DataFormatException may occur
        LOG.error("FlateFilter: stop reading corrupt stream due to a DataFormatException");
        // re-throw the exception, caller has to handle it
        IOException io = new IOException();
        io.initCause(exception);
        throw io;
    } finally {
        if (bais != null) {
            bais.close();
        }
        if (baos != null) {
            baos.close();
        }
    }
}

From source file:Base64.java

/**
 * Decodes data from Base64 notation, automatically
 * detecting gzip-compressed data and decompressing it.
 *
 * @param s the string to decode//from   w  w  w  . jav a 2  s  .co m
 * @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:org.sakaibrary.osid.repository.xserver.AssetIterator.java

/**
 * This method parses the xml StringBuilder and creates Assets, Records
 * and Parts in the Repository with the given repositoryId.
 *
 * @param xml input xml in "sakaibrary" format
 * @param log the log being used by the Repository
 * @param repositoryId the Id of the Repository in which to create Assets,
 * Records and Parts.//  www  . j av  a2  s.c  om
 *
 * @throws org.osid.repository.RepositoryException
 */
private void createAssets(java.io.ByteArrayInputStream xml, org.osid.shared.Id repositoryId)
        throws org.osid.repository.RepositoryException {
    this.repositoryId = repositoryId;
    recordStructureId = RecordStructure.getInstance().getId();
    textBuffer = new StringBuilder();

    // use a SAX parser
    javax.xml.parsers.SAXParserFactory factory;
    javax.xml.parsers.SAXParser saxParser;

    // set up the parser
    factory = javax.xml.parsers.SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);

    // start parsing
    try {
        saxParser = factory.newSAXParser();
        saxParser.parse(xml, this);
        xml.close();
    } catch (SAXParseException spe) {
        // Use the contained exception, if any
        Exception x = spe;

        if (spe.getException() != null) {
            x = spe.getException();
        }

        // Error generated by the parser
        LOG.warn("createAssets() parsing exception: " + spe.getMessage() + " - xml line " + spe.getLineNumber()
                + ", uri " + spe.getSystemId(), x);
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("createAssets() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        LOG.warn("createAssets() SAX parser cannot be built with " + "specified options");
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("createAssets() IO exception", ioe);
    }
}

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

/**
 * Copy Summary Html reports created by LoadRunner
 *
 * @param reportFolder/*from www .ja  v  a  2 s.c  o 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, false);
            }
        }
    }
}

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

/**
 * Copies the run report from the executing node to the Jenkins master for processing.
 * @param reportFolder//from w  w  w. j  av  a 2  s .  c om
 * @param buildDir
 * @param scenarioName
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
private FilePath copyRunReport(FilePath reportFolder, File buildDir, String scenarioName)
        throws IOException, InterruptedException {
    FilePath slaReportFilePath = new FilePath(reportFolder, "RunReport.xml");
    if (slaReportFilePath.exists()) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        slaReportFilePath.zip(baos);
        File slaDirectory = new File(buildDir, "RunReport");
        if (!slaDirectory.exists()) {
            slaDirectory.mkdir();
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        FilePath slaDirectoryFilePath = new FilePath(slaDirectory);
        FilePath tmpZipFile = new FilePath(slaDirectoryFilePath, "runReport.zip");
        tmpZipFile.copyFrom(bais);
        bais.close();
        baos.close();
        tmpZipFile.unzip(slaDirectoryFilePath);
        FilePath slaFile = new FilePath(slaDirectoryFilePath, "RunReport.xml");
        slaFile.getBaseName();
        slaFile.renameTo(new FilePath(slaDirectoryFilePath, scenarioName + ".xml"));

        slaFile = new FilePath(slaDirectoryFilePath, scenarioName + ".xml");

        return slaFile;
    }
    return null;
}

From source file:com.clt.sub.controller.DriverAction.java

/**
 * ??// ww w .  java 2s.  c o m
 * 
 * @param request
 * @param files
 * @throws FileNotFoundException
 * @throws IOException
 */
private void uploadCardImg(HttpServletRequest request, CommonsMultipartFile[] files, TDriver driver)
        throws FileNotFoundException, IOException {
    if (files == null) {
        return;
    }
    for (int i = 0; i < files.length; i++) {
        System.out.println("fileName---------->" + files[i].getOriginalFilename());

        if (!files[i].isEmpty()) {
            int pre = (int) System.currentTimeMillis();
            // String source = request.getSession().getServletContext()
            // .getRealPath( "/" );
            String source = pictureService.getPathById(22);// ?
            if (!source.endsWith("/")) {
                source += "/";
            }
            if (StringUtils.isBlank(source)) {
                System.out.println("source??");
                return;
            }
            String path = source;
            File pathFile = new File(path);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            String jpgPath = new Date().getTime() + files[i].getOriginalFilename();
            // path += new Date().getTime() +
            // files[i].getOriginalFilename();
            path += jpgPath;
            // ?????
            FileOutputStream os = new FileOutputStream(path);
            // ?
            ByteArrayInputStream in = (ByteArrayInputStream) files[i].getInputStream();

            // ?
            int b = 0;
            while ((b = in.read()) != -1) {
                os.write(b);
            }
            os.flush();
            os.close();
            in.close();
            int finaltime = (int) System.currentTimeMillis();
            System.out.println(finaltime - pre);
            String imgPath = driver.getVcCardImgPath();// ??
            if (StringUtils.isBlank(imgPath)) {
                driver.setVcCardImgPath(jpgPath);
            } else {
                // share.setVcImgpath( imgPath + "," + path );
                imgPath = imgPath.substring(imgPath.lastIndexOf("/") + 1);// ?
                String existImgPath = source + imgPath;
                File imgFile = new File(existImgPath);
                if (imgFile.exists()) {
                    boolean isDel = imgFile.delete();
                    if (isDel) {
                        System.out.println("'" + imgPath + "'");
                    }
                }
                driver.setVcCardImgPath(jpgPath);
            }
        }
    }
}

From source file:com.clt.sub.controller.DriverAction.java

/**
 * ??//from w  w  w  . j a v a  2s  .c  om
 * 
 * @param request
 * @param files
 * @throws FileNotFoundException
 * @throws IOException
 */
private void uploadDriveImg(HttpServletRequest request, CommonsMultipartFile[] files, TDriver driver)
        throws FileNotFoundException, IOException {
    if (files == null) {
        return;
    }
    for (int i = 0; i < files.length; i++) {
        System.out.println("fileName---------->" + files[i].getOriginalFilename());

        if (!files[i].isEmpty()) {
            int pre = (int) System.currentTimeMillis();
            // String source = request.getSession().getServletContext()
            // .getRealPath( "/" );
            String source = pictureService.getPathById(22);// ?
            if (!source.endsWith("/")) {
                source += "/";
            }
            if (StringUtils.isBlank(source)) {
                System.out.println("source??");
                return;
            }
            String path = source;
            File pathFile = new File(path);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            String jpgPath = new Date().getTime() + files[i].getOriginalFilename();
            // path += new Date().getTime() +
            // files[i].getOriginalFilename();
            path += jpgPath;
            // ?????
            FileOutputStream os = new FileOutputStream(path);
            // ?
            ByteArrayInputStream in = (ByteArrayInputStream) files[i].getInputStream();

            // ?
            int b = 0;
            while ((b = in.read()) != -1) {
                os.write(b);
            }
            os.flush();
            os.close();
            in.close();
            int finaltime = (int) System.currentTimeMillis();
            System.out.println(finaltime - pre);
            String imgPath = driver.getVcDriveImgPath();// ??
            if (StringUtils.isBlank(imgPath)) {
                driver.setVcDriveImgPath(jpgPath);
            } else {
                // share.setVcImgpath( imgPath + "," + path );
                imgPath = imgPath.substring(imgPath.lastIndexOf("/") + 1);// ?
                String existImgPath = source + imgPath;
                File imgFile = new File(existImgPath);
                if (imgFile.exists()) {
                    boolean isDel = imgFile.delete();
                    if (isDel) {
                        System.out.println("'" + imgPath + "'");
                    }
                }
                driver.setVcDriveImgPath(jpgPath);
            }
        }
    }
}