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:com.sharksharding.util.web.http.QueryViewServlet.java

/**
 * ????/*from www . ja  v a2 s.c  o m*/
 * 
 * @author gaoxianglong
 * 
 * @param path
 *            ?
 * 
 * @return byte[] ??
 */
protected byte[] initView(String path) {
    byte[] value = null;
    BufferedInputStream reader = null;
    try {
        reader = new BufferedInputStream(QueryViewServlet.class.getClassLoader().getResourceAsStream(path));
        value = new byte[reader.available()];
        reader.read(value);
    } catch (IOException e) {
        throw new FileNotFoundException("can not find config");
    } finally {
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return value;
}

From source file:raymond.mockftpserver.S3CachedFtpServer.java

private void readKeyFile(File _accessFile) throws IOException, EncryptionException {
    logger.info("@@ reading cypher from:" + _accessFile);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(_accessFile));
    int len = in.available();
    byte[] buffer = new byte[len];
    in.read(buffer);/*  ww w  . j  a va  2s. c o m*/
    in.close();
    logger.info("@@ len read is:" + len);

    byte[] cleartext;

    Encryptor crypt = new ThreeDESEncryptor(chave + keyBase);
    cleartext = crypt.decrypt(buffer);

    int nameLen = cleartext[0];
    int accessKeyLen = cleartext[1];
    int secretKeyLen = cleartext.length - 2 - nameLen - accessKeyLen;
    if (secretKeyLen % 2 != 0) {
        throw new RuntimeException("internal error: secret key has odd bytecount");
    }

    byte[] nameRaw = new byte[nameLen];
    for (int i = 0; i < nameLen; i++) {
        nameRaw[i] = cleartext[i + 2];
    }
    String nameCheck = new String(nameRaw, charset);
    if (!chave.equals(nameCheck)) {
        throw new RuntimeException("internal error: secret key name mismatch");
    }

    // Get the Access Key
    int offset = 2 + nameLen;
    byte[] accessKeyRaw = new byte[accessKeyLen];
    for (int i = 0; i < accessKeyLen; i++) {
        accessKeyRaw[i] = cleartext[i + offset];
    }
    apiKey = new String(accessKeyRaw, charset);

    // Get the Secret Key
    char[] secretKey = new char[secretKeyLen / 2];
    offset += accessKeyLen;
    for (int i = 0; i < secretKeyLen / 2; i++) {
        int spot = i + i + offset;
        char ch = (char) ((cleartext[spot] << 8) + cleartext[spot + 1]);
        secretKey[i] = ch;
    }
    apiKeySecret = new String(secretKey);
}

From source file:org.sufficientlysecure.keychain.ui.adapter.ImportKeysListLoader.java

/**
 * Reads all PGPKeyRing objects from input
 *
 * @param inputData/* w ww.  j  a va  2  s .c  o m*/
 * @return
 */
private void generateListOfKeyrings(InputData inputData) {

    boolean isEmpty = true;

    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
    // armor blocks
    BufferedInputStream bufferedInput = new BufferedInputStream(progressIn);
    try {

        // read all available blocks... (asc files can contain many blocks with BEGIN END)
        while (bufferedInput.available() > 0) {
            // todo deal with non-keyring objects?
            List<UncachedKeyRing> rings = UncachedKeyRing.fromStream(bufferedInput);
            for (UncachedKeyRing key : rings) {
                ImportKeysListEntry item = new ImportKeysListEntry(getContext(), key);
                mData.add(item);
                mParcelableRings.put(key.getMasterKeyId(), new ParcelableKeyRing(key.getEncoded()));
                isEmpty = false;
            }
        }
    } catch (Exception e) {
        Log.e(Constants.TAG, "Exception on parsing key file!", e);
        mEntryListWrapper = new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>(mData, e);
    }

    if (isEmpty) {
        Log.e(Constants.TAG, "File has no content!", new FileHasNoContent());
        mEntryListWrapper = new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>(mData,
                new FileHasNoContent());
    }
}

From source file:org.sufficientlysecure.keychain.ui.widget.ImportKeysListLoader.java

/**
 * Similar to PGPMain.importKeyRings/*from   w w  w .java  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(Constants.TAG, "Found class: " + obj.getClass());

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

From source file:de.betterform.xml.xforms.ui.UploadTest.java

/**
 * Tests ui element state.//from   ww w . j  a  va2 s . c  o m
 *
 * @throws Exception if any error occurred during the test.
 */
public void testUploadBase64() throws Exception {
    Upload upload = (Upload) this.xformsProcesssorImpl.getContainer().lookup("upload-base64");
    upload.getTarget().addEventListener(XFormsEventNames.VALUE_CHANGED, this.valueChangedListener, false);

    String filename = "UploadTest.xhtml";
    String mediatype = "application/xhtml+xml";

    BufferedInputStream bis = new BufferedInputStream(getClass().getResourceAsStream(filename));
    byte[] data = new byte[bis.available()];
    bis.read(data);
    upload.setValue(data, filename, mediatype);
    upload.getTarget().removeEventListener(XFormsEventNames.VALUE_CHANGED, this.valueChangedListener, false);

    assertEquals(new String(data), new String(Base64.decodeBase64(((String) upload.getValue()).getBytes())));
    assertEquals(filename, upload.getFilename().getValue());
    assertEquals(mediatype, upload.getMediatype().getValue());

    ModelItem modelItem = upload.getModel().getInstance(upload.getInstanceId())
            .getModelItem(upload.getInstanceNode());
    assertEquals(filename, modelItem.getFilename());
    assertEquals(mediatype, modelItem.getMediatype());

    assertEquals("upload-base64", this.valueChangedListener.getId());
}

From source file:de.betterform.xml.xforms.ui.UploadTest.java

/**
 * Tests ui element state./*from  w  ww .j av a 2  s .  c  om*/
 *
 * @throws Exception if any error occurred during the test.
 */
public void testUploadHex() throws Exception {
    Upload upload = (Upload) this.xformsProcesssorImpl.getContainer().lookup("upload-hex");
    upload.getTarget().addEventListener(XFormsEventNames.VALUE_CHANGED, this.valueChangedListener, false);

    String filename = "UploadTest.xhtml";
    String mediatype = "application/xhtml+xml";

    BufferedInputStream bis = new BufferedInputStream(getClass().getResourceAsStream(filename));
    byte[] data = new byte[bis.available()];
    bis.read(data);
    upload.setValue(data, filename, mediatype);
    upload.getTarget().removeEventListener(XFormsEventNames.VALUE_CHANGED, this.valueChangedListener, false);

    assertEquals(new String(data), new String(Hex.decodeHex(((String) upload.getValue()).toCharArray())));
    assertEquals(filename, upload.getFilename().getValue());
    assertEquals(mediatype, upload.getMediatype().getValue());

    ModelItem modelItem = upload.getModel().getInstance(upload.getInstanceId())
            .getModelItem(upload.getInstanceNode());
    assertEquals(filename, modelItem.getFilename());
    assertEquals(mediatype, modelItem.getMediatype());

    assertEquals("upload-hex", this.valueChangedListener.getId());
}

From source file:org.thialfihar.android.apg.ui.adapter.ImportKeysListLoader.java

/**
 * Reads all PGPKeyRing objects from input
 *
 * @param inputData/*from  w  w w. j a v  a2s.  c  om*/
 * @return
 */
private void generateListOfKeyrings(InputData inputData) {
    boolean isEmpty = true;
    int nonPgpCounter = 0;

    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
    // armor blocks
    BufferedInputStream bufferedInput = new BufferedInputStream(progressIn);
    try {

        // read all available blocks... (asc files can contain many blocks with BEGIN END)
        while (bufferedInput.available() > 0) {
            isEmpty = false;
            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(Constants.TAG, "Found class: " + obj.getClass());

                if (obj instanceof PGPKeyRing) {
                    PGPKeyRing newKeyring = (PGPKeyRing) obj;
                    addToData(newKeyring);
                } else {
                    Log.e(Constants.TAG, "Object not recognized as PGPKeyRing!", new Exception());
                    nonPgpCounter++;
                }
            }
        }
    } catch (Exception e) {
        Log.e(Constants.TAG, "Exception on parsing key file!", e);
        mEntryListWrapper = new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>(mData, e);
        nonPgpCounter = 0;
    }

    if (isEmpty) {
        Log.e(Constants.TAG, "File has no content!", new FileHasNoContent());
        mEntryListWrapper = new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>(mData,
                new FileHasNoContent());
    }

    if (nonPgpCounter > 0) {
        mEntryListWrapper = new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>(mData,
                new NonPgpPartException(nonPgpCounter));
    }
}

From source file:org.openiot.gsn.wrappers.GPSGenerator.java

public boolean initialize() {
    setName("GPSGenerator-Thread" + (++threadCounter));
    AddressBean addressBean = getActiveAddressBean();
    if (addressBean.getPredicateValue("rate") != null) {
        samplingRate = ParamParser.getInteger(addressBean.getPredicateValue("rate"), DEFAULT_SAMPLING_RATE);
        if (samplingRate <= 0) {
            logger.warn(/* ww w  .  ja  va  2s . com*/
                    "The specified >sampling-rate< parameter for the >MemoryMonitoringWrapper< should be a positive number.\nGSN uses the default rate ("
                            + DEFAULT_SAMPLING_RATE + "ms ).");
            samplingRate = DEFAULT_SAMPLING_RATE;
        }
    }
    if (addressBean.getPredicateValue("picture") != null) {
        String picture = addressBean.getPredicateValue("picture");
        File pictureF = new File(picture);
        if (!pictureF.isFile() || !pictureF.canRead()) {
            logger.warn("The GPSGenerator can't access the specified picture file. Initialization failed.");
            return false;
        }
        try {
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(pictureF));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4 * 1024];
            while (fis.available() > 0)
                outputStream.write(buffer, 0, fis.read(buffer));
            fis.close();
            this.picture = outputStream.toByteArray();
            outputStream.close();
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage(), e);
            return false;
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
    } else {
        logger.warn("The >picture< parameter is missing from the GPSGenerator wrapper.");
        return false;
    }
    ArrayList<DataField> output = new ArrayList<DataField>();
    for (int i = 0; i < FIELD_NAMES.length; i++)
        output.add(new DataField(FIELD_NAMES[i], FIELD_TYPES_STRING[i], FIELD_DESCRIPTION[i]));
    outputStrcture = output.toArray(new DataField[] {});
    return true;
}

From source file:gsn.wrappers.GPSGenerator.java

public boolean initialize() {
    AddressBean addressBean = getActiveAddressBean();
    if (addressBean.getPredicateValue("rate") != null) {
        samplingRate = ParamParser.getInteger(addressBean.getPredicateValue("rate"), DEFAULT_SAMPLING_RATE);
        if (samplingRate <= 0) {
            logger.warn(/*from w ww .  j  a  v  a 2s  .  com*/
                    "The specified >sampling-rate< parameter for the >MemoryMonitoringWrapper< should be a positive number.\nGSN uses the default rate ("
                            + DEFAULT_SAMPLING_RATE + "ms ).");
            samplingRate = DEFAULT_SAMPLING_RATE;
        }
    }
    if (addressBean.getPredicateValue("picture") != null) {
        String picture = addressBean.getPredicateValue("picture");
        File pictureF = new File(picture);
        if (!pictureF.isFile() || !pictureF.canRead()) {
            logger.warn("The GPSGenerator can't access the specified picture file. Initialization failed.");
            return false;
        }
        try {
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(pictureF));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4 * 1024];
            while (fis.available() > 0)
                outputStream.write(buffer, 0, fis.read(buffer));
            fis.close();
            this.picture = outputStream.toByteArray();
            outputStream.close();
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage(), e);
            return false;
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
    } else {
        logger.warn("The >picture< parameter is missing from the GPSGenerator wrapper.");
        return false;
    }
    ArrayList<DataField> output = new ArrayList<DataField>();
    for (int i = 0; i < FIELD_NAMES.length; i++)
        output.add(new DataField(FIELD_NAMES[i], FIELD_TYPES_STRING[i], FIELD_DESCRIPTION[i]));
    outputStrcture = output.toArray(new DataField[] {});
    return true;
}

From source file:org.b3log.solo.processor.CaptchaProcessor.java

/**
 * Loads captcha.//from   w  ww  .ja va  2  s .  c om
 */
private synchronized void loadCaptchas() {
    LOGGER.info("Loading captchas....");

    try {
        captchas = new Image[CAPTCHA_COUNT];

        ZipFile zipFile;

        if (RuntimeEnv.LOCAL == Latkes.getRuntimeEnv()) {
            final InputStream inputStream = SoloServletListener.class.getClassLoader()
                    .getResourceAsStream("captcha_static.zip");
            final File file = File.createTempFile("b3log_captcha_static", null);
            final OutputStream outputStream = new FileOutputStream(file);

            IOUtils.copy(inputStream, outputStream);
            zipFile = new ZipFile(file);

            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        } else {
            final URL captchaURL = SoloServletListener.class.getClassLoader().getResource("captcha_static.zip");

            zipFile = new ZipFile(captchaURL.getFile());
        }

        final Enumeration<? extends ZipEntry> entries = zipFile.entries();

        int i = 0;

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();

            final BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    zipFile.getInputStream(entry));
            final byte[] captchaCharData = new byte[bufferedInputStream.available()];

            bufferedInputStream.read(captchaCharData);
            bufferedInputStream.close();

            final Image image = IMAGE_SERVICE.makeImage(captchaCharData);

            image.setName(entry.getName().substring(0, entry.getName().lastIndexOf('.')));

            captchas[i] = image;

            i++;
        }

        zipFile.close();
    } catch (final Exception e) {
        LOGGER.error("Can not load captchs!");

        throw new IllegalStateException(e);
    }

    LOGGER.info("Loaded captch images");
}