Example usage for java.io BufferedInputStream available

List of usage examples for java.io BufferedInputStream available

Introduction

In this page you can find the example usage for java.io BufferedInputStream available.

Prototype

public synchronized int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:org.kuali.kra.s2s.service.PrintFormTest.java

@Test
public void testPrint() throws IOException {
    ProposalDevelopmentDocument document = new ProposalDevelopmentDocument();
    Organization performOrganization = new Organization();
    performOrganization.setOrganizationName("Espace");
    Rolodex rolodex = new Rolodex();
    rolodex.setAddressLine1("1290 Avenue of the Americas");
    rolodex.setAddressLine2("Suite 550");
    rolodex.setCity("New York");
    rolodex.setCounty("County");
    rolodex.setPostalCode("10104");
    rolodex.setState("NY");
    rolodex.setCountryCode("USA");

    performOrganization.setRolodex(rolodex);

    ProposalSite performSite = new ProposalSite();
    performSite.setOrganization(performOrganization);
    document.getDevelopmentProposal().setPerformingOrganization(performSite);

    List<ProposalSite> proList = new ArrayList<ProposalSite>();
    ProposalSite proposalSite = new ProposalSite();
    proposalSite.setRolodex(rolodex);// ww  w .  ja  va2 s.c o m
    proList.add(proposalSite);
    document.getDevelopmentProposal().setOtherOrganizations(proList);

    Narrative narrative = new Narrative();
    narrative.setModuleNumber(123);
    List<Narrative> naList = new ArrayList<Narrative>();

    NarrativeAttachment narrativeAttachment = new NarrativeAttachment();
    //InputStream inStream = getClass().getResourceAsStream("pdftestDoc4.pdf");
    File file = new File(S2STestUtils.ATT_DIR_PATH + "exercise5.pdf");
    InputStream inStream = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(inStream);
    byte[] narrativePdf = new byte[bis.available()];
    bis.read(narrativePdf);
    narrativeAttachment.setNarrativeData(narrativePdf);

    List<NarrativeAttachment> narrativeList = new ArrayList<NarrativeAttachment>();
    narrativeList.add(0, narrativeAttachment);
    narrative.setNarrativeTypeCode("40");
    narrative.setNarrativeAttachmentList(narrativeList);
    narrative.setFileName("OpportunityForm");
    naList.add(narrative);
    document.getDevelopmentProposal().setNarratives(naList);
    S2sOppForms forms = new S2sOppForms();
    forms.setOppNameSpace("http://apply.grants.gov/forms/RR_PerformanceSite-V1.0");
    List<S2sOppForms> oppForms = new ArrayList<S2sOppForms>();
    oppForms.add(forms);
    document.getDevelopmentProposal().setS2sOppForms(oppForms);
    PrintService printService = ((PrintService) KraServiceLocator.getService(PrintService.class));
    try {
        printService.printForm(document);
    } catch (S2SException e) {
        LOG.error(e.getMessage(), e);
    } catch (PrintingException pe) {
        LOG.error(pe.getMessage());
    }

}

From source file:org.growingstems.scouting.MatchSchedule.java

private String getSchedule(Context parent) {
    try {/*  w w w .  j  a  v  a 2 s .  co  m*/
        BufferedInputStream bis = new BufferedInputStream(parent.openFileInput(FILENAME));
        byte[] buffer = new byte[bis.available()];
        bis.read(buffer, 0, buffer.length);
        return new String(buffer);
    } catch (Exception e) {
        return "";
    }
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }/*w w  w  . java 2s  .  c o  m*/

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}

From source file:com.oneops.cms.crypto.CmsCryptoDES.java

private KeyParameter getSecretKeyFromFile() throws IOException, GeneralSecurityException {
    BufferedInputStream keystream = new BufferedInputStream(new FileInputStream(secretKeyFile));
    int len = keystream.available();
    if (len < MIN_DES_FILE_LENGTH) {
        keystream.close();/*from w  ww.j  a va  2s. c  om*/
        throw new EOFException(">>>> Bad DES file length = " + len);
    }
    byte[] keyhex = new byte[len];
    keystream.read(keyhex, 0, len);
    keystream.close();
    return new KeyParameter(Hex.decode(keyhex));
}

From source file:org.dynamicloud.wiztorage.reader.FileReaderImpl.java

/**
 * This method will read a file and every read chunk will be passed through File Reader Callback newChunk method.
 *
 * @param file               file to read
 * @param fileReaderCallback callback for every built chunk.
 * @throws org.dynamicloud.wiztorage.exception.FileReaderException when any error occurs.
 *//*from   ww  w.ja  v  a2s . com*/
@Override
public void readFile(File file, FileReaderCallback fileReaderCallback) throws FileReaderException {
    if (file == null) {
        throw new FileReaderException("File is null, this is an illegal argument.");
    }

    if (fileReaderCallback == null) {
        throw new FileReaderException("Callback is null, this is an illegal argument.");
    }

    StorageConfigurator configurator = StorageConfigurator.StorageConfiguratorInitializer.getConfigurator();

    int maxSizeFile = Integer.parseInt(configurator.getProperty("maxSizeFile"));

    if (file.length() == 0) {
        throw new FileReaderException("This file is empty");
    }

    if (file.length() > (maxSizeFile * 1024 * 1024)/*to bytes*/) {
        throw new FileReaderException("File size is greater than Max file size '" + maxSizeFile + "'.");
    }

    long bytesInBuffer = Integer.parseInt(configurator.getProperty("maxSizePerChunk")) * 1024
            * 1024/*to bytes*/;
    bytesInBuffer = file.length() < bytesInBuffer ? file.length() : bytesInBuffer;

    BufferedInputStream reader = null;
    try {
        reader = new BufferedInputStream(new FileInputStream(file));
        int index = 0;

        while (reader.available() != 0) {
            byte[] buffer = new byte[(int) bytesInBuffer];

            int read = reader.read(buffer);

            if (read <= 0) {
                break;
            }

            /**
             * Convert this content as based64
             */
            if (read < bytesInBuffer) {
                byte[] newBuffer = new byte[read];
                System.arraycopy(buffer, 0, newBuffer, 0, read);

                fileReaderCallback.newChunk(new String(Base64.encodeBase64(newBuffer), "UTF-8"), index++);
            } else {
                fileReaderCallback.newChunk(new String(Base64.encodeBase64(buffer), "UTF-8"), index++);
            }
        }
    } catch (IOException e) {
        throw new FileReaderException(e.getMessage());
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (Exception ignore) {
        }
    }
}

From source file:psef.handler.ProjectGetHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws PsefException {
    //1. get the project metadata
    try {//from   ww w . java 2s . co  m
        Connection conn = Connector.getConnection();
        docid = request.getParameter(Params.DOCID);
        if (docid == null || docid.length() == 0)
            throw new PsefException("Missing docid");
        String project = conn.getFromDb(Database.PROJECTS, docid);
        JSONObject jObj = (JSONObject) JSONValue.parse(project);
        String site_url = (String) jObj.get(JSONKeys.SITE_URL);
        // 2. create the temporary directory
        if (site_url != null) {
            File tempDir = new File(System.getProperty("java.io.tmpdir"));
            URL siteU = new URL(site_url);
            root = new File(tempDir, getLastPart(siteU));
            if (!root.exists())
                root.mkdir();
            URL current = new URL(site_url);
            String path = urlDiff(siteU, current);
            // 2. get the home page and parse it
            writeUrlContents(site_url, path);
            File archive = tarRoot();
            response.setContentType("application/gzip");
            ServletOutputStream sos = response.getOutputStream();
            byte[] buffer = new byte[BUF_SIZE];
            FileInputStream fis = new FileInputStream(archive);
            BufferedInputStream bis = new BufferedInputStream(fis, BUF_SIZE);
            while (bis.available() > 0) {
                int amt = bis.available();
                amt = (amt > BUF_SIZE) ? BUF_SIZE : amt;
                bis.read(buffer, 0, amt);
                sos.write(buffer, 0, amt);
            }
        } else
            throw new Exception("project doesn't have a site_url");
    } catch (Exception e) {
        throw new PsefException(e);
    }
}

From source file:id.nci.stm_9.ImportKeysListLoader.java

/**
 * Reads all PGPKeyRing objects from input
 * //from  ww w.  ja va 2s  .  com
 * @param keyringBytes
 * @return
 */
private void generateListOfKeyrings(InputData inputData) {
    PositionAwareInputStream progressIn = new PositionAwareInputStream(inputData.getInputStream());

    // need to have access to the bufferedInput, so we can reuse it for the possible
    // PGPObject chunks after the first one, e.g. files with several consecutive ASCII
    // armour blocks
    BufferedInputStream bufferedInput = new BufferedInputStream(progressIn);
    try {

        // read all available blocks... (asc files can contain many blocks with BEGIN END)
        while (bufferedInput.available() > 0) {
            InputStream in = PGPUtil.getDecoderStream(bufferedInput);
            PGPObjectFactory objectFactory = new PGPObjectFactory(in);

            // go through all objects in this block
            Object obj;
            while ((obj = objectFactory.nextObject()) != null) {
                Log.d("stm-9", "Found class: " + obj.getClass());

                if (obj instanceof PGPKeyRing) {
                    PGPKeyRing newKeyring = (PGPKeyRing) obj;
                    addToData(newKeyring);
                } else {
                    Log.e("stm-9", "Object not recognized as PGPKeyRing!");
                }
            }
        }
    } catch (Exception e) {
        Log.e("stm-9", "Exception on parsing key file!", e);
    }
}

From source file:com.teasoft.teavote.util.Signature.java

public boolean verifyFile(String pathToFile) throws FileNotFoundException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException, IOException, SignatureException, InvalidKeySpecException {
    File fileToVerify = new File(pathToFile);
    FileInputStream originalFileIs = new FileInputStream(fileToVerify);

    String dataPathToVerify = new ConfigLocation().getConfigPath() + File.separator + "dataToVerify.sql";
    File dataToVerify = new File(dataPathToVerify);
    FileOutputStream fw = new FileOutputStream(dataToVerify);

    //Read the caution message and signature out
    byte[] cautionMsg = new byte[175]; //Caution section occupies 175 bytes
    originalFileIs.read(cautionMsg);/* w  w w . jav a  2s .  c  om*/

    //Read and Write the rest of the bytes in original file into data to verify
    byte[] buffer = new byte[1024];
    int nRead = 0;
    while ((nRead = originalFileIs.read(buffer)) != -1) {
        fw.write(buffer, 0, nRead);
    }
    //Close originalFileIs and dataToVerify
    originalFileIs.close();
    fw.close();

    //Get signature from caution/signation message
    byte[] sigToVerify = new byte[64];
    for (int i = 0, j = 0; i < cautionMsg.length; i++) {
        if (i >= 106 && i < 170) {
            sigToVerify[j++] = cautionMsg[i];
        }
    }
    //decode signature bytes
    sigToVerify = Base64.decodeBase64(sigToVerify);
    //        sigToVerify = com.sun.org.apache.xml.internal.security.utils.Base64.decode(sigToVerify);

    java.security.Signature sig = java.security.Signature.getInstance("SHA1withDSA", "SUN");
    sig.initVerify(getPublicKey());
    //Get digital signature
    FileInputStream datafis = new FileInputStream(dataPathToVerify);
    BufferedInputStream bufin = new BufferedInputStream(datafis);
    int len;
    while (bufin.available() != 0) {
        len = bufin.read(buffer);
        sig.update(buffer, 0, len);
    }
    bufin.close();
    //Delete fileToVerify
    dataToVerify.delete();
    return sig.verify(sigToVerify);

}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Add root certificates from an input stream.
 * /*from  w w w.j a va2  s. co  m*/
 * @param in
 *            input
 * @throws CertificateException
 *             on error
 * @throws IOException
 *             on I/O error
 */
public void addRootCertificates(InputStream in) throws CertificateException, IOException {
    try {
        BufferedInputStream bufferedIn = new BufferedInputStream(in);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bufferedIn.available() > 0) {
            Certificate cert = cf.generateCertificate(bufferedIn);
            addRootCertificate((X509Certificate) cert);
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Add root certificates from an input stream.
 * //from ww w  . j  a  v  a 2  s  .  c om
 * @param in
 *            input
 * @throws CertificateException
 *             on error
 * @throws IOException
 *             on I/O error
 */
public void addIntermediateCertificate(InputStream in) throws CertificateException, IOException {
    try {
        BufferedInputStream bufferedIn = new BufferedInputStream(in);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bufferedIn.available() > 0) {
            Certificate cert = cf.generateCertificate(bufferedIn);
            addIntermediateCertificate((X509Certificate) cert);
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}