Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

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

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

From source file:org.opensilk.music.cast.CastWebServer.java

/**
 * Fetches and serves the album art//from  w ww  . j  a va  2 s.co m
 *
 * @param uri
 * @param headers
 * @return
 */
//@DebugLog
private Response serveArt(Map<String, String> headers, Map<String, String> params, String uri) {
    String artist = params.get("artist");
    String album = params.get("album");
    if (TextUtils.isEmpty(artist) || TextUtils.isEmpty(album)) {
        return notFoundResponse();
    }
    String reqEtag = headers.get("if-none-match");
    if (!quiet)
        Log.d(TAG, "requested Art etag " + reqEtag);
    // Check our cache if we served up this etag for this url already
    // we can just return and save ourselfs a lot of expensive db/disk queries
    if (!TextUtils.isEmpty(reqEtag)) {
        String oldUri;
        synchronized (mEtagCache) {
            oldUri = mEtagCache.get(reqEtag);
        }
        if (oldUri != null && oldUri.equals(uri)) {
            // We already served it
            return createResponse(Response.Status.NOT_MODIFIED, MIME_ART, "");
        }
    }
    // We've got get get the art
    InputStream parcelIn = null;
    ByteArrayOutputStream tmpOut = null;
    try {
        final ParcelFileDescriptor pfd = mContext.getContentResolver()
                .openFileDescriptor(ArtworkProvider.createArtworkUri(artist, album), "r");
        //Hackish but hopefully will yield unique etags (at least for this session)
        String etag = Integer.toHexString(pfd.hashCode());
        if (!quiet)
            Log.d(TAG, "Created etag " + etag + " for " + uri);
        synchronized (mEtagCache) {
            mEtagCache.put(etag, uri);
        }
        // pipes dont perform well over the network and tend to get broken
        // so copy the image into memory and send the copy
        parcelIn = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
        tmpOut = new PoolingByteArrayOutputStream(mBytePool, 512 * 1024);
        IOUtils.copy(parcelIn, tmpOut);
        if (!quiet)
            Log.d(TAG, "image size=" + tmpOut.size() / 1024.0 + "k");
        Response res = createResponse(Response.Status.OK, MIME_ART,
                new ByteArrayInputStream(tmpOut.toByteArray()));
        res.addHeader("ETag", etag);
        return res;
    } catch (NullPointerException | IOException e) {
        // Serve up the default art
        return createResponse(Response.Status.OK, MIME_ART,
                mContext.getResources().openRawResource(R.drawable.default_artwork));
    } finally {
        IOUtils.closeQuietly(tmpOut);
        IOUtils.closeQuietly(parcelIn);
    }
}

From source file:org.jboss.test.syslog.TCPSyslogSocketHandler.java

public void run() {
    try {// ww  w . j a v a  2s.c o  m
        final BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        int b = -1;
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        boolean firstByte = true;
        boolean octetCounting = false;
        StringBuilder octetLenStr = new StringBuilder();
        do {
            b = bis.read();
            if (firstByte && b >= '1' && b <= '9') {
                // handle Octet Counting messages (cf. rfc-6587)
                octetCounting = true;
            }
            firstByte = false;
            if (octetCounting) {
                if (b != ' ') {
                    octetLenStr.append((char) b);
                } else {
                    int len = Integer.parseInt(octetLenStr.toString());
                    handleSyslogMessage(IOUtils.toByteArray(bis, len));
                    // reset the stuff
                    octetLenStr = new StringBuilder();
                    firstByte = true;
                    octetCounting = false;
                }
            } else {
                // handle Non-Transparent-Framing messages (cf. rfc-6587)
                switch (b) {
                case -1:
                case '\r':
                case '\n':
                    if (baos.size() > 0) {
                        handleSyslogMessage(baos.toByteArray());
                        baos.reset();
                        firstByte = true;
                    }
                    break;
                default:
                    baos.write(b);
                    break;
                }
            }
        } while (b != -1);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(socket);
        sockets.remove(socket);
    }
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Create a resource using Smartsheet REST API.
 *
 * Exceptions:/* ww w  .j  av a2 s .c  o m*/
 *   IllegalArgumentException : if any argument is null, or path is empty string
 *   InvalidRequestException : if there is any problem with the REST API request
 *   AuthorizationException : if there is any problem with the REST API authorization(access token)
 *   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
 *   SmartsheetRestException : if there is any other REST API related error occurred during the operation
 *   SmartsheetException : if there is any other error occurred during the operation
 *
 * @param <T> the generic type of object to return/deserialize
 * @param <S> the generic type of object to serialize
 * @param path the relative path of the resource collections
 * @param objectClass the resource object class
 * @param object the object to create
 * @return the created resource
 * @throws SmartsheetException the smartsheet exception
 */
protected <T, S> T createResource(String path, Class<T> objectClass, S object) throws SmartsheetException {
    Util.throwIfNull(path, object, objectClass);
    Util.throwIfEmpty(path);

    HttpRequest request = createHttpRequest(smartsheet.getBaseURI().resolve(path), HttpMethod.POST);

    ByteArrayOutputStream objectBytesStream = new ByteArrayOutputStream();
    this.smartsheet.getJsonSerializer().serialize(object, objectBytesStream);
    HttpEntity entity = new HttpEntity();
    entity.setContentType("application/json");
    entity.setContent(new ByteArrayInputStream(objectBytesStream.toByteArray()));
    entity.setContentLength(objectBytesStream.size());
    request.setEntity(entity);

    T obj = null;
    try {
        HttpResponse response = this.smartsheet.getHttpClient().request(request);
        switch (response.getStatusCode()) {
        case 200: {
            InputStream inputStream = response.getEntity().getContent();
            String content = null;
            try {
                if (log.isInfoEnabled()) {
                    ByteArrayOutputStream contentCopyStream = new ByteArrayOutputStream();
                    inputStream = StreamUtil.cloneContent(inputStream, response.getEntity().getContentLength(),
                            contentCopyStream);
                    content = StreamUtil.toUtf8StringOrHex(contentCopyStream, getResponseLogLength());
                }
                obj = this.smartsheet.getJsonSerializer().deserializeResult(objectClass, inputStream)
                        .getResult();
            } catch (JSONSerializerException e) {
                log.info("failure parsing '{}'", content, e);
                throw new SmartsheetException(e);
            } catch (IOException e) {
                log.info("failure cloning content from inputStream '{}'", inputStream, e);
                throw new SmartsheetException(e);
            }
            break;
        }
        default:
            handleError(response);
        }
    } finally {
        smartsheet.getHttpClient().releaseConnection();
    }

    return obj;
}

From source file:org.jboss.as.test.integration.logging.syslogserver.TCPSyslogSocketHandler.java

public void run() {
    try {//from  w  w  w.j  a v a2 s . co m
        final BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        int b = -1;
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        boolean firstByte = true;
        boolean octetCounting = false;
        StringBuilder octetLenStr = new StringBuilder();
        do {
            b = bis.read();
            if (firstByte && b >= '1' && b <= '9') {
                // handle Octet Counting messages (cf. rfc-6587)
                octetCounting = true;
            }
            firstByte = false;
            if (octetCounting) {
                if (b != ' ') {
                    octetLenStr.append((char) b);
                } else {
                    int len = Integer.parseInt(octetLenStr.toString());
                    handleSyslogMessage(IOUtils.toByteArray(bis, len));
                    // reset the stuff
                    octetLenStr = new StringBuilder();
                    firstByte = true;
                    octetCounting = false;
                }
            } else {
                // handle Non-Transparent-Framing messages (cf. rfc-6587)
                switch (b) {
                case -1:
                case '\r':
                case '\n':
                    if (baos.size() > 0) {
                        handleSyslogMessage(baos.toByteArray());
                        baos.reset();
                        firstByte = true;
                    }
                    break;
                default:
                    baos.write(b);
                    break;
                }
            }
        } while (b != -1);
    } catch (IOException e) {
        LOGGER.warn("IOException occurred", e);
    } finally {
        IOUtils.closeQuietly(socket);
        sockets.remove(socket);
    }
}

From source file:org.mifosplatform.infrastructure.reportmailingjob.service.ReportMailingJobWritePlatformServiceImpl.java

/** 
 * generate the Pentaho report output stream
 * /*from   w  w w  .j av  a2  s  .c om*/
 * @return StringBuilder object -- the error log StringBuilder object
 **/
private StringBuilder generatePentahoReportOutputStream(final ReportMailingJob reportMailingJob,
        final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat,
        final Map<String, String> reportParams, final String reportName, final StringBuilder errorLog) {

    try {
        this.switchToReadOnlyDatabase();

        final ByteArrayOutputStream byteArrayOutputStream = this.readReportingService
                .generatePentahoReportAsOutputStream(reportName, emailAttachmentFileFormat.getValue(),
                        reportParams, null, reportMailingJob.getRunAsUser(), errorLog);
        final MifosPlatformTenant platformTenant = ThreadLocalContextUtil.getTenant();
        final String fileLocation = FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator
                + platformTenant.getTenantIdentifier() + File.separator + "reportmailingjob";
        final String fileNameWithoutExtension = fileLocation + File.separator + reportName;

        // check if file directory exists, if not create directory
        if (!new File(fileLocation).isDirectory()) {
            new File(fileLocation).mkdirs();
        }

        if (byteArrayOutputStream.size() == 0) {
            errorLog.append("Pentaho report processing failed, empty output stream created");
        }

        else if (errorLog.length() == 0 && (byteArrayOutputStream.size() > 0)) {
            final String fileName = fileNameWithoutExtension + "." + emailAttachmentFileFormat.getValue();

            // send the file to email recipients
            this.sendPentahoReportFileToEmailRecipients(reportMailingJob, fileName, byteArrayOutputStream,
                    errorLog);
        }
    }

    catch (Exception e) {
        // do nothing for now
        errorLog.append(e);
    }

    return errorLog;
}

From source file:org.opendaylight.netvirt.dhcpservice.DhcpPktHandler.java

private void setOptionClasslessRoute(DHCP reply, DhcpInfo dhcpInfo) {
    List<HostRoutes> hostRoutes = dhcpInfo.getHostRoutes();
    if (hostRoutes == null) {
        //we can't set this option, so return
        return;/*  www.j  a va 2s  .  c  o  m*/
    }
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    for (HostRoutes hostRoute : hostRoutes) {
        if (hostRoute.getNexthop().getIpv4Address() == null
                || hostRoute.getDestination().getIpv4Prefix() == null) {
            // we only deal with IPv4 addresses
            return;
        }
        String router = hostRoute.getNexthop().getIpv4Address().getValue();
        String dest = hostRoute.getDestination().getIpv4Prefix().getValue();
        try {
            result.write(convertToClasslessRouteOption(dest, router));
        } catch (IOException | NullPointerException e) {
            LOG.trace("Exception {}", e.getMessage());
        }
    }
    if (result.size() > 0) {
        reply.setOptionBytes(DHCPConstants.OPT_CLASSLESS_ROUTE, result.toByteArray());
    }
}

From source file:com.clustercontrol.hub.session.FluentdTransferFactory.java

/**
 * ?????????//from  w  w w.ja va 2  s .  c o  m
 * 
 */
@Override
public Transfer createTansfer(final TransferInfo info, final PropertyBinder binder) throws TransferException {
    // HTTP ?????
    TransferDestProp urlProp = null;
    TransferDestProp connectTimeoutProp = null;
    TransferDestProp requestTimeoutProp = null;
    for (TransferDestProp prop : info.getDestProps()) {
        switch (prop.getName()) {
        case prop_url:
            urlProp = prop;
            break;
        case prop_connect_timeout:
            connectTimeoutProp = prop;
            break;
        case prop_request_timeout:
            requestTimeoutProp = prop;
            break;
        default:
            logger.warn(String.format("createTansfer() : unknown property(%s)", prop.getValue()));
            break;
        }
    }

    if (urlProp == null || urlProp.getValue() == null)
        throw new TransferException(String.format("createTansfer() : Value of \"%s\" must be set.", prop_url));

    if (!urlPattern.matcher(urlProp.getValue()).matches())
        throw new TransferException(
                String.format("createTansfer() : invalid url format. url=%s", urlProp.getValue()));

    final String urlStr = urlProp.getValue();

    Integer timeout;
    try {
        timeout = Integer.valueOf(connectTimeoutProp.getValue());
    } catch (NumberFormatException e) {
        timeout = DEFAULT_CONNECT_TIMEOUT;
        logger.warn(String.format("createTansfer() : can't regognize connectTimeout(%s) as number.",
                connectTimeoutProp.getValue()));
    } catch (NullPointerException e) {
        timeout = DEFAULT_CONNECT_TIMEOUT;
        logger.warn(String.format(
                "createTansfer() : connectTimeout is null, then use default value as connectTimeout(%s).",
                timeout));
    }
    final Integer connectTimeout = timeout;

    try {
        timeout = Integer.valueOf(requestTimeoutProp.getValue());
    } catch (NumberFormatException e) {
        timeout = DEFAULT_REQUEST_TIMEOUT;
        logger.warn(String.format("createTansfer() : can't regognize requestTimeout(%s) as number.",
                requestTimeoutProp.getValue()));
    } catch (NullPointerException e) {
        timeout = DEFAULT_CONNECT_TIMEOUT;
        logger.warn(String.format(
                "createTansfer() : requestTimeout is null, then use default value as requestTimeout(%s).",
                timeout));
    }
    final Integer requestTimeout = timeout;

    // ??
    return new Transfer() {
        private static final int BUFF_SIZE = 1024 * 1024;
        private static final int BODY_MAX_SIZE = 5 * BUFF_SIZE;

        private CloseableHttpClient client = null;

        /*
         * ??
         * 
         */
        @Override
        public TransferNumericData transferNumerics(Iterable<TransferNumericData> numerics,
                TrasferCallback<TransferNumericData> callback) throws TransferException {
            TransferNumericData lastPosition = null;
            for (TransferNumericData numeric : numerics) {
                ObjectNode root = JsonNodeFactory.instance.objectNode();
                root.put("item_name", numeric.key.getItemName());
                root.put("display_name", numeric.key.getDisplayName());
                root.put("monitor_id", numeric.key.getMonitorId());
                root.put("facility_id", numeric.key.getFacilityid());
                root.put("time", numeric.data.getTime());
                root.put("value", numeric.data.getValue());
                root.put("position", numeric.data.getPosition());

                String url = binder.bind(numeric.key, numeric.data, urlStr);
                String data = root.toString();
                try {
                    send(url, data);
                    lastPosition = numeric;

                    if (callback != null)
                        callback.onTransferred(lastPosition);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                    internalError_monitor(numeric.key.getMonitorId(), data, e, url);
                    break;
                }
            }
            return lastPosition;
        }

        /*
         * ??
         * 
         */
        @Override
        public TransferStringData transferStrings(Iterable<TransferStringData> strings,
                TrasferCallback<TransferStringData> callback) throws TransferException {
            TransferStringData lastPosition = null;
            for (TransferStringData string : strings) {
                ObjectNode root = JsonNodeFactory.instance.objectNode();
                root.put("target_name", string.key.getTargetName());
                root.put("monitor_id", string.key.getMonitorId());
                root.put("facility_id", string.key.getFacilityId());
                root.put("log_format_id", string.data.getLogformatId());
                root.put("time", string.data.getTime());
                root.put("source", string.data.getValue());

                for (CollectDataTag t : string.data.getTagList()) {
                    root.put(t.getKey(), t.getValue());
                }

                root.put("position", string.data.getDataId());

                String url = binder.bind(string.key, string.data, urlStr);
                String data = root.toString();
                try {
                    send(url, data);
                    lastPosition = string;

                    if (callback != null)
                        callback.onTransferred(lastPosition);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                    internalError_monitor(string.key.getMonitorId(), data, e, url);
                    break;
                }
            }
            return lastPosition;
        }

        /*
         * ??
         * 
         */
        @Override
        public JobSessionEntity transferJobs(Iterable<JobSessionEntity> sessions,
                TrasferCallback<JobSessionEntity> callback) throws TransferException {
            JobSessionEntity lastPosition = null;
            for (JobSessionEntity session : sessions) {
                ObjectNode sessionNode = JsonNodeFactory.instance.objectNode();
                sessionNode.put("ssession_id", session.getSessionId());
                sessionNode.put("job_id", session.getJobId());
                sessionNode.put("jobunit_id", session.getJobunitId());
                sessionNode.put("schedule_date", session.getScheduleDate());
                sessionNode.put("position", session.getPosition());

                ArrayNode jobArray = sessionNode.putArray("jobs");
                for (JobSessionJobEntity job : session.getJobSessionJobEntities()) {
                    ObjectNode jobNode = jobArray.addObject();
                    jobNode.put("job_id", job.getId().getJobId());
                    jobNode.put("jobunit_id", job.getId().getJobunitId());
                    if (job.getScopeText() != null)
                        jobNode.put("scope_text", job.getScopeText());
                    if (job.getStatus() != null)
                        jobNode.put("status", job.getStatus());
                    if (job.getStartDate() != null)
                        jobNode.put("start_date", job.getStartDate());
                    if (job.getEndDate() != null)
                        jobNode.put("end_date", job.getEndDate());
                    if (job.getEndValue() != null)
                        jobNode.put("end_value", job.getEndValue());
                    if (job.getEndStatus() != null)
                        jobNode.put("end_status", job.getEndStatus());
                    if (job.getResult() != null)
                        jobNode.put("result", job.getResult());
                    if (job.getJobInfoEntity() != null)
                        jobNode.put("job_type", job.getJobInfoEntity().getJobType());

                    if (!job.getJobSessionNodeEntities().isEmpty()) {
                        ArrayNode nodeArray = jobNode.putArray("nodes");
                        for (JobSessionNodeEntity node : job.getJobSessionNodeEntities()) {
                            ObjectNode nodeNode = nodeArray.addObject();
                            nodeNode.put("facility_id", node.getId().getFacilityId());
                            nodeNode.put("node_name", node.getNodeName());
                            nodeNode.put("status", node.getStatus());
                            nodeNode.put("start_date", node.getStartDate());
                            nodeNode.put("end_date", node.getEndDate());
                            nodeNode.put("end_value", node.getEndValue());
                            nodeNode.put("message", node.getMessage());
                            nodeNode.put("result", node.getResult());
                            nodeNode.put("start_date", node.getStartDate());
                            nodeNode.put("startup_time", node.getStartupTime());
                            nodeNode.put("instance_id", node.getInstanceId());
                        }
                    }
                }

                String url = binder.bind(session, urlStr);
                String data = sessionNode.toString();
                try {
                    send(url, data);
                    lastPosition = session;

                    if (callback != null)
                        callback.onTransferred(lastPosition);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                    internalError_session(session.getSessionId(), data, e, url);
                    break;
                }
            }
            return lastPosition;
        }

        /*
         * ??
         * 
         */
        @Override
        public EventLogEntity transferEvents(Iterable<EventLogEntity> events,
                TrasferCallback<EventLogEntity> callback) throws TransferException {
            EventLogEntity lastPosition = null;
            for (EventLogEntity event : events) {
                ObjectNode eventNode = JsonNodeFactory.instance.objectNode();
                eventNode.put("monitor_id", event.getId().getMonitorId());
                eventNode.put("monitor_detail_id", event.getId().getMonitorDetailId());
                eventNode.put("plugin_id", event.getId().getPluginId());
                eventNode.put("generation_date", event.getGenerationDate());
                eventNode.put("facility_id", event.getId().getFacilityId());
                eventNode.put("scope_text", event.getScopeText());
                eventNode.put("application", event.getApplication());
                eventNode.put("message", event.getMessage());
                eventNode.put("message_org", event.getMessageOrg());
                eventNode.put("priority", event.getPriority());
                eventNode.put("confirm_flg", event.getConfirmFlg());
                eventNode.put("confirm_date", event.getCommentDate());
                eventNode.put("confirm_user", event.getCommentUser());
                eventNode.put("duplication_count", event.getDuplicationCount());
                eventNode.put("output_date", event.getId().getOutputDate());
                eventNode.put("inhibited_flg", event.getInhibitedFlg());
                eventNode.put("comment_date", event.getCommentDate());
                eventNode.put("comment_user", event.getCommentUser());
                eventNode.put("comment", event.getComment());
                eventNode.put("position", event.getPosition());

                String url = binder.bind(event, urlStr);
                String data = eventNode.toString();
                try {
                    send(url, data);
                    lastPosition = event;

                    if (callback != null)
                        callback.onTransferred(lastPosition);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                    internalError_monitor(event.getId().getMonitorId(), data, e, url);
                    break;
                }
            }
            return lastPosition;
        }

        /*
         *  ID ??
         * 
         */
        @Override
        public String getDestTypeId() {
            return transfer_id;
        }

        /*
         * Fluentd ?????? HttpClient ??
         * ?????????
         * 
         */
        private CloseableHttpClient getHttpClient() {
            if (client == null) {
                client = createHttpClient();
            }
            return client;
        }

        /*
         * Fluentd ?????? HttpClient ??
         * 
         */
        private CloseableHttpClient createHttpClient() {
            String proxyHost = null;
            Integer proxyPort = null;
            CredentialsProvider cledentialProvider = null;
            List<String> ignoreHostList = new ArrayList<>();

            try {
                // Hinemos ???
                proxyHost = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.host", null);
                Long proxyPortLong = HinemosPropertyUtil.getHinemosPropertyNum("hub.fluentd.proxy.port", null);
                if (proxyPortLong != null)
                    proxyPort = proxyPortLong.intValue();
                if (proxyPort == null)
                    proxyPort = 80;
                String proxyUser = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.user", null);
                String proxyPassword = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.password",
                        null);

                if (proxyHost != null && proxyPort != null) {
                    logger.debug(
                            "initializing fluentd proxy : proxyHost = " + proxyHost + ", port = " + proxyPort);
                    String ignoreHostStr = HinemosPropertyUtil
                            .getHinemosPropertyStr("hub.fluentd.proxy.ignorehosts", null);
                    if (ignoreHostStr != null) {
                        ignoreHostList = Arrays.asList(ignoreHostStr.split(","));
                    }

                    if (proxyUser != null && proxyPassword != null) {
                        cledentialProvider = new BasicCredentialsProvider();
                        cledentialProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                                new UsernamePasswordCredentials(proxyUser, proxyPassword));
                    }
                }
            } catch (Throwable t) {
                logger.warn("invalid proxy configuration.", t);
                proxyHost = null;
                proxyPort = null;
                cledentialProvider = null;
                ignoreHostList = Collections.emptyList();
            }

            List<Header> headers = new ArrayList<>();
            HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(cledentialProvider)
                    .setDefaultHeaders(headers);

            Builder requestBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT);
            if (connectTimeout != null)
                requestBuilder.setConnectTimeout(connectTimeout);
            if (connectTimeout != null)
                requestBuilder.setSocketTimeout(requestTimeout);

            builder.setDefaultRequestConfig(requestBuilder.build());

            if (proxyHost != null) {
                Matcher m = urlPattern.matcher(urlStr);
                if (!m.matches())
                    throw new InternalError(String.format("invalid url(%s)", urlStr));

                m.toMatchResult();

                boolean ignore = false;
                String host = m.group("host");
                for (String ignoreHost : ignoreHostList) {
                    if (ignoreHost.equals(host)) {
                        ignore = true;
                        break;
                    }
                }

                if (!ignore) {
                    HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
                    builder.setProxy(proxy);
                }
            }

            if (keepAlive) {
                headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE));
            } else {
                headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
            }
            return builder.build();
        }

        /*
         * ?? URL ???
         * 
         */
        private void send(String url, String data) throws Exception {
            // URL  ?
            Matcher m = urlPattern.matcher(url);
            if (!m.matches())
                throw new InternalError(String.format("invalid url(%s)", urlStr));
            m.toMatchResult();
            String path = m.group("path");
            if (path != null && !path.isEmpty()) {
                String host = m.group("host");
                String port = m.group("port");

                String[] paths = path.split("/");
                for (int i = 1; i < paths.length; ++i) {
                    paths[i] = URLEncoder.encode(paths[i], "utf-8");
                }
                url = "http://" + host + (port == null || port.isEmpty() ? "" : (":" + port));
                for (int i = 1; i < paths.length; ++i) {
                    url += "/" + paths[i];
                }
            }

            HttpPost requestPost = new HttpPost(url);
            requestPost.addHeader("content-type", "application/json");
            requestPost.setEntity(new StringEntity(data, StandardCharsets.UTF_8));

            logger.debug(String.format("send() : request start. url=%s", url));

            int count = 0;
            int maxTryCount = PropertyConstants.hub_transfer_max_try_count.number();

            while (count < maxTryCount) {
                try {
                    long start = HinemosTime.currentTimeMillis();
                    try (CloseableHttpResponse response = getHttpClient().execute(requestPost)) {
                        long responseTime = HinemosTime.currentTimeMillis() - start;
                        logger.debug(String.format("send() : url=%s, responseTime=%d", url, responseTime));

                        int statusCode = response.getStatusLine().getStatusCode();
                        logger.debug(String.format("send() : url=%s, code=%d", url, statusCode));
                        if (statusCode == HttpStatus.SC_OK) {
                            logger.debug(String.format("send() : url=%s, success=%s", url,
                                    response.getStatusLine().toString()));
                            if (logger.isDebugEnabled()) {
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                try (InputStream in = response.getEntity().getContent()) {
                                    byte[] buffer = new byte[BUFF_SIZE];
                                    while (out.size() < BODY_MAX_SIZE) {
                                        int len = in.read(buffer);
                                        if (len < 0) {
                                            break;
                                        }
                                        out.write(buffer, 0, len);
                                    }
                                }
                                String res = new String(out.toByteArray(), "UTF-8");
                                if (!res.isEmpty())
                                    logger.debug(String.format("send() : url=%s, response=%s", url, res));
                            }
                        } else {
                            throw new RuntimeException(
                                    String.format("http status code isn't 200. code=%d, message=%s", statusCode,
                                            response.getStatusLine().toString()));
                        }
                    }

                    logger.debug(String.format("send() : success. url=%s, count=%d", url, count));
                    break;
                } catch (RuntimeException e) {
                    ++count;

                    if (count < maxTryCount) {
                        logger.debug(e.getMessage(), e);
                        logger.debug(String.format(
                                "send() : fail to send, and then wait to retry. url=%s, count=%d", url, count));
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e1) {
                            logger.debug(e.getMessage());
                        }
                    } else {
                        throw new TransferException(
                                String.format("send() : fail to send. url=%s, retry count=%d, error=\"%s\"",
                                        url, count, e.getMessage()));
                    }
                }
            }
        }

        @Override
        public void close() throws Exception {
            if (client != null)
                client.close();
        }

        private void internalError_session(String sessionId, String data, Exception error, String url) {
            internalError_session(sessionId, data,
                    error.getMessage() == null || error.getMessage().isEmpty()
                            ? error.getClass().getSimpleName()
                            : error.getMessage(),
                    url);
        }

        private void internalError_session(String sessionId, String data, String error, String url) {
            AplLogger.put(PriorityConstant.TYPE_WARNING, HinemosModuleConstant.HUB_TRANSFER,
                    MessageConstant.MESSAGE_HUB_DATA_TRANSFER_FAILED, new String[] { info.getTransferId() },
                    String.format("error=%s%ntransferId=%s%ndestTypeId=%s%nsessionId=%s%ndata=%s%nurl=%s",
                            error, info.getTransferId(), info.getDestTypeId(), sessionId, data, url));
        }

        private void internalError_monitor(String sessionId, String data, Exception error, String url) {
            internalError_monitor(sessionId, data,
                    error.getMessage() == null || error.getMessage().isEmpty()
                            ? error.getClass().getSimpleName()
                            : error.getMessage(),
                    url);
        }

        private void internalError_monitor(String monitorId, String data, String error, String url) {
            AplLogger.put(PriorityConstant.TYPE_WARNING, HinemosModuleConstant.HUB_TRANSFER,
                    MessageConstant.MESSAGE_HUB_DATA_TRANSFER_FAILED, new String[] { info.getTransferId() },
                    String.format("error=%s%ntransferId=%s%ndestTypeId=%s%nmonitorId=%s%ndata=%s%nurl=%s",
                            error, info.getTransferId(), info.getDestTypeId(), monitorId, data, url));
        }
    };
}

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpPktHandler.java

private void setOptionClasslessRoute(DHCP reply, DhcpInfo dhcpInfo) {
    List<HostRoutes> hostRoutes = dhcpInfo.getHostRoutes();
    if (hostRoutes == null) {
        //we can't set this option, so return
        return;/*  w ww  .  java  2s .c o m*/
    }
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    Iterator<HostRoutes> iter = hostRoutes.iterator();
    while (iter.hasNext()) {
        HostRoutes hostRoute = iter.next();
        if (hostRoute.getNexthop().getIpv4Address() == null
                || hostRoute.getDestination().getIpv4Prefix() == null) {
            // we only deal with IPv4 addresses
            return;
        }
        String router = hostRoute.getNexthop().getIpv4Address().getValue();
        String dest = hostRoute.getDestination().getIpv4Prefix().getValue();
        try {
            result.write(convertToClasslessRouteOption(dest, router));
        } catch (IOException | NullPointerException e) {
            LOG.debug("Exception {}", e.getMessage());
        }
    }
    if (result.size() > 0) {
        reply.setOptionBytes(DHCPConstants.OPT_CLASSLESS_ROUTE, result.toByteArray());
    }
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

/**
 * /* w ww. j  a va2  s  . c o m*/
 * @param message
 * @param type set to 5 when sending a PKI request, 3 when sending a PKIConf
 * @return
 * @throws IOException
 * @throws NoSuchProviderException
 */
protected byte[] sendCmpTcp(byte[] message, int type) throws IOException, NoSuchProviderException {
    final String host = getProperty("tcpCmpProxyIP", this.CMP_HOST);
    final int port = getProperty("tcpCmpProxyPort", PORT_NUMBER);
    try {
        final Socket socket = new Socket(host, port);

        final byte[] msg = createTcpMessage(message);
        try {
            final BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());
            os.write(msg);
            os.flush();

            DataInputStream dis = new DataInputStream(socket.getInputStream());

            // Read the length, 32 bits
            final int len = dis.readInt();
            log.info("Got a message claiming to be of length: " + len);
            // Read the version, 8 bits. Version should be 10 (protocol draft nr
            // 5)
            final int ver = dis.readByte();
            log.info("Got a message with version: " + ver);
            assertEquals(ver, 10);

            // Read flags, 8 bits for version 10
            final byte flags = dis.readByte();
            log.info("Got a message with flags (1 means close): " + flags);
            // Check if the client wants us to close the connection (LSB is 1 in
            // that case according to spec)

            // Read message type, 8 bits
            final int msgType = dis.readByte();
            log.info("Got a message of type: " + msgType);
            assertEquals(msgType, type);

            // Read message
            final ByteArrayOutputStream baos = new ByteArrayOutputStream(3072);
            while (dis.available() > 0) {
                baos.write(dis.read());
            }

            log.info("Read " + baos.size() + " bytes");
            final byte[] respBytes = baos.toByteArray();
            assertNotNull(respBytes);
            assertTrue(respBytes.length > 0);
            return respBytes;
        } finally {
            socket.close();
        }
    } catch (ConnectException e) {
        assertTrue("This test requires a CMP TCP listener to be configured on " + host + ":" + port
                + ". Edit conf/cmptcp.properties and redeploy.", false);
    } catch (EOFException e) {
        assertTrue("Response was malformed.", false);
    } catch (Exception e) {
        e.printStackTrace();
        assertTrue(false);
    }
    return null;
}

From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ByteArrayOutputStream dupIn = null;
    if (dumpRequests) {
        String qs = req.getQueryString();
        Logger.getAnonymousLogger().info(String.format("method: %s, requestUrl: %s", req.getMethod(),
                req.getRequestURL().append(qs != null ? "?" + URLDecoder.decode(qs, "UTF-8") : "").toString()

        ));//  w  ww  .ja  v  a2 s.com
        dupIn = new ByteArrayOutputStream();
        req = new AlternateInputHttpServletRequestWrapper(req,
                new InputStreamServletInputStream(new DuplicatingInputStream(req.getInputStream(), dupIn)));
    }
    long s = System.currentTimeMillis();
    try {
        super.service(req, res);
    } finally {
        long d = System.currentTimeMillis() - s;
        if (displayProcessTime) {
            Logger.getAnonymousLogger().info("processTime: " + d + "ms.");
        }
        if (dupIn != null && dupIn.size() > 0) {
            Logger.getAnonymousLogger()
                    .info(String.format("requestInput: %s", new String(dupIn.toByteArray(), "UTF-8")));
        }
    }
}