Search in sources :

Example 71 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project sling by apache.

the class TopologyConnectorClient method ping.

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    final HttpClientContext clientContext = HttpClientContext.create();
    final CloseableHttpClient httpClient = createHttpClient();
    final HttpPut putRequest = new HttpPut(uri);
    // setting the connection timeout (idle connection, configured in seconds)
    putRequest.setConfig(RequestConfig.custom().setConnectTimeout(1000 * config.getSocketConnectTimeout()).build());
    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            clientContext.getCredentialsProvider().setCredentials(new AuthScope(putRequest.getURI().getHost(), putRequest.getURI().getPort()), c);
        }
        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView;
        try {
            clusterView = clusterViewService.getLocalClusterView();
        } catch (UndefinedClusterViewException e) {
            // SLING-5030 : then we cannot ping
            logger.warn("ping: no clusterView available at the moment, cannot ping others now: " + e);
            return;
        }
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterView.getInstances().iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // all fine then
                        return true;
                    }
                }
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());
        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(putRequest, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            putRequest.addHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            putRequest.setEntity(new ByteArrayEntity(gzippedEncodedJson, ContentType.APPLICATION_JSON));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            final StringEntity plaintext = new StringEntity(p, "UTF-8");
            plaintext.setContentType(ContentType.APPLICATION_JSON.getMimeType());
            putRequest.setEntity(plaintext);
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        putRequest.addHeader("Accept-Encoding", "gzip");
        final CloseableHttpResponse response = httpClient.execute(putRequest, clientContext);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
        }
        lastStatusCode = response.getStatusLine().getStatusCode();
        lastResponseEncoding = null;
        if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            // limiting to 16MB, should be way enough
            final String responseBody = requestValidator.decodeMessage(putRequest.getURI().getPath(), response);
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:
                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("ping: connector response indicated a loop detected. not registering this announcement from " + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        if (config.isAutoStopLocalLoopEnabled()) {
                            // results in connected -> false and representsloop -> true
                            inheritedAnnouncement = null;
                            // results in isAutoStopped -> true
                            autoStopped = true;
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("ping: connector response is from an instance which I already see in my topology" + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JsonException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        putRequest.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("disconnect: could not close httpClient: " + e, e);
        }
    }
}
Also used : ClusterView(org.apache.sling.discovery.ClusterView) JsonException(javax.json.JsonException) Announcement(org.apache.sling.discovery.base.connectors.announcement.Announcement) AnnouncementFilter(org.apache.sling.discovery.base.connectors.announcement.AnnouncementFilter) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) GZIPOutputStream(java.util.zip.GZIPOutputStream) Iterator(java.util.Iterator) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Date(java.util.Date) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) AuthScope(org.apache.http.auth.AuthScope) UndefinedClusterViewException(org.apache.sling.discovery.base.commons.UndefinedClusterViewException) InstanceDescription(org.apache.sling.discovery.InstanceDescription) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 72 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project tika by apache.

the class TensorflowRESTRecogniser method recognise.

@Override
public List<RecognisedObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {
    List<RecognisedObject> recObjs = new ArrayList<>();
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(getApiUri(metadata));
        try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
            //TODO: convert this to stream, this might cause OOM issue
            // InputStreamEntity is not working
            // request.setEntity(new InputStreamEntity(stream, -1));
            IOUtils.copy(stream, byteStream);
            request.setEntity(new ByteArrayEntity(byteStream.toByteArray()));
        }
        HttpResponse response = client.execute(request);
        try (InputStream reply = response.getEntity().getContent()) {
            String replyMessage = IOUtils.toString(reply);
            if (response.getStatusLine().getStatusCode() == 200) {
                JSONObject jReply = new JSONObject(replyMessage);
                JSONArray jClasses = jReply.getJSONArray("classnames");
                JSONArray jConfidence = jReply.getJSONArray("confidence");
                if (jClasses.length() != jConfidence.length()) {
                    LOG.warn("Classes of size {} is not equal to confidence of size {}", jClasses.length(), jConfidence.length());
                }
                assert jClasses.length() == jConfidence.length();
                for (int i = 0; i < jClasses.length(); i++) {
                    RecognisedObject recObj = new RecognisedObject(jClasses.getString(i), LABEL_LANG, jClasses.getString(i), jConfidence.getDouble(i));
                    recObjs.add(recObj);
                }
            } else {
                LOG.warn("Status = {}", response.getStatusLine());
                LOG.warn("Response = {}", replyMessage);
            }
        }
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    LOG.debug("Num Objects found {}", recObjs.size());
    return recObjs;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) HttpResponse(org.apache.http.HttpResponse) RecognisedObject(org.apache.tika.parser.recognition.RecognisedObject) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) TikaException(org.apache.tika.exception.TikaException) TikaConfigException(org.apache.tika.exception.TikaConfigException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) JSONObject(org.json.JSONObject)

Example 73 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project cdap by caskdata.

the class AppFabricTestBase method addArtifact.

// add an artifact and return the response code
protected HttpResponse addArtifact(Id.Artifact artifactId, InputSupplier<? extends InputStream> artifactContents, Set<ArtifactRange> parents) throws Exception {
    String path = getVersionedAPIPath("artifacts/" + artifactId.getName(), artifactId.getNamespace().getId());
    HttpEntityEnclosingRequestBase request = getPost(path);
    request.setHeader(Constants.Gateway.API_KEY, "api-key-example");
    request.setHeader("Artifact-Version", artifactId.getVersion().getVersion());
    if (parents != null && !parents.isEmpty()) {
        request.setHeader("Artifact-Extends", Joiner.on('/').join(parents));
    }
    request.setEntity(new ByteArrayEntity(ByteStreams.toByteArray(artifactContents)));
    return execute(request);
}
Also used : HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity)

Example 74 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project cdap-ingest by caskdata.

the class RestStreamWriter method write.

@Override
public ListenableFuture<Void> write(ByteBuffer buffer, Map<String, String> headers) throws IllegalArgumentException {
    Preconditions.checkNotNull(buffer, "ByteBuffer parameter is null.");
    HttpEntity content;
    if (buffer.hasArray()) {
        content = new ByteArrayEntity(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
    } else {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        content = new ByteArrayEntity(bytes);
    }
    return write(content, headers);
}
Also used : HttpEntity(org.apache.http.HttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity)

Aggregations

ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)74 HttpEntity (org.apache.http.HttpEntity)25 HttpPost (org.apache.http.client.methods.HttpPost)22 HttpResponse (org.apache.http.HttpResponse)19 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 IOException (java.io.IOException)13 JSONObject (org.json.JSONObject)10 Test (org.junit.Test)10 HttpClient (org.apache.http.client.HttpClient)8 JSONArray (org.json.JSONArray)7 InputStream (java.io.InputStream)6 AbstractHttpEntity (org.apache.http.entity.AbstractHttpEntity)5 BytesRef (org.apache.lucene.util.BytesRef)5 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)5 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)5 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)5 GetRequest (org.elasticsearch.action.get.GetRequest)5 IndexRequest (org.elasticsearch.action.index.IndexRequest)5 WriteRequest (org.elasticsearch.action.support.WriteRequest)5 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)5