Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

private long getOutStreamSizeAndData(Uri uri, String contentType) throws IOException {

    String name = null;/*w  w w. ja  v a  2  s .  c om*/
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.DISPLAY_NAME }, null, null,
                null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    name = c.getString(c.getColumnIndex(MediaColumns.DISPLAY_NAME));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    long size = -1;
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.SIZE }, null, null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    size = c.getInt(c.getColumnIndex(MediaColumns.SIZE));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    String data = null;
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.DATA }, null, null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    data = c.getString(c.getColumnIndex(MediaColumns.DATA));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    if (name == null) {
        name = uri.getLastPathSegment();
    }

    File f = null;
    if (size <= 0) {
        String uriString = uri.toString();
        if (uriString.startsWith("file://")) {
            MyLog.v(TAG, uriString.substring("file://".length()));
            f = new File(uriString.substring("file://".length()));
            size = f.length();
        } else {
            MyLog.v(TAG, "not a file: " + uriString);
        }
    }

    ContentResolver cr = getContentResolver();
    InputStream is;
    // read file bytes
    try {
        is = cr.openInputStream(uri);
    } catch (FileNotFoundException e) {
        if (!TextUtils.isEmpty(data)) {
            is = new FileInputStream(data);
        } else {
            return -1; // unable to load file at all
        }
    }

    if ((contentType != null) && (contentType.indexOf('*') != -1)) {
        contentType = getContentResolver().getType(uri);
    }

    if (contentType == null) {
        contentType = URLConnection.guessContentTypeFromStream(is);
        if (contentType == null) {
            String extension = SSUtil.getFileExtensionOnly(name);
            contentType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            if (contentType == null) {
                contentType = SafeSlingerConfig.MIMETYPE_OPEN_ATTACH_DEF;
            }
        }
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[4096];
    while (is.read(buf) > -1) {
        baos.write(buf);
    }
    baos.flush();

    final byte[] fileBytes = baos.toByteArray();
    DraftData d = DraftData.INSTANCE;
    d.setFileData(fileBytes);
    d.setFileSize(fileBytes.length);
    d.setFileType(contentType);
    d.setFileName(name);
    if (f != null && f.exists()) {
        d.setFileDir(f.getAbsolutePath());
    } else if (!TextUtils.isEmpty(data)) {
        d.setFileDir(new File(data).getAbsolutePath());
    }
    return d.getFileSize();
}

From source file:com.dh.perfectoffer.event.framework.net.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request
 * and return the result.//from ww  w .j a va 2 s.  c o m
 * 
 * @param context
 *            The context to use for this operation. Used to generate the
 *            user agent if needed.
 * @param urlValue
 *            The webservice URL.
 * @param method
 *            The request method to use.
 * @param parameterList
 *            The parameters to add to the request.
 * @param headerMap
 *            The headers to add to the request.
 * @param isGzipEnabled
 *            Whether the request will use gzip compression if available on
 *            the server.
 * @param userAgent
 *            The user agent to set in the request. If null, a default
 *            Android one will be created.
 * @param postText
 *            The POSTDATA text to add in the request.
 * @param credentials
 *            The credentials to use for authentication.
 * @param isSslValidationEnabled
 *            Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled, String contentType, List<byte[]> fileByteDates,
        List<String> fileMimeTypes, int httpErrorResCodeFilte, boolean isMulFiles) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // ?
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0 && NetworkConnection.CT_DEFALUT.equals(contentType)) { // form
                // ?
                // headerMap.put(HTTP.CONTENT_TYPE,
                // "application/x-www-form-urlencoded");
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, contentType);
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null && (NetworkConnection.CT_JSON.equals(contentType)
                    || NetworkConnection.CT_XML.equals(contentType))) { // body
                // ?
                // headerMap.put(HTTP.CONTENT_TYPE, "application/json");
                // //add ?json???
                headerMap.put(HTTP.CONTENT_TYPE, contentType); // add
                // ?json???
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(postText.getBytes().length));
                outputText = postText;
                // Log.e("newtewewerew",
                // "1111application/json------------------outputText222222:::"+outputText+"-------method::"+method+"----paramBuilder.length() :"+paramBuilder.length()+"----postText:"+postText
                // );
            } else if (NetworkConnection.CT_MULTIPART.equals(contentType)) { // 
                String[] Array = urlValue.split("/");
                /*Boolean isFiles = false;
                if (Array[Array.length - 1].equals("clientRemarkPic")) {
                   isFiles = true;
                }*/
                if (null == fileByteDates || fileByteDates.size() <= 0) {
                    throw new ConnectionException("file formdata no bytes data",
                            NetworkConnection.EXCEPTION_CODE_FORMDATA_NOBYTEDATE);
                }
                headerMap.put(HTTP.CONTENT_TYPE, contentType + ";boundary=" + BOUNDARY);
                String bulidFormText = bulidFormText(parameterList);
                bos.write(bulidFormText.getBytes());
                for (int i = 0; i < fileByteDates.size(); i++) {
                    long currentTimeMillis = System.currentTimeMillis();
                    StringBuffer sb = new StringBuffer("");
                    sb.append(PREFIX).append(BOUNDARY).append(LINEND);
                    // sb.append("Content-Type:application/octet-stream" +
                    // LINEND);
                    // sb.append("Content-Disposition: form-data; name=\""+nextInt+"\"; filename=\""+nextInt+".png\"").append(LINEND);;
                    if (isMulFiles)
                        sb.append("Content-Disposition: form-data; name=\"files\";filename=\"pic"
                                + currentTimeMillis + ".png\"").append(LINEND);
                    else
                        sb.append("Content-Disposition: form-data; name=\"file\";filename=\"pic"
                                + currentTimeMillis + ".png\"").append(LINEND);
                    // sb.append("Content-Type:image/png" + LINEND);
                    sb.append("Content-Type:" + fileMimeTypes.get(i) + LINEND);
                    // sb.append("Content-Type:image/png" + LINEND);
                    sb.append(LINEND);
                    bos.write(sb.toString().getBytes());
                    bos.write(fileByteDates.get(i));
                    bos.write(LINEND.getBytes());
                }
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
                bos.write(end_data);
                bos.flush();
                headerMap.put(HTTP.CONTENT_LEN, bos.size() + "");
            }
            // L.e("newtewewerew",
            // "2222------------------outputText222222:::"+outputText+"-------method::"+method+"----paramBuilder.length() :"+paramBuilder.length()+"----postText:"+postText
            // );
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);
        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT)) {
            OutputStream output = null;
            try {
                if (NetworkConnection.CT_MULTIPART.equals(contentType)) {
                    output = connection.getOutputStream();
                    output.write(bos.toByteArray());
                } else {
                    if (null != outputText) {
                        L.e("newtewewerew", method + "------------------outputText:::" + outputText);
                        output = connection.getOutputStream();
                        output.write(outputText.getBytes());
                    }
                }

            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing
                        // to do here.
                    }
                }
            }
        }

        // Log the request
        if (L.canLog(Log.DEBUG)) {
            L.d(TAG, "Request url: " + urlValue);
            L.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                L.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    L.d(TAG, message);
                }
                L.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                L.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                L.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    L.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        L.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            // L.e("responseCode:"+responseCode+" httpErrorResCodeFilte:"+httpErrorResCodeFilte+" responseCode==httpErrorResCodeFilte:"+(responseCode==httpErrorResCodeFilte));
            if (responseCode == httpErrorResCodeFilte) { // 400???...
                logResBodyAndHeader(connection, error);
                return new ConnectionResult(connection.getHeaderFields(), error, responseCode);
            } else {
                throw new ConnectionException(error, responseCode);
            }
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        // ?? ?
        if (null != body && body.contains("\r")) {
            body = body.replace("\r", "");
        }

        if (null != body && body.contains("\n")) {
            body = body.replace("\n", "");
        }

        logResBodyAndHeader(connection, body);

        return new ConnectionResult(connection.getHeaderFields(), body, responseCode);
    } catch (IOException e) {
        L.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        L.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        L.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.hrbb.loan.pos.biz.backstage.inter.impl.LoanPosCreditApplyBackStageBizImpl.java

@Override
    public Map<String, Object> uploadCreditInvestHtml(Map<String, Object> reqMap) {

        String htmlUrl = SysConfigFactory.getInstance().getService("basicService").getPropertyValue("fsUrl");

        Map<String, Object> resultMap = Maps.newHashMap();
        String certNo = (String) reqMap.get("certNo");
        String channel = (String) reqMap.get("channel");
        logger.info("====================" + certNo + "?");
        if (StringUtil.isEmpty(certNo)) {
            resultMap.put("respCode", "1");
            resultMap.put("respMsg", "??");
            return resultMap;
        }/*from   ww w .  j  av a 2s  . c om*/
        Map<String, Object> queryMap = Maps.newHashMap();
        queryMap.put("certType", "?");
        queryMap.put("certNo", certNo);
        try {
            TCreditReportBrief brief = tCreditReportBriefDao.selectOneByCertNo(queryMap);
            if (brief != null && StringUtil.isNotEmpty(brief.getFormatHtml())) {
                //??
                String fileName = brief.getFormatHtml().substring(brief.getFormatHtml().lastIndexOf("/") + 1,
                        brief.getFormatHtml().length());
                logger.info("??" + fileName);
                String zipUploadFolder = System.getProperty("java.io.tmpdir") + "/zipupload";
                File zipUploadFolderFile = new File(zipUploadFolder);
                if (!zipUploadFolderFile.exists()) {
                    zipUploadFolderFile.mkdir();
                }
                String destFileName = System.getProperty("java.io.tmpdir") + "/zipupload/" + fileName;
                logger.info("?" + htmlUrl + brief.getFormatHtml());
                logger.info("" + destFileName);
                if (HttpUtil.getHttpFile(htmlUrl + brief.getFormatHtml(), destFileName)) {
                    logger.info("???");
                    String pwd = PwdUtil.getTcZipPwd(certNo);
                    logger.info("?" + destFileName + ", ?:" + pwd);
                    //?
                    String currTime = "_" + IdUtil.getCreditInvestigateId();
                    if (ZipUtils.zipEncrypt(destFileName.replace(".html", currTime + ".zip"), destFileName, pwd)) {
                        logger.info("??");
                        //ftp
                        HFTPFile ftpFile = new HFTPFile();
                        InputStream is = new FileInputStream(destFileName.replace(".html", currTime + ".zip"));

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        byte[] b = new byte[2048];
                        while ((is.read(b)) != -1) {
                            bos.write(b);
                        }
                        byte[] bytes = bos.toByteArray();

                        bos.flush();
                        bos.close();
                        is.close();
                        ftpFile.setData(bytes);
                        ftpFile.setName(fileName.replace(".html", currTime + ".zip"));
                        logger.info("getFtpCode");
                        String ftpCode = FtpCodeFactory.getFtpCode(channel);
                        logger.info("getFtpCode?");
                        ParamResBean resBean = ftpTransUpload.uploadFile(ftpCode, ftpFile);
                        logger.info("uploadFile?");
                        if ("000".equals(resBean.getRespCode())) {
                            logger.info("ftp?");
                            resultMap.put("respCode", "0");
                            resultMap.put("zipFileName", fileName.replace(".html", currTime + ".zip"));
                            resultMap.put("zipFilePwd", pwd);
                            resultMap.put("respMsg", "??");
                            //
                            File deleteFile = new File(destFileName);
                            File deleteZipFile = new File(destFileName.replace(".html", currTime + ".zip"));
                            deleteFile.deleteOnExit();
                            deleteZipFile.deleteOnExit();

                        } else {
                            logger.info("ftp");
                            resultMap.put("respCode", "1");
                            resultMap.put("respMsg", "ftp");
                            return resultMap;
                        }
                    } else {
                        logger.error("?");
                        resultMap.put("respCode", "1");
                        resultMap.put("respMsg", "?");
                        return resultMap;
                    }
                } else {
                    resultMap.put("respCode", "1");
                    resultMap.put("respMsg", "??");
                    return resultMap;
                }

            } else {
                resultMap.put("respCode", "1");
                resultMap.put("respMsg", "??");
            }
            return resultMap;

        } catch (Exception e) {
            logger.error("?:", e);
            resultMap.put("respCode", "1");
            resultMap.put("respMsg", "?");
            return resultMap;
        }
    }

From source file:org.apache.olingo.fit.Services.java

@POST
@Path("/async/$batch")
public Response async(@Context final UriInfo uriInfo) {

    try {//w  ww . ja v a2 s.c om
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.write("HTTP/1.1 200 Ok".getBytes());
        bos.write(Constants.CRLF);
        bos.write("OData-Version: 4.0".getBytes());
        bos.write(Constants.CRLF);
        bos.write(
                ("Content-Type: " + ContentType.APPLICATION_OCTET_STREAM + ";boundary=" + BOUNDARY).getBytes());
        bos.write(Constants.CRLF);
        bos.write(Constants.CRLF);

        bos.write(("--" + BOUNDARY).getBytes());
        bos.write(Constants.CRLF);
        bos.write("Content-Type: application/http".getBytes());
        bos.write(Constants.CRLF);
        bos.write("Content-Transfer-Encoding: binary".getBytes());
        bos.write(Constants.CRLF);
        bos.write(Constants.CRLF);

        bos.write("HTTP/1.1 202 Accepted".getBytes());
        bos.write(Constants.CRLF);
        bos.write("Location: http://service-root/async-monitor".getBytes());
        bos.write(Constants.CRLF);
        bos.write("Retry-After: 10".getBytes());
        bos.write(Constants.CRLF);
        bos.write(Constants.CRLF);
        bos.write(("--" + BOUNDARY + "--").getBytes());
        bos.write(Constants.CRLF);

        final UUID uuid = UUID.randomUUID();
        providedAsync.put(uuid.toString(), bos.toString(Constants.ENCODING.toString()));

        bos.flush();
        bos.close();

        return xml.createAsyncResponse(uriInfo.getRequestUri().toASCIIString().replace("async/$batch", "")
                + "monitor/" + uuid.toString());
    } catch (Exception e) {
        return xml.createFaultResponse(Accept.JSON.toString(), e);
    }
}

From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

private BrandingResult extractBranding(final BrandedItem item, final File encryptedBrandingFile,
        final File tmpDecryptedBrandingFile, final File tmpBrandingDir) throws BrandingFailureException {
    try {/*from w w w  . j  ava2 s . c o  m*/
        L.i("Extracting " + tmpDecryptedBrandingFile + " (" + item.brandingKey + ")");
        File brandingFile = new File(tmpBrandingDir, "branding.html");
        File watermarkFile = null;
        Integer backgroundColor = null;
        Integer menuItemColor = null;
        ColorScheme scheme = ColorScheme.light;
        boolean showHeader = true;
        String contentType = null;
        boolean wakelockEnabled = false;
        ByteArrayOutputStream brandingBos = new ByteArrayOutputStream();
        try {
            MessageDigest digester = MessageDigest.getInstance("SHA256");
            DigestInputStream dis = new DigestInputStream(
                    new BufferedInputStream(new FileInputStream(tmpDecryptedBrandingFile)), digester);
            try {
                ZipInputStream zis = new ZipInputStream(dis);
                try {
                    byte data[] = new byte[BUFFER_SIZE];
                    ZipEntry entry;
                    while ((entry = zis.getNextEntry()) != null) {
                        L.d("Extracting: " + entry);
                        int count = 0;
                        if (entry.getName().equals("branding.html")) {
                            while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                                brandingBos.write(data, 0, count);
                            }
                        } else {
                            if (entry.isDirectory()) {
                                L.d("Skipping branding dir " + entry.getName());
                                continue;
                            }
                            File destination = new File(tmpBrandingDir, entry.getName());
                            destination.getParentFile().mkdirs();
                            if ("__watermark__".equals(entry.getName())) {
                                watermarkFile = destination;
                            }
                            final OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination),
                                    BUFFER_SIZE);
                            try {
                                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                                    fos.write(data, 0, count);
                                }
                            } finally {
                                fos.close();
                            }
                        }
                    }
                    while (dis.read(data) >= 0)
                        ;
                } finally {
                    zis.close();
                }
            } finally {
                dis.close();
            }
            String hexDigest = com.mobicage.rogerthat.util.TextUtils.toHex(digester.digest());
            if (!hexDigest.equals(item.brandingKey)) {
                encryptedBrandingFile.delete();
                SystemUtils.deleteDir(tmpBrandingDir);
                throw new BrandingFailureException("Branding cache was invalid!");
            }
            brandingBos.flush();
            byte[] brandingBytes = brandingBos.toByteArray();
            if (brandingBytes.length == 0) {
                encryptedBrandingFile.delete();
                SystemUtils.deleteDir(tmpBrandingDir);
                throw new BrandingFailureException("Invalid branding package!");
            }
            String brandingHtml = new String(brandingBytes, "UTF8");

            switch (item.type) {
            case BrandedItem.TYPE_MESSAGE:
                MessageTO message = (MessageTO) item.object;
                brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE,
                        TextUtils.htmlEncode(message.message).replace("\r", "").replace("\n", "<br>"));

                brandingHtml = brandingHtml.replace(NUNTIUZ_TIMESTAMP,
                        TimeUtils.getDayTimeStr(mContext, message.timestamp * 1000));

                FriendsPlugin friendsPlugin = mMainService.getPlugin(FriendsPlugin.class);
                brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME,
                        TextUtils.htmlEncode(friendsPlugin.getName(message.sender)));
                break;
            case BrandedItem.TYPE_FRIEND:
                FriendTO friend = (FriendTO) item.object;
                // In this case Friend is fully populated
                brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE,
                        TextUtils.htmlEncode(friend.description).replace("\r", "").replace("\n", "<br>"));

                brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(friend.name));

                break;
            case BrandedItem.TYPE_GENERIC:
                if (item.object instanceof FriendTO) {
                    brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME,
                            TextUtils.htmlEncode(((FriendTO) item.object).name));
                }
                break;
            }

            Matcher matcher = RegexPatterns.BRANDING_BACKGROUND_COLOR.matcher(brandingHtml);
            if (matcher.find()) {
                String bg = matcher.group(1);
                if (bg.length() == 4) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("#");
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(3));
                    sb.append(bg.charAt(3));
                    bg = sb.toString();
                }
                backgroundColor = Color.parseColor(bg);
            }

            matcher = RegexPatterns.BRANDING_MENU_ITEM_COLOR.matcher(brandingHtml);
            if (matcher.find()) {
                String bg = matcher.group(1);
                if (bg.length() == 4) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("#");
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(3));
                    sb.append(bg.charAt(3));
                    bg = sb.toString();
                }
                menuItemColor = Color.parseColor(bg);
            }

            matcher = RegexPatterns.BRANDING_COLOR_SCHEME.matcher(brandingHtml);
            if (matcher.find()) {
                String schemeStr = matcher.group(1);
                scheme = "dark".equalsIgnoreCase(schemeStr) ? ColorScheme.dark : ColorScheme.light;
            }

            matcher = RegexPatterns.BRANDING_SHOW_HEADER.matcher(brandingHtml);
            if (matcher.find()) {
                String showHeaderStr = matcher.group(1);
                showHeader = "true".equalsIgnoreCase(showHeaderStr);
            }

            matcher = RegexPatterns.BRANDING_CONTENT_TYPE.matcher(brandingHtml);
            if (matcher.find()) {
                String contentTypeStr = matcher.group(1);
                L.i("Branding content-type: " + contentTypeStr);
                if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentTypeStr)) {
                    File tmpBrandingFile = new File(tmpBrandingDir, "embed.pdf");
                    if (tmpBrandingFile.exists()) {
                        contentType = AttachmentViewerActivity.CONTENT_TYPE_PDF;
                    }
                }
            }

            Dimension dimension1 = null;
            Dimension dimension2 = null;
            matcher = RegexPatterns.BRANDING_DIMENSIONS.matcher(brandingHtml);
            if (matcher.find()) {
                String dimensionsStr = matcher.group(1);
                L.i("Branding dimensions: " + dimensionsStr);
                String[] dimensions = dimensionsStr.split(",");
                try {
                    dimension1 = new Dimension(Integer.parseInt(dimensions[0]),
                            Integer.parseInt(dimensions[1]));
                    dimension2 = new Dimension(Integer.parseInt(dimensions[2]),
                            Integer.parseInt(dimensions[3]));
                } catch (Exception e) {
                    L.bug("Invalid branding dimension: " + matcher.group(), e);
                }
            }

            matcher = RegexPatterns.BRANDING_WAKELOCK_ENABLED.matcher(brandingHtml);
            if (matcher.find()) {
                String wakelockEnabledStr = matcher.group(1);
                wakelockEnabled = "true".equalsIgnoreCase(wakelockEnabledStr);
            }

            final List<String> externalUrlPatterns = new ArrayList<String>();
            matcher = RegexPatterns.BRANDING_EXTERNAL_URLS.matcher(brandingHtml);
            while (matcher.find()) {
                externalUrlPatterns.add(matcher.group(1));
            }

            FileOutputStream fos = new FileOutputStream(brandingFile);

            try {
                fos.write(brandingHtml.getBytes("UTF8"));
            } finally {
                fos.close();
            }
            if (contentType != null
                    && AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentType)) {
                brandingFile = new File(tmpBrandingDir, "embed.pdf");
            }
            return new BrandingResult(tmpBrandingDir, brandingFile, watermarkFile, backgroundColor,
                    menuItemColor, scheme, showHeader, dimension1, dimension2, contentType, wakelockEnabled,
                    externalUrlPatterns);
        } finally {
            brandingBos.close();
        }
    } catch (IOException e) {
        L.e(e);
        throw new BrandingFailureException("Error copying cached branded file to private space", e);
    } catch (NoSuchAlgorithmException e) {
        L.e(e);
        throw new BrandingFailureException("Cannot validate ", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0401Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<Pref> prefs = getPrefs();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.xml");

    tsv.setTime(timestamp);//from   www. ja  v a 2 s . co  m
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "\t" + pref.getName() + "\t" + pref.getYomi() + CRLF)
                    .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "," + pref.getName() + "," + pref.getYomi() + CRLF)
                    .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (Pref pref : prefs) {

            jwriter.object().key("code").value(pref.getCode()).key("name").value(pref.getName()).key("yomi")
                    .value(pref.getYomi()).endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0401s");

        for (Pref pref : prefs) {

            xwriter.writeStartElement("x0401");
            xwriter.writeAttribute("code", pref.getCode());
            xwriter.writeAttribute("name", pref.getName());
            xwriter.writeAttribute("yomi", pref.getYomi());
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0401.zip");
        log.info("prefs: " + prefs.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0402Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<City> cities = getCities();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml");

    tsv.setTime(timestamp);/*from ww w . j  ava 2s  .  c  o  m*/
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t"
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + ","
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (City city : cities) {

            jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi")
                    .value(city.getYomi()).key("expired")
                    .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false")
                    .endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0402s");

        for (City city : cities) {

            xwriter.writeStartElement("x0402");
            xwriter.writeAttribute("code", city.getCode());
            xwriter.writeAttribute("name", city.getName());
            xwriter.writeAttribute("yomi", city.getYomi());
            xwriter.writeAttribute("expired",
                    (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false");
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0402.zip");
        log.info("cities: " + cities.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given {@link HttpServletResponse}
 * //  w ww.j  a  v  a  2 s .  c  om
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied response back to the client
 * @param digest
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, String user, String password, ProxyInfo proxyInfo)
        throws IOException, ServletException {

    if (user != null && password != null) {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, upc);
    }

    httpMethodProxyRequest.setFollowRedirects(false);

    InputStream inputStreamServerResponse = null;
    ByteArrayOutputStream baos = null;

    try {

        // //////////////////////////
        // Execute the request
        // //////////////////////////

        int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

        onRemoteResponse(httpMethodProxyRequest);

        // ////////////////////////////////////////////////////////////////////////////////
        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        // ////////////////////////////////////////////////////////////////////////////////

        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {

            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(Utils.LOCATION_HEADER).getValue();

            if (stringLocation == null) {
                throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                        + Utils.LOCATION_HEADER + " header was found in the response");
            }

            // /////////////////////////////////////////////
            // Modify the redirect to go to this proxy
            // servlet rather that the proxied host
            // /////////////////////////////////////////////

            String stringMyHostName = httpServletRequest.getServerName();

            if (httpServletRequest.getServerPort() != 80) {
                stringMyHostName += ":" + httpServletRequest.getServerPort();
            }

            stringMyHostName += httpServletRequest.getContextPath();
            httpServletResponse.sendRedirect(stringLocation.replace(
                    Utils.getProxyHostAndPort(proxyInfo) + proxyInfo.getProxyPath(), stringMyHostName));

            return;

        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {

            // ///////////////////////////////////////////////////////////////
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            // ///////////////////////////////////////////////////////////////

            httpServletResponse.setIntHeader(Utils.CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

            return;
        }

        // /////////////////////////////////////////////
        // Pass the response code back to the client
        // /////////////////////////////////////////////

        httpServletResponse.setStatus(intProxyResponseCode);

        // /////////////////////////////////////////////
        // Pass response headers back to the client
        // /////////////////////////////////////////////

        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();

        for (Header header : headerArrayResponse) {

            // /////////////////////////
            // Skip GZIP Responses
            // /////////////////////////

            if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_ACCEPT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING))
                continue;
            //                else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_WWW_AUTHENTICATE))
            //                    continue;                
            else
                httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // ///////////////////////////////////
        // Send the content to the client
        // ///////////////////////////////////

        inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();

        if (inputStreamServerResponse != null) {
            byte[] b = new byte[proxyConfig.getDefaultStreamByteSize()];

            baos = new ByteArrayOutputStream(b.length);

            int read = 0;
            while ((read = inputStreamServerResponse.read(b)) > 0) {
                baos.write(b, 0, read);
                baos.flush();
            }

            baos.writeTo(httpServletResponse.getOutputStream());
        }

    } catch (HttpException e) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error executing HTTP method ", e);
    } finally {
        try {
            if (inputStreamServerResponse != null)
                inputStreamServerResponse.close();
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing request input stream ", e);
            throw new ServletException(e.getMessage());
        }

        try {
            if (baos != null) {
                baos.flush();
                baos.close();
            }
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing response stream ", e);
            throw new ServletException(e.getMessage());
        }

        httpMethodProxyRequest.releaseConnection();
    }
}

From source file:lasige.steeldb.jdbc.BFTRowSet.java

/**
 * Generates the bytes of the results of a query.
 * This method is used to create the hash of the results, to provide a way to
 * compare two queries results.//  w  ww. j av a2 s. c o m
 * 
 * @return the bytes of the vector with results from a query
 */
public byte[] getResultsBytes() {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ObjectOutputStream obOut = null;
    try {
        obOut = new ObjectOutputStream(bOut);
        obOut.writeObject(rvh);
        obOut.flush();
        bOut.flush();
        obOut.close();
        bOut.close();
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return bOut.toByteArray();
}