Example usage for org.apache.http.protocol HTTP CONN_CLOSE

List of usage examples for org.apache.http.protocol HTTP CONN_CLOSE

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP CONN_CLOSE.

Prototype

String CONN_CLOSE

To view the source code for org.apache.http.protocol HTTP CONN_CLOSE.

Click Source Link

Usage

From source file:org.jsnap.http.base.HttpServlet.java

protected void doService(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response)
        throws HttpException, IOException {
    // Client might keep the executing thread blocked for very long unless this header is added.
    response.addHeader(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
    // Create a wrapped request object.
    String uri, data;//from w ww.ja v  a2 s .c o  m
    String method = request.getRequestLine().getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        BasicHttpRequest get = (BasicHttpRequest) request;
        data = get.getRequestLine().getUri();
        int ix = data.indexOf('?');
        uri = (ix < 0 ? data : data.substring(0, ix));
        data = (ix < 0 ? "" : data.substring(ix + 1));
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        BasicHttpEntityEnclosingRequest post = (BasicHttpEntityEnclosingRequest) request;
        HttpEntity postedEntity = post.getEntity();
        uri = post.getRequestLine().getUri();
        data = EntityUtils.toString(postedEntity);
    } else {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
        response.setHeader(new Header(HTTP.CONTENT_LEN, "0"));
        return;
    }
    String cookieLine = "";
    if (request.containsHeader(COOKIE)) {
        Header[] cookies = request.getHeaders(COOKIE);
        for (Header cookie : cookies) {
            if (cookieLine.length() > 0)
                cookieLine += "; ";
            cookieLine += cookie.getValue();
        }
    }
    HttpRequest req = new HttpRequest(uri, underlying, data, cookieLine);
    // Create a wrapped response object.
    ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
    HttpResponse resp = new HttpResponse(out);
    // Do implementation specific processing.
    doServiceImpl(req, resp);
    out.flush(); // It's good practice to do this.
    // Do the actual writing to the actual response object.
    if (resp.redirectTo != null) {
        // Redirection is requested.
        resp.statusCode = HttpStatus.SC_MOVED_TEMPORARILY;
        response.setStatusCode(resp.statusCode);
        Header redirection = new Header(LOCATION, resp.redirectTo);
        response.setHeader(redirection);
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, redirection.toString());
    } else {
        // There will be a response entity.
        response.setStatusCode(resp.statusCode);
        HttpEntity entity;
        Header contentTypeHeader;
        boolean text = resp.contentType.startsWith(Formatter.TEXT);
        if (text) { // text/* ...
            entity = new StringEntity(out.toString(resp.characterSet), resp.characterSet);
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE,
                    resp.contentType + HTTP.CHARSET_PARAM + resp.characterSet);
        } else { // application/octet-stream, image/* ...
            entity = new ByteArrayEntity(out.toByteArray());
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType);
        }
        boolean acceptsGzip = clientAcceptsGzip(request);
        long contentLength = entity.getContentLength();
        // If client accepts gzipped content, the implementing object requested that response
        // gets gzipped and size of the response exceeds implementing object's size threshold
        // response entity will be gzipped.
        boolean gzipped = false;
        if (acceptsGzip && resp.zipSize > 0 && contentLength >= resp.zipSize) {
            ByteArrayOutputStream zipped = new ByteArrayOutputStream(BUFFER_SIZE);
            GZIPOutputStream gzos = new GZIPOutputStream(zipped);
            entity.writeTo(gzos);
            gzos.close();
            entity = new ByteArrayEntity(zipped.toByteArray());
            contentLength = zipped.size();
            gzipped = true;
        }
        // This is where true writes are made.
        Header contentLengthHeader = new Header(HTTP.CONTENT_LEN, Long.toString(contentLength));
        Header contentEncodingHeader = null;
        response.setHeader(contentTypeHeader);
        response.setHeader(contentLengthHeader);
        if (gzipped) {
            contentEncodingHeader = new Header(CONTENT_ENCODING, Formatter.GZIP);
            response.setHeader(contentEncodingHeader);
        }
        response.setEntity(entity);
        // Log critical headers.
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentTypeHeader.toString());
        if (gzipped)
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentEncodingHeader.toString());
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentLengthHeader.toString());
    }
    // Log cookies.
    for (Cookie cookie : resp.cookies) {
        if (cookie.valid()) {
            Header h = new Header(SET_COOKIE, cookie.toString());
            response.addHeader(h);
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, h.toString());
        }
    }
}

From source file:android.core.TestEventHandler.java

/**
 * Implements the EventHandler headers method called when a server
 * sends header fields/* w w  w.ja va  2  s . c o m*/
 */
public void headers(Headers headers) {
    if (false) {
        Log.v(LOGTAG, "TestEventHandler:headers()");
    }
    expects[TEST_HEADERS] = false;

    if (notExpecting[TEST_HEADERS]) {
        expectDetails.append("Header event received but not expected");
        expectDetails.append("\r\n");
    }

    /* Check through headers received for matches with expected
     * headers */
    if (expectHeaders.isEmpty()) {
        return;
    }

    for (int i = expectHeaders.size() - 1; i >= 0; i--) {
        TestHeader h = expectHeaders.get(i);
        System.out.println("Expected header name: " + h.name);
        String s = null;
        switch (h.name.hashCode()) {
        case -1132779846:
            s = Long.toString(headers.getContentLength());
            break;
        case 785670158:
            s = headers.getContentType();
            break;
        case 2095084583:
            s = headers.getContentEncoding();
            break;
        case 1901043637:
            s = headers.getLocation();
            break;
        case -243037365:
            s = headers.getWwwAuthenticate();
            break;
        case -301767724:
            s = headers.getProxyAuthenticate();
            break;
        case -1267267485:
            s = headers.getContentDisposition();
            break;
        case 1397189435:
            s = headers.getAcceptRanges();
            break;
        case -1309235404:
            s = headers.getExpires();
            break;
        case -208775662:
            s = headers.getCacheControl();
            break;
        case 150043680:
            s = headers.getLastModified();
            break;
        case 3123477:
            s = headers.getEtag();
            break;
        case -775651618:
            int ct = headers.getConnectionType();
            if (ct == Headers.CONN_CLOSE) {
                s = HTTP.CONN_CLOSE;
            } else if (ct == Headers.CONN_KEEP_ALIVE) {
                s = HTTP.CONN_KEEP_ALIVE;
            }
            break;
        default:
            s = null;

        }
        if (evaluateHeader(h, s)) {
            expectHeaders.remove(i);
        }
    }

}

From source file:org.apache.synapse.transport.nhttp.Axis2HttpRequest.java

/**
 * Create and return a new HttpPost request to the destination EPR
 *
 * @return the HttpRequest to be sent out
 * @throws IOException in error retrieving the <code>HttpRequest</code>
 *///from   w ww .jav  a 2 s  . co  m
public HttpRequest getRequest() throws IOException, HttpException {
    String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
    if (httpMethod == null) {
        httpMethod = "POST";
    }
    endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);

    boolean forceHTTP10 = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0);
    HttpVersion httpver = forceHTTP10 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;

    HttpRequest httpRequest;

    try {
        if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {

            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            BasicHttpEntityEnclosingRequest requestWithEntity = new BasicHttpEntityEnclosingRequest(httpMethod,
                    uri.toASCIIString(), httpver);

            BasicHttpEntity entity = new BasicHttpEntity();

            if (forceHTTP10) {
                setStreamAsTempData(entity);
            } else {
                entity.setChunked(chunked);
                if (!chunked) {
                    setStreamAsTempData(entity);
                }
            }
            requestWithEntity.setEntity(entity);
            requestWithEntity.setHeader(HTTP.CONTENT_TYPE,
                    messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
            httpRequest = requestWithEntity;

        } else if ("GET".equals(httpMethod) || "DELETE".equals(httpMethod)) {

            URL url = messageFormatter.getTargetAddress(msgContext, format, new URL(epr.getAddress()));

            URI uri = rewriteRequestURI(url.toURI());
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
            /*GETs and DELETEs do not need Content-Type headers because they do not have payloads*/
            //httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
            //        msgContext, format, msgContext.getSoapAction()));

        } else {
            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
        }

    } catch (URISyntaxException ex) {
        throw new HttpException(ex.getMessage(), ex);
    }

    // set any transport headers
    Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof Map) {
        Map headers = (Map) o;
        for (Object header : headers.keySet()) {
            Object value = headers.get(header);
            if (header instanceof String && value != null && value instanceof String) {
                if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
                    httpRequest.setHeader((String) header, (String) value);

                    String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

                    Map map = (Map) msgContext.getProperty(excessProp);
                    if (map != null && map.get(header) != null) {
                        log.debug("Number of excess values for " + header + " header is : "
                                + ((Collection) (map.get(header))).size());

                        for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                            String key = (String) iterator.next();

                            for (String excessVal : (Collection<String>) map.get(key)) {
                                httpRequest.addHeader((String) header, (String) excessVal);
                            }

                        }
                    }

                } else {
                    if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) {
                        httpRequest.setHeader((String) header,
                                (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER));
                    }
                }

            }
        }
    }

    // if the message is SOAP 11 (for which a SOAPAction is *required*), and
    // the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
    // use that over any transport header that may be available
    String soapAction = msgContext.getSoapAction();
    if (soapAction == null) {
        soapAction = msgContext.getWSAAction();
    }
    if (soapAction == null) {
        msgContext.getAxisOperation().getInputAction();
    }

    if (msgContext.isSOAP11() && soapAction != null && soapAction.length() >= 0) {
        Header existingHeader = httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
        if (existingHeader != null) {
            httpRequest.removeHeader(existingHeader);
        }
        httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
                messageFormatter.formatSOAPAction(msgContext, null, soapAction));
    }

    if (NHttpConfiguration.getInstance().isKeepAliveDisabled()
            || msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
        httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    return httpRequest;
}

From source file:org.archive.modules.fetcher.FetchHTTPRequest.java

protected void configureRequestHeaders() {
    if (fetcher.getAcceptCompression()) {
        request.addHeader("Accept-Encoding", "gzip,deflate");
    }//from w w  w.  ja  v a 2 s .co m

    String from = fetcher.getUserAgentProvider().getFrom();
    if (StringUtils.isNotBlank(from)) {
        request.setHeader(HttpHeaders.FROM, from);
    }

    if (fetcher.getMaxLengthBytes() > 0 && fetcher.getSendRange()) {
        String rangeEnd = Long.toString(fetcher.getMaxLengthBytes() - 1);
        request.setHeader(HttpHeaders.RANGE, "bytes=0-" + rangeEnd);
    }

    if (fetcher.getSendConnectionClose()) {
        request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    // referer
    if (fetcher.getSendReferer() && !LinkContext.PREREQ_MISC.equals(curi.getViaContext())) {
        // RFC2616 says no referer header if referer is https and the url is not
        String via = Processor.flattenVia(curi);
        if (!StringUtils.isEmpty(via) && !(curi.getVia().getScheme().equals(FetchHTTP.HTTPS_SCHEME)
                && curi.getUURI().getScheme().equals(FetchHTTP.HTTP_SCHEME))) {
            request.setHeader(HttpHeaders.REFERER, via);
        }
    }

    if (!curi.isPrerequisite()) {
        maybeAddConditionalGetHeader(fetcher.getSendIfModifiedSince(), A_LAST_MODIFIED_HEADER,
                "If-Modified-Since");
        maybeAddConditionalGetHeader(fetcher.getSendIfNoneMatch(), A_ETAG_HEADER, "If-None-Match");
    }

    // TODO: What happens if below method adds a header already added above,
    // e.g. Connection, Range, or Referer?
    for (String headerString : fetcher.getAcceptHeaders()) {
        String[] nameValue = headerString.split(": +");
        if (nameValue.length == 2) {
            request.addHeader(nameValue[0], nameValue[1]);
        } else {
            logger.warning("Invalid accept header: " + headerString);
        }
    }

    if (curi.getViaContext() != null && "a[data-remote='true']/@href".equals(curi.getViaContext().toString())) {
        request.addHeader("X-Requested-With", "XMLHttpRequest");
    }

    /*
     * set custom request headers in last interceptor, so they override
     * anything else (this could just as well belong in
     * configureHttpClientBuilder())
     */
    httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            @SuppressWarnings("unchecked")
            Map<String, String> uriCustomHeaders = (Map<String, String>) curi.getData()
                    .get("customHttpRequestHeaders");
            if (uriCustomHeaders != null) {
                for (Entry<String, String> h : uriCustomHeaders.entrySet()) {
                    request.setHeader(h.getKey(), h.getValue());
                }
            }
        }
    });

}

From source file:com.jana.android.net.Headers.java

private void setConnectionType(CharArrayBuffer buffer, int pos) {
    if (CharArrayBuffers.containsIgnoreCaseTrimmed(buffer, pos, HTTP.CONN_CLOSE)) {
        connectionType = CONN_CLOSE;/* w  w  w.  ja v  a 2s .  com*/
    } else if (CharArrayBuffers.containsIgnoreCaseTrimmed(buffer, pos, HTTP.CONN_KEEP_ALIVE)) {
        connectionType = CONN_KEEP_ALIVE;
    }
}

From source file:org.wso2.carbon.bpel.core.ode.integration.utils.AxisServiceUtils.java

public static void addCustomHeadersToMessageContext(MessageContext mctx) {

    List<Header> headers = null;

    BPELServerConfiguration bpelServerConfiguration = BPELServiceComponent.getBPELServer()
            .getBpelServerConfiguration();

    if (!bpelServerConfiguration.isKeepAlive()) {

        headers = new ArrayList();
        headers.add(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
    }//from   w  w  w.j  av  a  2 s . c  o m

    //Add more custom header values in the future
    if ((headers != null) && (headers.size() > 0)) {
        mctx.setProperty(HTTPConstants.HTTP_HEADERS, headers);
    }
}

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

/**
 * ?????????//from ww  w  . j av  a  2  s  .c  om
 * 
 */
@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));
        }
    };
}