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.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private KeyStore loadSecretToKeyStore(SecretBundle secret, String secretPassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    ByteArrayInputStream secretStream = new ByteArrayInputStream(_base64.decode(secret.value()));
    KeyStore keyStore = KeyStore.getInstance(PKCS12);
    keyStore.load(secretStream, secretPassword.toCharArray());
    secretStream.close();
    return keyStore;
}

From source file:org.alfresco.encoding.BomCharactersetFinder.java

/**
 * Just searches the Byte Order Marker, i.e. the first three characters for a sign of
 * the encoding./*from  w w  w.j  ava  2  s.com*/
 */
protected Charset detectCharsetImpl(byte[] buffer) throws Exception {
    Charset charset = null;
    ByteArrayInputStream bis = null;
    try {
        bis = new ByteArrayInputStream(buffer);
        bis.mark(3);
        char[] byteHeader = new char[3];
        InputStreamReader in = new InputStreamReader(bis);
        int bytesRead = in.read(byteHeader);
        bis.reset();

        if (bytesRead < 2) {
            // ASCII
            charset = Charset.forName("Cp1252");
        } else if (byteHeader[0] == 0xFE && byteHeader[1] == 0xFF) {
            // UCS-2 Big Endian
            charset = Charset.forName("UTF-16BE");
        } else if (byteHeader[0] == 0xFF && byteHeader[1] == 0xFE) {
            // UCS-2 Little Endian
            charset = Charset.forName("UTF-16LE");
        } else if (bytesRead >= 3 && byteHeader[0] == 0xEF && byteHeader[1] == 0xBB && byteHeader[2] == 0xBF) {
            // UTF-8
            charset = Charset.forName("UTF-8");
        } else {
            // No idea
            charset = null;
        }
        // Done
        return charset;
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (Throwable e) {
            }
        }
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Looks if the data is compressed and decompresses it if necessary
 *///from   w  ww . jav a 2  s  .c  o  m
public Part decompressData(Part part, AS2Message message) throws Exception {
    Part compressedPart = this.getCompressedEmbeddedPart(part);
    if (compressedPart == null) {
        return (part);
    }
    SMIMECompressed compressed = null;
    if (compressedPart instanceof MimeBodyPart) {
        compressed = new SMIMECompressed((MimeBodyPart) compressedPart);
    } else {
        compressed = new SMIMECompressed((MimeMessage) compressedPart);
    }
    byte[] decompressedData = compressed.getContent();
    ((AS2MessageInfo) message.getAS2Info()).setCompressionType(AS2Message.COMPRESSION_ZLIB);
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("data.compressed.expanded",
                        new Object[] { message.getAS2Info().getMessageId(),
                                AS2Tools.getDataSizeDisplay(part.getSize()),
                                AS2Tools.getDataSizeDisplay(decompressedData.length) }),
                message.getAS2Info());
    }
    ByteArrayInputStream memIn = new ByteArrayInputStream(decompressedData);
    MimeBodyPart uncompressedPayload = new MimeBodyPart(memIn);
    memIn.close();
    return (uncompressedPayload);
}

From source file:com.example.administrator.terrificweather.common.ACache.java

/**
 * ? Serializable?//  w  w w . j a v  a  2  s. co m
 *
 * @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.apache.hadoop.hbase.crosssite.CrossSiteZNodes.java

/**
 * Lists the descriptors of the cross site tables.
 * /*from ww w .  ja  v a  2s .  co  m*/
 * @param tableNames
 * @return
 * @throws KeeperException
 * @throws IOException
 */
public HTableDescriptor[] listTableDescs(List<String> tableNames) throws KeeperException, IOException {
    List<HTableDescriptor> htds = Collections.emptyList();
    if (tableNames != null && !tableNames.isEmpty()) {
        htds = new ArrayList<HTableDescriptor>();
        for (String tableName : tableNames) {
            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:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java

/************************************************************************************
 * exectute all image actions (rotation, scaling etc.) and send image back to output stream of the servlet, after setting correct mime type
 * /*from  ww  w  .j  ava 2 s .  c  o  m*/
 * @param request {@link HttpServletRequest} of ServletRequest
 * @param response {@link HttpServletResponse} for writing to response output stream
 * @throws IOException
 * @throws ImageInterpreterException 
 * @throws ServletException
 * @throws ContentLibException
 * @throws URISyntaxException
 * @throws ContentLibPdfException 
 ************************************************************************************/
@Override
public void run(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException, ContentLibException {
    long startTime = System.currentTimeMillis();

    super.run(servletContext, request, response);

    /*
     * -------------------------------- get central configuration --------------------------------
     */
    URI sourceImageUrl = null;
    ContentServerConfiguration config = ContentServerConfiguration.getInstance();
    if (!request.getParameter("sourcepath").startsWith("file:")
            && !request.getParameter("sourcepath").startsWith("http:")) {
        sourceImageUrl = new URI(config.getRepositoryPathImages() + request.getParameter("sourcepath"));
    } else {
        sourceImageUrl = new URI(request.getParameter("sourcepath"));
    }

    try {
        Cache cc = null;
        ServletOutputStream output = response.getOutputStream();
        if (request.getParameter("thumbnail") != null) {
            cc = ContentServer.getThumbnailCache();
        } else {
            cc = ContentServer.getContentCache();
        }
        // String myUniqueID = getContentCacheIdForRequest(request, config);
        String myUniqueID = getContentCacheIdForParamMap(request.getParameterMap(), config);
        String targetExtension = request.getParameter("format");

        boolean ignoreCache = false;
        /* check if cache should be ignored */
        if (request.getParameter("ignoreCache") != null) {
            String ignore = request.getParameter("ignoreCache").trim();
            ignoreCache = Boolean.parseBoolean(ignore);
        }
        boolean useCache = false;
        if (request.getParameter("thumbnail") != null) {
            useCache = config.getThumbnailCacheUse();
        } else {
            useCache = config.getContentCacheUse();
        }
        if (request.getParameterMap().containsKey("highlight")) {
            useCache = false;
        }
        if (cc == null || !useCache) {
            ignoreCache = true;
            cc = null;
            LOGGER.debug("cache deactivated via configuration");
        }

        if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) {
            LOGGER.debug("get file from cache: " + myUniqueID + "." + targetExtension);
            CacheObject co;
            try {
                co = (CacheObject) cc.get(myUniqueID + "." + targetExtension).getObjectValue();
                ByteArrayInputStream in = new ByteArrayInputStream(co.getData());

                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    output.write(buf, 0, len);
                }
                in.close();
                output.flush();
                output.close();
                return;
            } catch (NullPointerException e) {
                LOGGER.debug("element not in cache anymore: " + myUniqueID + "." + targetExtension);
            }

        } else if (!ignoreCache) {
            LOGGER.debug("file not found in cache: " + myUniqueID + "." + targetExtension);
        }

        // if (!ignoreCache && cc.cacheContains(myUniqueID, targetExtension)) {
        // LOGGER.debug("get file from cache: " + myUniqueID);
        // cc.writeToStream(output, myUniqueID, targetExtension);
        // output.flush();
        // output.close();
        // return;
        // } else if (ignoreCache == false) {
        // LOGGER.debug("file not found in cache: " + myUniqueID);
        // }

        // /*
        // * -------------------------------- if there is an internal request from goobiContentServer, you have to overwrite the
        // sourcepath with
        // * given attribute for image url --------------------------------
        // */
        // if (request.getAttribute("sourcepath") != null) {
        // sourceImageUrl = new URI((String) request.getAttribute("sourcepath"));
        // }
        LOGGER.debug("source image:" + sourceImageUrl);

        /*
         * -------------------------------- retrieve source image from url --------------------------------
         */
        ImageManager sourcemanager = new ImageManager(sourceImageUrl.toURL());
        LOGGER.trace("imageManager initialized");

        /*
         * -------------------------------- set the defaults --------------------------------
         */
        int angle = 0;
        int scaleX = 100;
        int scaleY = 100;
        int scaleType = ImageManager.SCALE_BY_PERCENT;
        LinkedList<String> highlightCoordinateList = null;
        Color highlightColor = null;
        Watermark myWatermark = null;
        LOGGER.trace("Variables set");

        /*
         * -------------------------------- rotate --------------------------------
         */
        if (request.getParameterMap().containsKey("rotate")) {
            angle = Integer.parseInt(request.getParameter("rotate"));
            LOGGER.trace("rotate image:" + angle);
        }

        /*
         * -------------------------------- scale: scale the image to some percent value --------------------------------
         */
        if (request.getParameterMap().containsKey("scale")) {
            scaleX = Integer.parseInt(request.getParameter("scale"));
            scaleY = scaleX;
            scaleType = ImageManager.SCALE_BY_PERCENT;
            LOGGER.trace("scale image to percent:" + scaleX);
        }

        if (request.getParameterMap().containsKey("width") && request.getParameterMap().containsKey("height")) {
            scaleX = Integer.parseInt(request.getParameter("width"));
            scaleY = Integer.parseInt(request.getParameter("height"));
            scaleType = ImageManager.SCALE_TO_BOX;
        }

        /*
         * -------------------------------- width: scale image to fixed width --------------------------------
         */
        else if (request.getParameterMap().containsKey("width")) {
            scaleX = Integer.parseInt(request.getParameter("width"));
            scaleY = 0;
            scaleType = ImageManager.SCALE_BY_WIDTH;
            LOGGER.trace("scale image to width:" + scaleX);
        }

        /*
         * -------------------------------- height: scale image to fixed height --------------------------------
         */
        else if (request.getParameterMap().containsKey("height")) {
            scaleY = Integer.parseInt(request.getParameter("height"));
            scaleX = 0;
            scaleType = ImageManager.SCALE_BY_HEIGHT;
            LOGGER.trace("scale image to height:" + scaleY);
        }

        /*
         * -------------------------------- highlight --------------------------------
         */
        if (request.getParameterMap().containsKey("highlight")) {
            highlightCoordinateList = new LinkedList<String>();
            String highlight = request.getParameter("highlight");
            StrTokenizer areas = new StrTokenizer(highlight, "$");
            for (String area : areas.getTokenArray()) {
                StrTokenizer coordinates = new StrTokenizer(area, ",");
                highlightCoordinateList.add(coordinates.getContent());
            }
            highlightColor = config.getDefaultHighlightColor();
        }

        /*
         * -------------------------------- insert watermark, if it should be used --------------------------------
         */
        if (!request.getParameterMap().containsKey("ignoreWatermark") && config.getWatermarkUse()) {
            File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath()));
            myWatermark = Watermark.generateWatermark(request, watermarkfile);
        }

        /*
         * -------------------------------- prepare target --------------------------------
         */
        // change to true if watermark should scale
        RenderedImage targetImage = null;
        if (config.getScaleWatermark()) {
            targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle,
                    highlightCoordinateList, highlightColor, myWatermark, true, ImageManager.BOTTOM);
        } else {
            targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle,
                    highlightCoordinateList, highlightColor, myWatermark, false, ImageManager.BOTTOM);
        }
        LOGGER.trace("Creating ImageInterpreter");
        ImageFileFormat targetFormat = ImageFileFormat.getImageFileFormatFromFileExtension(targetExtension);
        ImageInterpreter wi = targetFormat.getInterpreter(targetImage); // read file
        LOGGER.trace("Image stored in " + wi.getClass().toString());
        /*
         * -------------------------------- set file name and attachment header from parameter or from configuration
         * --------------------------------
         */
        LOGGER.trace("Creating target file");
        StringBuilder targetFileName = new StringBuilder();
        if (config.getSendImageAsAttachment()) {
            targetFileName.append("attachment; ");
        }
        targetFileName.append("filename=");

        if (request.getParameter("targetFileName") != null) {
            targetFileName.append(request.getParameter("targetFileName"));
        } else {
            String filename = ContentLibUtil.getCustomizedFileName(config.getDefaultFileNameImages(),
                    "." + targetFormat.getFileExtension());
            targetFileName.append(filename);
        }
        LOGGER.trace("Adding targetFile " + targetFileName.toString() + " to response");
        response.setHeader("Content-Disposition", targetFileName.toString());
        response.setContentType(targetFormat.getMimeType());

        /*
         * -------------------------------- resolution --------------------------------
         */
        LOGGER.trace("Setting image resolution values");
        if (request.getParameter("resolution") != null) {
            wi.setXResolution(Float.parseFloat(request.getParameter("resolution")));
            wi.setYResolution(Float.parseFloat(request.getParameter("resolution")));
        } else {
            wi.setXResolution(config.getDefaultResolution());
            wi.setYResolution(config.getDefaultResolution());
        }

        LOGGER.trace("Setting image compression");
        if (request.getParameter("compression") != null) {
            String value = request.getParameter("compression");
            try {
                int intvalue = Integer.parseInt(value);
                wi.setWriterCompressionValue(intvalue);
            } catch (Exception e) {
                LOGGER.trace("value is not a number, use default value");
            }
        }

        /*
         * -------------------------------- write target image to stream --------------------------------
         */
        // cc.put(new Element(myUniqueID + "." + targetExtension, wi.getRenderedImage()));

        if (cc != null) {
            byte[] data = wi.writeToStreamAndByteArray(output);
            cc.putIfAbsent(new Element(myUniqueID + "." + targetExtension, new CacheObject(data)));
        } else {
            LOGGER.trace("writing file to servlet response");
            wi.writeToStream(null, output);
        }
        LOGGER.trace("Done writing ImageInterpreter to stream");
        wi.clear();
        LOGGER.trace("Done clearing ImageInterpreter");
    } catch (Exception e) {
        LOGGER.error("CacheException", e);
    }
    long endTime = System.currentTimeMillis();
    LOGGER.trace("Content server time to process request: " + (endTime - startTime) + " ms");
    // try {
    // CommonUtils.appendTextFile("Image request for file " + new File(sourceImageUrl).getAbsolutePath() + "; Time to process: " + (endTime -
    // startTime)
    // + " ms\n", new File(de.unigoettingen.sub.commons.contentlib.servlet.Util.getBaseFolderAsFile(), "timeConsumptionLog.txt"));
    //
    // } catch (IOException e) {
    // LOGGER.info("Unable to write time log file due to IOException " + e.toString());
    // }
}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Export the e2e keys for a dedicated session.
 * @param session the session//  ww w.  j  a  v a 2s . c o m
 * @param password the password
 * @param callback the asynchronous callback.
 */
public static void exportKeys(final MXSession session, final String password,
        final ApiCallback<String> callback) {
    final Context appContext = VectorApp.getInstance();

    session.getCrypto().exportRoomKeys(password, new ApiCallback<byte[]>() {
        @Override
        public void onSuccess(byte[] bytesArray) {
            try {
                ByteArrayInputStream stream = new ByteArrayInputStream(bytesArray);
                String url = session.getMediasCache().saveMedia(stream,
                        "riot-" + System.currentTimeMillis() + ".txt", "text/plain");
                stream.close();

                String path = CommonActivityUtils.saveMediaIntoDownloads(appContext,
                        new File(Uri.parse(url).getPath()), "riot-keys.txt", "text/plain");

                if (null != callback) {
                    callback.onSuccess(path);
                }
            } catch (Exception e) {
                if (null != callback) {
                    callback.onMatrixError(new MatrixError(null, e.getLocalizedMessage()));
                }
            }
        }

        @Override
        public void onNetworkError(Exception e) {
            if (null != callback) {
                callback.onNetworkError(e);
            }
        }

        @Override
        public void onMatrixError(MatrixError e) {
            if (null != callback) {
                callback.onMatrixError(e);
            }
        }

        @Override
        public void onUnexpectedError(Exception e) {
            if (null != callback) {
                callback.onUnexpectedError(e);
            }
        }
    });
}

From source file:org.jnrain.mobile.accounts.kbs.KBSRegisterActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.kbs_register);

    mHandler = new Handler() {
        @Override/*w  w  w . j a va2  s .c  o m*/
        public void handleMessage(Message msg) {
            loadingDlg = DialogHelper.showProgressDialog(KBSRegisterActivity.this,
                    R.string.check_updates_dlg_title, R.string.please_wait, false, false);
        }
    };

    lastUIDCheckTime = 0;

    initValidationMapping();

    // instance state
    if (savedInstanceState != null) {
        /*
         * editNewUID.onRestoreInstanceState(savedInstanceState
         * .getParcelable("newUID"));
         * editNewEmail.onRestoreInstanceState(savedInstanceState
         * .getParcelable("newEmail"));
         * editNewPassword.onRestoreInstanceState(savedInstanceState
         * .getParcelable("newPass"));
         * editRetypeNewPassword.onRestoreInstanceState
         * (savedInstanceState .getParcelable("repeatPass"));
         * editNewNickname.onRestoreInstanceState(savedInstanceState
         * .getParcelable("newNickname"));
         * editStudID.onRestoreInstanceState(savedInstanceState
         * .getParcelable("studID"));
         * editRealName.onRestoreInstanceState(savedInstanceState
         * .getParcelable("realname"));
         * editPhone.onRestoreInstanceState(savedInstanceState
         * .getParcelable("phone"));
         * editCaptcha.onRestoreInstanceState(savedInstanceState
         * .getParcelable("captcha"));
         */

        // captcha image
        byte[] captchaPNG = savedInstanceState.getByteArray("captchaImage");
        ByteArrayInputStream captchaStream = new ByteArrayInputStream(captchaPNG);
        try {
            Drawable captchaDrawable = BitmapDrawable.createFromStream(captchaStream, "src");
            imageRegCaptcha.setImageDrawable(captchaDrawable);
        } finally {
            try {
                captchaStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    // event handlers
    // UID
    editNewUID.addTextChangedListener(new StrippedDownTextWatcher() {
        long lastCheckTime = 0;
        String lastUID;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // FIXME: use monotonic clock...
            long curtime = System.currentTimeMillis();
            if (curtime - lastCheckTime >= KBSUIConstants.REG_CHECK_UID_INTERVAL_MILLIS) {
                String uid = s.toString();

                // don't check at the first char
                if (uid.length() > 1) {
                    checkUIDAvailability(uid, curtime);
                }

                lastCheckTime = curtime;
                lastUID = uid;

                // schedule a new delayed check
                if (delayedUIDChecker != null) {
                    delayedUIDChecker.cancel();
                    delayedUIDChecker.purge();
                }
                delayedUIDChecker = new Timer();
                delayedUIDChecker.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        final String uid = getUID();

                        if (uid != lastUID) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    checkUIDAvailability(uid, System.currentTimeMillis());
                                }
                            });

                            lastUID = uid;
                        }
                    }
                }, KBSUIConstants.REG_CHECK_UID_INTERVAL_MILLIS);
            }
        }
    });

    editNewUID.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                // lost focus, force check uid availability
                checkUIDAvailability(getUID(), System.currentTimeMillis());
            } else {
                // inputting, temporarily clear that notice
                updateUIDAvailability(false, 0);
            }
        }
    });

    // E-mail
    editNewEmail.addTextChangedListener(new StrippedDownTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s)) {
                updateValidation(editNewEmail, false, true, R.string.reg_email_empty);
                return;
            }

            if (!EMAIL_CHECKER.matcher(s).matches()) {
                updateValidation(editNewEmail, false, true, R.string.reg_email_malformed);
                return;
            }

            updateValidation(editNewEmail, true, true, R.string.ok_short);
        }
    });

    // Password
    editNewPassword.addTextChangedListener(new StrippedDownTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s)) {
                updateValidation(editNewPassword, false, true, R.string.reg_psw_empty);
                return;
            }

            if (s.length() < 6) {
                updateValidation(editNewPassword, false, true, R.string.reg_psw_too_short);
                return;
            }

            if (s.length() > 39) {
                updateValidation(editNewPassword, false, true, R.string.reg_psw_too_long);
                return;
            }

            if (getUID().equalsIgnoreCase(s.toString())) {
                updateValidation(editNewPassword, false, true, 0);
            }

            updateValidation(editNewPassword, true, true, R.string.ok_short);

            updateRetypedPasswordCorrectness();
        }
    });

    // Retype password
    editRetypeNewPassword.addTextChangedListener(new StrippedDownTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateRetypedPasswordCorrectness();
        }
    });

    // Nickname
    editNewNickname.addTextChangedListener(new StrippedDownTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s)) {
                updateValidation(editNewNickname, false, true, R.string.reg_nick_empty);
                return;
            }

            updateValidation(editNewNickname, true, true, R.string.ok_short);
        }
    });

    // Student ID
    editStudID.addTextChangedListener(new StrippedDownTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s)) {
                updateValidation(editStudID, false, true, R.string.reg_stud_id_empty);
                return;
            }

            if (!IDENT_CHECKER.matcher(s).matches()) {
                updateValidation(editStudID, false, true, R.string.reg_stud_id_malformed);
                return;
            }

            updateValidation(editStudID, true, true, R.string.ok_short);
        }
    });

    // Real name
    editRealName.addTextChangedListener(new StrippedDownTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s)) {
                updateValidation(editRealName, false, true, R.string.reg_realname_empty);
                return;
            }

            updateValidation(editRealName, true, true, R.string.ok_short);
        }
    });

    // Phone
    editPhone.addTextChangedListener(new StrippedDownTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s)) {
                updateValidation(editPhone, false, true, R.string.reg_phone_empty);
                return;
            }

            if (!TextUtils.isDigitsOnly(s)) {
                updateValidation(editPhone, false, true, R.string.reg_phone_onlynumbers);
                return;
            }

            updateValidation(editPhone, true, true, R.string.ok_short);
        }
    });

    // Captcha
    editCaptcha.addTextChangedListener(new StrippedDownTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s)) {
                updateValidation(editCaptcha, false, true, R.string.reg_captcha_empty);
                return;
            }

            updateValidation(editCaptcha, true, true, R.string.ok_short);
        }
    });

    // Use current phone
    checkUseCurrentPhone.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setUseCurrentPhone(isChecked);
        }
    });

    // Is ethnic minority
    checkIsEthnicMinority.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setEthnicMinority(isChecked);
        }
    });

    // Submit form!
    btnSubmitRegister.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // progress dialog
            mHandler.sendMessage(new Message());

            // prevent repeated requests
            setSubmitButtonEnabled(false);

            // fire our biiiiiig request!
            // TODO: ??23333
            final String uid = getUID();
            final String psw = editNewPassword.getText().toString();
            makeSpiceRequest(
                    new KBSRegisterRequest(uid, psw, editNewNickname.getText().toString(), getRealName(),
                            editStudID.getText().toString(), editNewEmail.getText().toString(), getPhone(),
                            editCaptcha.getText().toString(), 2),
                    new KBSRegisterRequestListener(KBSRegisterActivity.this, uid, psw));
        }
    });

    // interface init
    // UID availability
    updateUIDAvailability(false, 0);

    // HTML-formatted register disclaimer
    FormatHelper.setHtmlText(this, textRegisterDisclaimer, R.string.register_disclaimer);
    textRegisterDisclaimer.setMovementMethod(LinkMovementMethod.getInstance());

    // is ethnic minority defaults to false
    checkIsEthnicMinority.setChecked(false);
    setEthnicMinority(false);

    // current phone number
    currentPhoneNumber = TelephonyHelper.getPhoneNumber(this);
    isCurrentPhoneNumberAvailable = currentPhoneNumber != null;

    if (isCurrentPhoneNumberAvailable) {
        // display the obtained number as hint
        FormatHelper.setHtmlText(this, checkUseCurrentPhone, R.string.field_use_current_phone,
                currentPhoneNumber);
    } else {
        // phone number unavailable, disable the choice
        checkUseCurrentPhone.setEnabled(false);
        checkUseCurrentPhone.setVisibility(View.GONE);
    }

    // default to use current phone number if available
    checkUseCurrentPhone.setChecked(isCurrentPhoneNumberAvailable);
    setUseCurrentPhone(isCurrentPhoneNumberAvailable);

    if (savedInstanceState == null) {
        // issue preflight request
        // load captcha in success callback
        this.makeSpiceRequest(new KBSRegisterRequest(), new KBSRegisterRequestListener(this));
    }
}

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

/**
 * Read from compressed file//from  w w w  . ja v  a  2  s  .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);
    ArArchiveInputStream ais = new ArArchiveInputStream(bais);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        ArArchiveEntry entry = ais.getNextArEntry();
        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.getNextArEntry();
        }
    } 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:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private X509Certificate loadCerToX509Certificate(CertificateBundle certificateBundle)
        throws CertificateException, IOException {
    Assert.assertNotNull(certificateBundle.cer());
    ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer());
    CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
    X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream);
    cerStream.close();
    return x509Certificate;
}