Package net.yacy.cora.protocol.http

Examples of net.yacy.cora.protocol.http.HTTPClient$IdledConnectionEvictor


            modifyProxyHeaders(requestHeader, httpVer);
           
            final String connectHost = hostPart(host, port, yAddress);
            final String getUrl = "http://"+ connectHost + remotePath;
           
            final HTTPClient client = setupHttpClient(requestHeader, connectHost);
           
            // send request
            try {
              client.GET(getUrl);
                if (log.isFinest()) log.logFinest(reqID +"    response status: "+ client.getHttpResponse().getStatusLine());
                conProp.put(HeaderFramework.CONNECTION_PROP_CLIENT_REQUEST_HEADER, requestHeader);

                final ResponseHeader responseHeader = new ResponseHeader(client.getHttpResponse().getAllHeaders());
                // determine if it's an internal error of the httpc
                if (responseHeader.isEmpty()) {
                  throw new Exception(client.getHttpResponse().getStatusLine().toString());
                }

                final ChunkedOutputStream chunkedOut = setTransferEncoding(conProp, responseHeader, client.getHttpResponse().getStatusLine().getStatusCode(), respond);

                // the cache does either not exist or is (supposed to be) stale
                long sizeBeforeDelete = -1;
                if (cachedResponseHeader != null) {
                    // delete the cache
                    ResponseHeader rh = Cache.getResponseHeader(url.hash());
                    if (rh != null && (sizeBeforeDelete = rh.getContentLength()) == 0) {
                        byte[] b = Cache.getContent(url.hash());
                        if (b != null) sizeBeforeDelete = b.length;
                    }
                    Cache.delete(url);
                    conProp.put(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_CODE, "TCP_REFRESH_MISS");
                }

                // reserver cache entry
                final Request request = new Request(
                  null,
                        url,
                        requestHeader.referer() == null ? null : new DigestURI(requestHeader.referer()).hash(),
                        "",
                        responseHeader.lastModified(),
                        sb.crawler.defaultProxyProfile.handle(),
                        0,
                        0,
                        0,
                        sizeBeforeDelete < 0 ? 0 : sizeBeforeDelete);
               

                // handle incoming cookies
                handleIncomingCookies(responseHeader, host, ip);

//                prepareResponseHeader(responseHeader, res.getHttpVer());
                prepareResponseHeader(responseHeader, client.getHttpResponse().getProtocolVersion().toString());

                // sending the respond header back to the client
                if (chunkedOut != null) {
                    responseHeader.put(HeaderFramework.TRANSFER_ENCODING, "chunked");
                }

                if (log.isFinest()) log.logFinest(reqID +"    sending response header: "+ responseHeader);
                HTTPDemon.sendRespondHeader(
                        conProp,
                        respond,
                        httpVer,
                        client.getHttpResponse().getStatusLine().getStatusCode(),
                        client.getHttpResponse().getStatusLine().toString(), // status text
                        responseHeader);

                if (hasBody(client.getHttpResponse().getStatusLine().getStatusCode())) {

                    final OutputStream outStream = chunkedOut != null ? chunkedOut : respond;
                    final Response response = new Response(
                            request,
                            requestHeader,
                            responseHeader,
                            Integer.toString(client.getHttpResponse().getStatusLine().getStatusCode()),
                            sb.crawler.defaultProxyProfile
                    );
                    final String storeError = response.shallStoreCacheForProxy();
                    final boolean storeHTCache = response.profile().storeHTCache();
                    final String supportError = TextParser.supports(response.url(), response.getMimeType());
                    if (
                            /*
                             * Now we store the response into the htcache directory if
                             * a) the response is cacheable AND
                             */
                            (storeError == null) &&
                            /*
                             * b) the user has configured to use the htcache OR
                             * c) the content should be indexed
                             */
                            ((storeHTCache) || (supportError != null))
                    ) {
                        // we don't write actually into a file, only to RAM, and schedule writing the file.
//                        int l = res.getResponseHeader().size();
                      int l = responseHeader.size();
                        final ByteArrayOutputStream byteStream = new ByteArrayOutputStream((l < 32) ? 32 : l);

                        final OutputStream toClientAndMemory = new MultiOutputStream(new OutputStream[] {outStream, byteStream});
//                        FileUtils.copy(res.getDataAsStream(), toClientAndMemory);
                        client.writeTo(toClientAndMemory);
                        // cached bytes
                        byte[] cacheArray;
                        if (byteStream.size() > 0) {
                            cacheArray = byteStream.toByteArray();
                        } else {
                            cacheArray = null;
                        }
                        if (log.isFine()) log.logFine(reqID +" writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length)));

                        if (sizeBeforeDelete == -1) {
                            // totally fresh file
                            response.setContent(cacheArray);
                            try {
                                Cache.store(response.url(), response.getResponseHeader(), cacheArray);
                                sb.toIndexer(response);
                            } catch (IOException e) {
                                log.logWarning("cannot write " + response.url() + " to Cache (1): " + e.getMessage(), e);
                            }
                            conProp.put(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_CODE, "TCP_MISS");
                        } else if (cacheArray != null && sizeBeforeDelete == cacheArray.length) {
                            // before we came here we deleted a cache entry
                            cacheArray = null;
                            //cacheManager.push(cacheEntry); // unnecessary update
                            conProp.put(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_CODE, "TCP_REF_FAIL_HIT");
                        } else {
                            // before we came here we deleted a cache entry
                            response.setContent(cacheArray);
                            try {
                                Cache.store(response.url(), response.getResponseHeader(), cacheArray);
                                sb.toIndexer(response);
                            } catch (IOException e) {
                                log.logWarning("cannot write " + response.url() + " to Cache (2): " + e.getMessage(), e);
                            }
                            conProp.put(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_CODE, "TCP_REFRESH_MISS");
                        }
                    } else {
                        // no caching
                        if (log.isFine()) log.logFine(reqID +" "+ url.toString() + " not cached." +
                                " StoreError=" + ((storeError==null)?"None":storeError) +
                                " StoreHTCache=" + storeHTCache +
                                " SupportError=" + supportError);

//                        FileUtils.copy(res.getDataAsStream(), outStream);
                        client.writeTo(outStream);

                        conProp.put(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS");
                    }

                    if (chunkedOut != null) {
                        chunkedOut.finish();
                        chunkedOut.flush();
                    }
                } // end hasBody
            } catch(SocketException se) {
                // if opened ...
//                if(res != null) {
//                    // client cut proxy connection, abort download
//                    res.abort();
//                }
              client.finish();
                handleProxyException(se,conProp,respond,url);
            } finally {
                // if opened ...
//                if(res != null) {
//                    // ... close connection
//                    res.closeStream();
//                }
              client.finish();
            }
        } catch (final Exception e) {
            handleProxyException(e,conProp,respond,url);
        }
    }
View Full Code Here


            // generate request-url
            final String connectHost = hostPart(host, port, yAddress);
            final String getUrl = "http://"+ connectHost + remotePath;
            if (log.isFinest()) log.logFinest(reqID +"    using url: "+ getUrl);
           
            final HTTPClient client = setupHttpClient(requestHeader, connectHost);
           
            // send request
//            try {
//            res = client.HEAD(getUrl);
//            if (log.isFinest()) log.logFinest(reqID +"    response status: "+ res.getStatusLine());
            client.HEADResponse(getUrl);
            if (log.isFinest()) log.logFinest(reqID +"    response status: "+ client.getHttpResponse().getStatusLine());
           
            // determine if it's an internal error of the httpc
//            final ResponseHeader responseHeader = res.getResponseHeader();
//            if (responseHeader.isEmpty()) {
//                throw new Exception(res.getStatusLine());
//            }     
            final ResponseHeader responseHeader = new ResponseHeader(client.getHttpResponse().getAllHeaders());
            if (responseHeader.isEmpty()) {
                throw new Exception(client.getHttpResponse().getStatusLine().toString());
            }
           
//            prepareResponseHeader(responseHeader, res.getHttpVer());
            prepareResponseHeader(responseHeader, client.getHttpResponse().getStatusLine().getProtocolVersion().toString());

            // sending the server respond back to the client
            if (log.isFinest()) log.logFinest(reqID +"    sending response header: "+ responseHeader);
//            HTTPDemon.sendRespondHeader(conProp,respond,httpVer,res.getStatusCode(),res.getStatusLine().substring(4),responseHeader);
            HTTPDemon.sendRespondHeader(
                conProp,
                respond,
                httpVer,
                client.getHttpResponse().getStatusLine().getStatusCode(),
                client.getHttpResponse().getStatusLine().toString(),
                responseHeader);
            respond.flush();
//            } finally {
//                if(res != null) {
//                    // ... close connection
View Full Code Here

           
            // the CONTENT_LENGTH will be added by entity and cause a ClientProtocolException if set
            final int contentLength = requestHeader.getContentLength();
            requestHeader.remove(HeaderFramework.CONTENT_LENGTH);
           
            final HTTPClient client = setupHttpClient(requestHeader, connectHost);
           
            // check input
            if(body == null) {
                log.logSevere("no body to POST!");
            }
            try {
              // sending the request
              client.POST(getUrl, body, contentLength);
              if (log.isFinest()) log.logFinest(reqID +"    response status: "+ client.getHttpResponse().getStatusLine());
             
              final ResponseHeader responseHeader = new ResponseHeader(client.getHttpResponse().getAllHeaders());
              // determine if it's an internal error of the httpc
              if (responseHeader.isEmpty()) {
                throw new Exception(client.getHttpResponse().getStatusLine().toString());
              }                                 
             
              final ChunkedOutputStream chunked = setTransferEncoding(conProp, responseHeader, client.getHttpResponse().getStatusLine().getStatusCode(), countedRespond);
             
              prepareResponseHeader(responseHeader, client.getHttpResponse().getProtocolVersion().toString());
             
              // sending the respond header back to the client
              if (chunked != null) {
                  responseHeader.put(HeaderFramework.TRANSFER_ENCODING, "chunked");
              }
             
              // sending response headers
              if (log.isFinest()) log.logFinest(reqID +"    sending response header: "+ responseHeader);
              HTTPDemon.sendRespondHeader(conProp,
                        countedRespond,
                        httpVer,
                        client.getHttpResponse().getStatusLine().getStatusCode(),
                        client.getHttpResponse().getStatusLine().toString(), // status text
                        responseHeader);
             
              final OutputStream outStream = (chunked != null) ? chunked : countedRespond;
              client.writeTo(outStream);
             
              if (chunked != null) {
                  chunked.finish();
              }
              outStream.flush();
            } catch(SocketException se) {
          // connection closed by client, abort download
              client.finish();
            } finally {
              client.finish();
            }
        } catch (final Exception e) {
            handleProxyException(e,conProp,countedRespond,url);                
        } finally {
            if(countedRespond != null) {
View Full Code Here

     * @param connectHost may be 'host:port' or 'host:port/path'
     * @return
     */
    private static HTTPClient setupHttpClient(final RequestHeader requestHeader, final String connectHost) {
        // setup HTTP-client
      final HTTPClient client = new HTTPClient();
      client.setTimout(timeout);
      client.setHeader(requestHeader.entrySet());
      client.setRedirecting(false);
        return client;
    }
View Full Code Here

            return;
        }
   
        // possibly branch into PROXY-PROXY connection
        if (ProxySettings.use && ProxySettings.use4ssl) {
          final HTTPClient remoteProxy = setupHttpClient(requestHeader, host);
   
            try {
              remoteProxy.HEADResponse("http://" + host + ":" + port);
              ResponseHeader header = new ResponseHeader(remoteProxy.getHttpResponse().getAllHeaders());
             
                // outputs a logline to the serverlog with the current status
              log.logInfo("CONNECT-RESPONSE: status=" + remoteProxy.getHttpResponse().getStatusLine() + ", header=" + header.toString());
              final boolean success = remoteProxy.getHttpResponse().getStatusLine().getStatusCode() >= 200 && remoteProxy.getHttpResponse().getStatusLine().getStatusCode() <= 399;
                if (success) {
                    // replace connection details
                    host = ProxySettings.host;
                    port = ProxySettings.port;
                    // go on (see below)
                } else {
                    // pass error response back to client
                  HTTPDemon.sendRespondHeader(
                      conProp,
                      clientOut,
                      httpVersion,
                      remoteProxy.getHttpResponse().getStatusLine().getStatusCode(),
                      remoteProxy.getHttpResponse().getStatusLine().toString(),
                      header);
                    //respondHeader(clientOut, response.status, response.responseHeader);
                    forceConnectionClose(conProp);
                    return;
                }
View Full Code Here

        final RequestHeader reqHeader = new RequestHeader();
        reqHeader.put(HeaderFramework.PRAGMA, "no-cache");
        reqHeader.put(HeaderFramework.CACHE_CONTROL, "no-cache"); // httpc uses HTTP/1.0 is this necessary?
        reqHeader.put(HeaderFramework.USER_AGENT, ClientIdentification.getUserAgent());
       
        final HTTPClient client = new HTTPClient();
        client.setHeader(reqHeader.entrySet());
        byte[] content = null;
        try {
            // send request
          content = client.GETbytes(seedURL);
        } catch (final Exception e) {
          throw new IOException("Unable to download seed file '" + seedURL + "'. " + e.getMessage());
        }
           
        // check response code
        if (client.getHttpResponse().getStatusLine().getStatusCode() != 200) {
          throw new IOException("Server returned status: " + client.getHttpResponse().getStatusLine());
        }
           
        try {
            // uncompress it if it is gzipped
            content = FileUtils.uncompressGZipArray(content);
View Full Code Here

        reqHeader.put(HeaderFramework.USER_AGENT, ClientIdentification.getUserAgent());

        final String name = getUrl().getFileName();
        byte[] signatureBytes = null;

        final HTTPClient client = new HTTPClient();
        client.setTimout(6000);
        client.setHeader(reqHeader.entrySet());

        // download signature first, if public key is available
        try {
            if (this.publicKey != null) {
              final byte[] signatureData = client.GETbytes(getUrl().toString() + ".sig");
                if (signatureData == null) {
                    Log.logWarning("yacyVersion", "download of signature " + getUrl().toString() + " failed. ignoring signature file.");
                }
                else signatureBytes = Base64Order.standardCoder.decode(UTF8.String(signatureData).trim());
            }
            client.setTimout(120000);
            client.GET(getUrl().toString());
            final ResponseHeader header = new ResponseHeader(client.getHttpResponse().getAllHeaders());

            final boolean unzipped = header.gzip() && (header.mime().toLowerCase().equals("application/x-tar")); // if true, then the httpc has unzipped the file
            if ((unzipped) && (name.endsWith(".tar.gz"))) {
                download = new File(storagePath, name.substring(0, name.length() - 3));
            } else {
                download = new File(storagePath, name);
            }
            if (this.publicKey != null && signatureBytes != null) {
                // copy to file and check signature
                SignatureOutputStream verifyOutput = null;
                try {
                    verifyOutput = new SignatureOutputStream(new FileOutputStream(download), CryptoLib.signAlgorithm, this.publicKey);
                    client.writeTo(new BufferedOutputStream(verifyOutput));

                    if (!verifyOutput.verify(signatureBytes)) throw new IOException("Bad Signature!");
                } catch (final NoSuchAlgorithmException e) {
                    throw new IOException("No such algorithm");
                } catch (final SignatureException e) {
                    throw new IOException("Signature exception");
                } finally {
                    if (verifyOutput != null)
                    verifyOutput.close();
                }
                // Save signature
                final File signatureFile = new File(download.getAbsoluteFile() + ".sig");
                FileUtils.copy(UTF8.getBytes(Base64Order.standardCoder.encode(signatureBytes)), signatureFile);
                if ((!signatureFile.exists()) || (signatureFile.length() == 0)) throw new IOException("create signature file failed");
            } else {
                // just copy into file
                client.writeTo(new BufferedOutputStream(new FileOutputStream(download)));
            }
            if ((!download.exists()) || (download.length() == 0)) throw new IOException("wget of url " + getUrl() + " failed");
        } catch (final IOException e) {
            // Saving file failed, abort download
            Log.logSevere("yacyVersion", "download of " + getName() + " failed: " + e.getMessage());
            if (download != null && download.exists()) {
                FileUtils.deletedelete(download);
                if (download.exists()) Log.logWarning("yacyVersion", "could not delete file "+ download);
            }
            download = null;
        } finally {
          try {
        client.finish();
      } catch (final IOException e) {
        Log.logSevere("yacyVersion", "finish of " + getName() + " failed: " + e.getMessage());
      }
        }
        this.releaseFile = download;
View Full Code Here

    }
    private static byte[] postToFile(final yacySeedDB seedDB, final String targetHash, final String filename, final Map<String,ContentBody> parts, final int timeout) throws IOException {
      return postToFile(seedDB.targetAddress(targetHash), targetHash, filename, parts, timeout);
    }
    private static byte[] postToFile(final String targetAddress, final String targetPeerHash, final String filename, final Map<String,ContentBody> parts, final int timeout) throws IOException {
        final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), timeout);
        return httpClient.POSTbytes(new MultiProtocolURI("http://" + targetAddress + "/yacy/" + filename), yacySeed.b64Hash2hexHash(targetPeerHash) + ".yacyh", parts, false);
    }
View Full Code Here

            parts.put("magic", UTF8.StringBody(Long.toString(yacyCore.magic)));
            parts.put("seed", UTF8.StringBody(mySeed.genSeedStr(salt)));
            // send request
            final long start = System.currentTimeMillis();
            // final byte[] content = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + address + "/yacy/hello.html"), 30000, yacySeed.b64Hash2hexHash(otherHash) + ".yacyh", parts);
            final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), 30000);
            final byte[] content = httpClient.POSTbytes(new MultiProtocolURI("http://" + address + "/yacy/hello.html"), yacySeed.b64Hash2hexHash(otherHash) + ".yacyh", parts, false);
            yacyCore.log.logInfo("yacyClient.hello thread '" + Thread.currentThread().getName() + "' contacted peer at " + address + ", received " + ((content == null) ? "null" : content.length) + " bytes, time = " + (System.currentTimeMillis() - start) + " milliseconds");
            result = FileUtils.table(content);
        } catch (final Exception e) {
            if (Thread.currentThread().isInterrupted()) {
                yacyCore.log.logInfo("yacyClient.hello thread '" + Thread.currentThread().getName() + "' interrupted.");
View Full Code Here

            final Map<String,ContentBody> parts = yacyNetwork.basicRequestParts(Switchboard.getSwitchboard(), target.hash, salt);
            parts.put("call", UTF8.StringBody("remotecrawl"));
            parts.put("count", UTF8.StringBody(Integer.toString(maxCount)));
            parts.put("time", UTF8.StringBody(Long.toString(maxTime)));
            // final byte[] result = HTTPConnector.getConnector(MultiProtocolURI.yacybotUserAgent).post(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/urls.xml"), (int) maxTime, target.getHexHash() + ".yacyh", parts);
            final HTTPClient httpClient = new HTTPClient(ClientIdentification.getUserAgent(), (int) maxTime);
            final byte[] result = httpClient.POSTbytes(new MultiProtocolURI("http://" + target.getClusterAddress() + "/yacy/urls.xml"), target.getHexHash() + ".yacyh", parts, false);
            final RSSReader reader = RSSReader.parse(RSSFeed.DEFAULT_MAXSIZE, result);
            if (reader == null) {
                yacyCore.log.logWarning("yacyClient.queryRemoteCrawlURLs failed asking peer '" + target.getName() + "': probably bad response from remote peer (1), reader == null");
                target.put(yacySeed.RCOUNT, "0");
                seedDB.update(target.hash, target); // overwrite number of remote-available number to avoid that this peer is called again (until update is done by peer ping)
View Full Code Here

TOP

Related Classes of net.yacy.cora.protocol.http.HTTPClient$IdledConnectionEvictor

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.