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:com.espringtran.compressor4j.processor.TarProcessor.java

/**
 * Read from compressed file/*  ww w.  j  a va2 s . co  m*/
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    TarArchiveInputStream ais = new TarArchiveInputStream(bais);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        TarArchiveEntry entry = ais.getNextTarEntry();
        while (entry != null && entry.getSize() > 0) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = ais.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = ais.read(buffer);
            }
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = ais.getNextTarEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        ais.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}

From source file:org.apache.hadoop.hbase.crosssite.CrossSiteZNodes.java

/**
 * Lists the descriptors of all the cross site tables with the pattern.
 * /*from www.j  a  va  2  s .c o m*/
 * @param pattern
 * @return
 * @throws KeeperException
 * @throws IOException
 */
public HTableDescriptor[] listTableDescs(Pattern pattern) throws KeeperException, IOException {
    List<HTableDescriptor> htds = Collections.emptyList();
    List<String> tableNames = listTables();
    if (tableNames != null && !tableNames.isEmpty()) {
        htds = new ArrayList<HTableDescriptor>();
        for (String tableName : tableNames) {
            if (pattern == null || pattern.matcher(tableName).matches()) {
                byte[] data = ZKUtil.getData(this.zkw, getTableDescZNode(tableName));
                if (data != null) {
                    ByteArrayInputStream stream = new ByteArrayInputStream(data);
                    DataInput in = new DataInputStream(stream);
                    HTableDescriptor htd = new HTableDescriptor();
                    htd.readFields(in);
                    stream.close();
                    htds.add(htd);
                }
            }
        }
    }
    return htds.toArray(new HTableDescriptor[0]);
}

From source file:com.espringtran.compressor4j.processor.CpioProcessor.java

/**
 * Read from compressed file//ww w.j a v  a  2s .  com
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    CpioArchiveInputStream ais = new CpioArchiveInputStream(bais);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        CpioArchiveEntry entry = ais.getNextCPIOEntry();
        while (entry != null && entry.getSize() > 0) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = ais.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = ais.read(buffer);
            }
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = ais.getNextCPIOEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        ais.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}

From source file:org.jlibrary.core.jcr.modules.JCRImportExportModule.java

public void importRepository(Ticket ticket, byte[] zippedContent, String name)
        throws RepositoryAlreadyExistsException, RepositoryException, SecurityException {

    try {/*from  ww  w.j a  v a2 s . c  om*/

        if (!ticket.getUser().isAdmin()) {
            throw new SecurityException(SecurityException.NOT_ENOUGH_PERMISSIONS);
        }

        javax.jcr.Session systemSession = SessionManager.getInstance().getSystemSession();
        WorkspaceImpl workspace = checkWorkspaceExists(name, systemSession);
        // Always change to lowercase
        name = name.toLowerCase();
        workspace.createWorkspace(name);

        javax.jcr.Repository repository = SessionManager.getInstance().getRepository();
        SimpleCredentials creds = new SimpleCredentials(
                JLibraryProperties.getProperty(JLibraryProperties.JLIBRARY_SYSTEM_USERNAME, "username"),
                JLibraryProperties.getProperty(JLibraryProperties.JLIBRARY_SYSTEM_PASSWORD, "password")
                        .toCharArray());

        systemSession = repository.login(creds, name);

        byte[] content = unzipContent(zippedContent);

        // First read the header
        int i = 0;
        while (content[i] != '*') {
            i++;
        }
        i++;
        byte[] header = new byte[i];
        System.arraycopy(content, 0, header, 0, i);
        String lengthString = new String(header);
        int contentLength = Integer.parseInt(lengthString.substring(0, lengthString.length() - 1));

        // Now, load root content

        byte[] rootContent = new byte[contentLength];
        System.arraycopy(content, i, rootContent, 0, contentLength);
        rootContent = filterForCompatibility(rootContent);
        ByteArrayInputStream bais1 = new ByteArrayInputStream(rootContent);

        // Now load system content
        byte[] systemContent = new byte[content.length - contentLength - header.length];
        System.arraycopy(content, header.length + contentLength, systemContent, 0, systemContent.length);
        systemContent = filterForCompatibility(systemContent);
        ByteArrayInputStream bais2 = new ByteArrayInputStream(systemContent);

        systemSession.importXML("/", bais1, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

        systemSession.importXML("/", bais2, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

        checkCustomProperties(systemSession);

        bais1.close();
        bais2.close();

        systemSession.save();

        // Finally check versions compatibility
        VersionChecker checker = new VersionChecker();
        checker.checkSession(systemSession);
    } catch (ConfigurationException ce) {
        //TODO: Remove this catch block when Jackrabbit supports workspace deletes
        throw new RecentlyRemovedRepositoryException();
    } catch (RepositoryAlreadyExistsException raee) {
        throw raee;
    } catch (SecurityException se) {
        throw se;
    } catch (AccessDeniedException e) {
        logger.error(e.getMessage(), e);
        throw new SecurityException(e);
    } catch (LoginException e) {
        logger.error(e.getMessage(), e);
        throw new SecurityException(e);
    } catch (RepositoryException re) {
        throw re;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException(e);
    }
}

From source file:com.dv.Utils.DvFileUtil.java

/**
 * ??byte[].//from  w ww  .  ja v a2  s. com
 * @param imgByte byte[]
 * @param fileName ?????.jpg
 * @param type ???AbConstant
 * @param newWidth 
 * @param newHeight 
 * @return Bitmap 
 */
public static Bitmap getBitmapFormByte(byte[] imgByte, String fileName, int type, int newWidth, int newHeight) {
    FileOutputStream fos = null;
    DataInputStream dis = null;
    ByteArrayInputStream bis = null;
    Bitmap b = null;
    File file = null;
    try {
        if (imgByte != null) {

            file = new File(imageDownFullDir + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            int readLength = 0;
            bis = new ByteArrayInputStream(imgByte);
            dis = new DataInputStream(bis);
            byte[] buffer = new byte[1024];

            while ((readLength = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLength);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            fos.flush();

            b = getBitmapFromSD(file, type, newWidth, newHeight);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (Exception e) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
    return b;
}

From source file:caesar.feng.framework.utils.ACache.java

/**
 * ? Serializable?//w  w  w .j  a  v  a 2 s.  c  om
 * 
 * @param key
 * @return Serializable ?
 */
public Object getAsObject(String key) {
    byte[] data = getAsBinary(key);
    if (data != null) {
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        try {
            bais = new ByteArrayInputStream(data);
            ois = new ObjectInputStream(bais);
            Object reObject = ois.readObject();
            return reObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bais != null)
                    bais.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ois != null)
                    ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;

}

From source file:org.alfresco.bm.api.v1.RestAPITest.java

/**
 * Checks the test application APIs for retrieving test results.
 *//*from  ww w .j av  a 2  s .  co m*/
@Test
public synchronized void testScenario07() throws Exception {
    /*
     * In-memory byte[] are used because we know the size of the documents
     * will be manageable.
     */

    executeTestRun("T07", "A test for scenario 07.", "01", "Scenario 07 - Run 01");

    // Get report for test run that does not exist
    try {
        ResultsRestAPI resultsAPI = api.getTestRunResultsAPI("T07MISSING", "01");
        resultsAPI.getReportCSV();
        Assert.fail("Expected exception regarding missing test.");
    } catch (WebApplicationException e) {
        assertEquals(Status.NOT_FOUND.getStatusCode(), e.getResponse().getStatus());
    }

    ResultsRestAPI resultsAPI = api.getTestRunResultsAPI("T07", "01");

    // Get the results CSV
    StreamingOutput csvOutput = resultsAPI.getReportCSV();
    ByteArrayOutputStream csvBos = new ByteArrayOutputStream();
    csvBos.close();
    csvOutput.write(csvBos);
    String csvResults = new String(csvBos.toByteArray());
    // Check
    assertTrue(csvResults.contains("Data:,bm21-data.T07.01.results"));
    assertTrue(csvResults.contains("Started"));
    assertTrue(csvResults.contains("Finished"));
    assertTrue(csvResults.contains("Duration"));

    // Get the JSON results
    String chartJson = resultsAPI.getTimeSeriesResults(0L, "seconds", 1, 5, false);
    assertTrue(chartJson.startsWith("[ { \"time\" : "));
    assertTrue(chartJson.contains("[ { \"time\" : "));
    assertTrue(chartJson.contains("000 , \"name\" : \"start\" , \"mean\" : "));
    assertTrue(chartJson.endsWith(" , \"fail\" : 0 , \"failPerSec\" : 0.0}]"));

    // Get the XLSX report
    StreamingOutput xlsxOutput = resultsAPI.getReportXLSX();
    ByteArrayOutputStream xlsxBos = new ByteArrayOutputStream();
    xlsxOutput.write(xlsxBos);
    xlsxBos.close();
    ByteArrayInputStream xlsxBis = new ByteArrayInputStream(xlsxBos.toByteArray());
    XSSFWorkbook xlsxWorkbook = new XSSFWorkbook(xlsxBis);
    xlsxBis.close();
    // Write it to a temp file just for fun
    File xlsxFile = File.createTempFile(UUID.randomUUID().toString(), ".xlsx");
    FileOutputStream xlsxFos = new FileOutputStream(xlsxFile);
    xlsxWorkbook.write(xlsxFos);
    xlsxFos.close();
    logger.info("XLSX report found here: " + xlsxFile);

    // Check
    POIXMLProperties xlsxProperties = xlsxWorkbook.getProperties();
    CoreProperties xlsxCoreProperties = xlsxProperties.getCoreProperties();
    Assert.assertNotNull("No XLSX description: " + xlsxFile, xlsxCoreProperties.getDescription());
    Assert.assertTrue("Title in XLSX must contain test run FQN: " + xlsxFile,
            xlsxCoreProperties.getTitle().contains("T07.01"));
    Assert.assertTrue("Description in XLSX must contain test name and description: " + xlsxFile,
            xlsxCoreProperties.getDescription().contains("A test for scenario 07."));
    Assert.assertTrue("Description in XLSX must contain test name and description." + xlsxFile,
            xlsxCoreProperties.getDescription().contains("Scenario 07 - Run 01"));
    xlsxWorkbook.close();
}

From source file:org.kalypso.ogc.gml.GisTemplateMapModell.java

public synchronized void saveGismapTemplate(final GM_Envelope bbox, final String srsName,
        IProgressMonitor monitor, final IFile file) throws CoreException {
    if (monitor == null)
        monitor = new NullProgressMonitor();

    ByteArrayInputStream bis = null;
    try {// ww  w .ja va  2  s .c  o  m
        final IKalypsoTheme[] themes = m_modell.getAllThemes();
        monitor.beginTask(Messages.getString("org.kalypso.ogc.gml.GisTemplateMapModell.10"), //$NON-NLS-1$
                themes.length * 1000 + 1000);

        final Gismapview gismapview = createGismapTemplate(bbox, srsName, new SubProgressMonitor(monitor, 100));

        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        GisTemplateHelper.saveGisMapView(gismapview, bos, file.getCharset());
        bos.close();
        bis = new ByteArrayInputStream(bos.toByteArray());
        if (file.exists())
            file.setContents(bis, false, true, new SubProgressMonitor(monitor, 900));
        else
            file.create(bis, false, new SubProgressMonitor(monitor, 900));

        bis.close();
    } catch (final Throwable e) {
        e.printStackTrace();
        throw new CoreException(StatusUtilities.statusFromThrowable(e,
                Messages.getString("org.kalypso.ogc.gml.GisTemplateMapModell.11"))); //$NON-NLS-1$
    } finally {
        monitor.done();

        IOUtils.closeQuietly(bis);
    }
}

From source file:com.betfair.testing.utils.cougar.manager.HttpPageManager.java

public boolean clickOnLink(HttpPageBean bean, String linkType, String linkName) {

    // Get all the links on the page that match the input type and name (using a regex)
    getPage(bean);//from  ww w  . j a  va 2  s .  c o m
    ByteArrayInputStream responseStream = null;
    Document d = null;
    try {
        responseStream = new ByteArrayInputStream(bean.getBuffer());
        d = httpHelpers.parseInputStream(responseStream);

        String regex = "/ViewObjectRes//.*" + linkType + ".*" + linkName;
        List<String> links = httpHelpers.getAnchoredLinks(d, regex);
        String linkString = links.get(0);

        if (linkString == null) { // request link can't be found on page
            return false;
        }

        // Set request URL to that of the link to be clicked (trimming any trailing /)
        String currentPageURL = bean.getRequestedURL();
        if (currentPageURL.endsWith("/")) {
            currentPageURL = currentPageURL.substring(0, currentPageURL.length() - 1);
        }
        bean.setRequestedURL(currentPageURL + linkString);

        // Reset flag and get linked page
        bean.setPageLoaded(false);
        getPage(bean);
        return bean.getPageLoaded();
    } finally {
        if (responseStream != null) {
            try {
                responseStream.close();
            } catch (IOException e) {
                // log
            }
        }
    }
}

From source file:org.alfresco.bm.api.v1.RestAPITest.java

/**
 * Extra data creation and export of XSLX Workbook
 * //from  w w w.  j  a v a 2  s .co m
 * @throws Exception
 */
@Test
public synchronized void testScenario11() throws Exception {
    // test definitions and extra data sheets
    String test = "T11";
    String run = "01";
    String driver = UUID.randomUUID().toString();
    String sheet1 = "extra.data.sheet1";
    String sheet2 = "extra.data.sheet2";
    String sheet3 = "extra.data.sheet3";
    String[] fieldNames = { "tf1", "tf2", "tf3", "tf4", "tf5" };
    String[] descriptions = { "Test Field 1", "Test Field 2", "Test Field 3", "Test Field 4", "Test Field 5" };
    String[] values = new String[5];

    executeTestRun(test, "A test for scenario 11.", run, "Scenario 11 - Run 01");

    // get the extra data report service
    DataReportService reportService = this.testRunServicesCache.getDataReportService(test, run);
    assertNotNull(reportService);

    // create a random value array
    for (int i = 0; i < 5; i++) {
        values[i] = UUID.randomUUID().toString();
    }

    // append some extra data and a description
    reportService.appendData(driver, test, run, sheet1, fieldNames, values);
    reportService.appendData(driver, test, run, sheet2, fieldNames, values);
    reportService.appendData(driver, test, run, sheet2, fieldNames, values);
    reportService.appendData(driver, test, run, sheet3, fieldNames, values);
    reportService.appendData(driver, test, run, sheet3, fieldNames, values);
    reportService.appendData(driver, test, run, sheet3, fieldNames, values);
    reportService.setDescription(driver, test, run, sheet3, fieldNames, descriptions);

    // create and download an XSLX
    ResultsRestAPI resultsAPI = api.getTestRunResultsAPI(test, run);
    StreamingOutput xlsxOutput = resultsAPI.getReportXLSX();
    ByteArrayOutputStream xlsxBos = new ByteArrayOutputStream();
    xlsxOutput.write(xlsxBos);
    xlsxBos.close();
    ByteArrayInputStream xlsxBis = new ByteArrayInputStream(xlsxBos.toByteArray());
    XSSFWorkbook xlsxWorkbook = new XSSFWorkbook(xlsxBis);
    xlsxBis.close();
    File xlsxFile = File.createTempFile(UUID.randomUUID().toString(), ".xlsx");
    FileOutputStream xlsxFos = new FileOutputStream(xlsxFile);
    xlsxWorkbook.write(xlsxFos);
    xlsxFos.close();

    // validate data in DB
    assertNull("Expected no description row for sheet 1, but found one?",
            reportService.getDescription(null, test, run, sheet1));
    assertNull("Expected no description row for sheet 2, but found one?",
            reportService.getDescription(null, test, run, sheet2));
    List<String> descList = reportService.getDescription(null, test, run, sheet3);
    assertNotNull("Expected a description row for sheet 3, but can't find any ...", descList);
    int count = 0;
    for (String desc : descList) {
        assertEquals(
                "Description of sheet 3 mismatch. Expected '" + descriptions[count] + "' found '" + desc + "'.",
                descriptions[count++], desc);
    }

    // validate number of sheets
    String[] sheetNames = reportService.getSheetNames(null, test, run);
    assertEquals("Expected 3 sheets of extra data, found: " + sheetNames.length, 3, sheetNames.length);

    // validate number of entries for each extra data
    int countTestEntries = 0;
    for (int j = 0; j < 3; j++) {
        DBCursor dbCursor = reportService.getData(null, test, run, sheetNames[j]);
        while (null != dbCursor && dbCursor.hasNext()) {
            List<String> valuesFromMongo = reportService.getNextValueRow(dbCursor);
            countTestEntries++;
            assertEquals("Expected 5 columns in extra data, found: " + valuesFromMongo.size(), 5,
                    valuesFromMongo.size());
        }
    }
    assertEquals("Expected 6 lines of extra data ... found: " + countTestEntries, 6, countTestEntries);

    // delete test
    api.deleteTest(test, true);

    // validate
    assertNull("Sheet names expected to be empty.", reportService.getSheetNames(null, test, run));
    assertNull("Description of sheet 3 expected to be empty.",
            reportService.getDescription(null, test, run, sheet3));

    // clean-up: delete XLSX file
    xlsxWorkbook.close();
    xlsxFile.delete();
}