/** * Read the next byte from the stream * @return The next byte or -1 if the end of stream has been reached. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read() */ @Override public int read() throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } int b = this.in.read(); if (b == -1) { if (pos < contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + contentLength + "; received: " + pos); } } else { pos++; } return b; }
/** * Does standard {@link InputStream#read(byte[], int, int)} behavior, but * also notifies the watcher when the contents have been consumed. * * @param b The byte array to fill. * @param off Start filling at this position. * @param len The number of bytes to attempt to read. * @return The number of bytes read, or -1 if the end of content has been * reached. * * @throws java.io.IOException Should an error occur on the wrapped stream. */ @Override public int read (byte[] b, int off, int len) throws java.io.IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } if (pos + len > contentLength) { len = (int) (contentLength - pos); } int count = this.in.read(b, off, len); if (count == -1 && pos < contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + contentLength + "; received: " + pos); } if (count > 0) { pos += count; } return count; }
/** * Read the next byte from the stream * @return The next byte or -1 if the end of stream has been reached. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read() */ @Override public int read() throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } final int b = this.in.read(); if (b == -1) { if (pos < contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + contentLength + "; received: " + pos); } } else { pos++; } return b; }
/** * Does standard {@link InputStream#read(byte[], int, int)} behavior, but * also notifies the watcher when the contents have been consumed. * * @param b The byte array to fill. * @param off Start filling at this position. * @param len The number of bytes to attempt to read. * @return The number of bytes read, or -1 if the end of content has been * reached. * * @throws java.io.IOException Should an error occur on the wrapped stream. */ @Override public int read (final byte[] b, final int off, final int len) throws java.io.IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } int chunk = len; if (pos + len > contentLength) { chunk = (int) (contentLength - pos); } final int count = this.in.read(b, off, chunk); if (count == -1 && pos < contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + contentLength + "; received: " + pos); } if (count > 0) { pos += count; } return count; }
public boolean urlSave(String url,Long fileSize, Long startIndex,Long endIndex, String outputFilePath, SimpleProgressBar bar, boolean isPart,StreamReqeustVO srVo) throws ConnectionClosedException, SocketTimeoutException, ConnectException { File file = definedVideoFile(srVo, outputFilePath, fileSize, bar, isPart); File tempFile = new File(outputFilePath + ".download"); Long received = createTmpFile(srVo, tempFile, bar); if (received < fileSize) { StreamReqeustVO newSrvo = setResumePoint(srVo, received,startIndex,endIndex); HttpResponse response = byHttpGet(url,newSrvo); if (response == null || response.getStatusLine().getStatusCode() > 300){ logger.info("{} response is illegal",srVo.getUrl()); return false; } boolean result = writeVideoFile(newSrvo, response, tempFile, received, bar, fileSize); if (!result) return false; } reName(file, tempFile); return true; }
private String findFaultClassifier(final String id) { if (registry.isRegistered(id, FaultClassifier.class)) { return generateBeanName(id, FaultClassifier.class); } else if (registry.isRegistered(FaultClassifier.class)) { return generateBeanName(FaultClassifier.class); } else { return registry.registerIfAbsent(FaultClassifier.class, () -> { final List<Predicate<Throwable>> predicates = list(); predicates.addAll(FaultClassifier.defaults()); predicates.add(ConnectionClosedException.class::isInstance); predicates.add(NoHttpResponseException.class::isInstance); return genericBeanDefinition(FaultClassifier.class) .setFactoryMethod("create") .addConstructorArgValue(predicates); }); } }
private void acceptClient(@NotNull Socket client) throws IOException { final SessionInputBuffer inputBuffer = wrapInputStream(client.getInputStream()); final HttpMessageParser<HttpRequest> parser = new DefaultHttpRequestParser(inputBuffer, new BasicLineParser(), new DefaultHttpRequestFactory(), MessageConstraints.DEFAULT ); final SessionOutputBuffer outputBuffer = wrapOutputStream(client.getOutputStream()); final HttpMessageWriter<HttpResponse> writer = new DefaultHttpResponseWriter(outputBuffer); while (!socket.isClosed()) { try { service(inputBuffer, outputBuffer, parser, writer); } catch (ConnectionClosedException ignored) { break; } catch (HttpException e) { log.error(e.getMessage(), e); break; } } }
@Override public void log(final Exception ex) { if (ex instanceof SocketTimeoutException || ex instanceof ConnectionClosedException) { // Do nothing } else { ex.printStackTrace(); } }
@Override protected HttpRequest parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new ConnectionClosedException("Client closed connection"); } ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor); return this.requestFactory.newHttpRequest(requestline); }
@Override protected HttpMessage parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new ConnectionClosedException("Client closed connection"); } ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor); return this.requestFactory.newHttpRequest(requestline); }
@Override public BackgroundException map(final IOException failure) { if(failure instanceof ConnectionClosedException) { final StringBuilder buffer = new StringBuilder(); this.append(buffer, failure.getMessage()); return new ConnectionRefusedException(buffer.toString(), failure); } return super.map(failure); }
@Override protected HttpRequest parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); final int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new ConnectionClosedException("Client closed connection"); } final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); final RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor); return this.requestFactory.newHttpRequest(requestline); }
@Bean public Http exampleHttp(final AsyncClientHttpRequestFactory requestFactory, final ClientHttpMessageConverters converters, final GaugeService gaugeService, final ScheduledExecutorService scheduler) { return Http.builder() .baseUrl("https://www.example.com") .urlResolution(UrlResolution.RFC) .requestFactory(requestFactory) .converters(converters.getConverters()) .plugin(new MetricsPlugin(gaugeService, new ZMONMetricsNameGenerator())) .plugin(new TransientFaultPlugin( FaultClassifier.create(ImmutableList.<Predicate<Throwable>>builder() .addAll(FaultClassifier.defaults()) .add(ConnectionClosedException.class::isInstance) .add(NoHttpResponseException.class::isInstance) .build()))) .plugin(new FailsafePlugin(scheduler) .withRetryPolicy(new RetryPolicy() .retryOn(TransientFaultException.class) .withBackoff(50, 2000, MILLISECONDS) .withMaxRetries(10) .withMaxDuration(2, SECONDS) .withJitter(0.2)) .withCircuitBreaker(new CircuitBreaker() .withFailureThreshold(5, 5) .withDelay(30, SECONDS) .withSuccessThreshold(3, 5) .withTimeout(3, SECONDS))) .plugin(new BackupRequestPlugin(scheduler, 10, MILLISECONDS)) .plugin(new TimeoutPlugin(scheduler, 3, SECONDS)) .plugin(new OriginalStackTracePlugin()) .plugin(new CustomPlugin()) .build(); }
private void performRequest(String url, Integer expectedStatus) throws IOException { try { ClientRequest.performRequest(url, expectedStatus); } catch (NoHttpResponseException | SocketException | ConnectionClosedException e) { e.printStackTrace(); if (expectedStatus != null) { fail(); } } }
@Override public void log(final Exception ex) { if (ex instanceof SocketTimeoutException) { Dbg.err("Connection timed out"); } else if (ex instanceof ConnectionClosedException) { Dbg.err("Connection closed: " + ex.getMessage()); } else { ex.printStackTrace(); } }
public static long copy( final InputStream inputStream, final WritableByteChannel writableByteChannel, final int bufferSize, final String objName, final boolean isPutCommand) throws IOException { final byte[] buffer = new byte[bufferSize]; final ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); int len; long totalBytes = 0; final long startTime = PerformanceUtils.getCurrentTime(); long statusUpdateTime = startTime; try { while ((len = inputStream.read(buffer)) != -1) { totalBytes += len; try { byteBuffer.position(0); byteBuffer.limit(len); writableByteChannel.write(byteBuffer); } catch (final Throwable t) { throw new UnrecoverableIOException(t); } final long curTime = PerformanceUtils.getCurrentTime(); if (statusUpdateTime <= curTime) { PerformanceUtils.logMbpsStatus(startTime, curTime, totalBytes, objName, isPutCommand); statusUpdateTime += 60000D; //Only logs status once a minute } } } catch (final ConnectionClosedException e) { LOG.error("Connection closed trying to copy from stream to channel.", e); } return totalBytes; }
/** * Expects the stream to start with a chunksize in hex with optional * comments after a semicolon. The line must end with a CRLF: "a3; some * comment\r\n" Positions the stream at the start of the next line. */ private long getChunkSize() throws IOException { final int st = this.state; switch (st) { case CHUNK_CRLF: this.buffer.clear(); final int bytesRead1 = this.in.readLine(this.buffer); if (bytesRead1 == -1) { throw new MalformedChunkCodingException( "CRLF expected at end of chunk"); } if (!this.buffer.isEmpty()) { throw new MalformedChunkCodingException( "Unexpected content at the end of chunk"); } state = CHUNK_LEN; //$FALL-THROUGH$ case CHUNK_LEN: this.buffer.clear(); final int bytesRead2 = this.in.readLine(this.buffer); if (bytesRead2 == -1) { throw new ConnectionClosedException("Premature end of chunk coded message body: " + "closing chunk expected"); } int separator = this.buffer.indexOf(';'); if (separator < 0) { separator = this.buffer.length(); } final String s = this.buffer.substringTrimmed(0, separator); try { return Long.parseLong(s, 16); } catch (final NumberFormatException e) { throw new MalformedChunkCodingException("Bad chunk header: " + s); } default: throw new IllegalStateException("Inconsistent codec state"); } }
private static boolean isPrematureEndException(Throwable exception) { return exception instanceof ConnectionClosedException && exception.getMessage() != null && exception.getMessage().startsWith("Premature end of Content-Length"); }