private Content handleEntity(final HttpEntity entity) throws IOException { Content content = null; if (entity != null) { content = new Content(EntityUtils.toByteArray(entity), ContentType.getOrDefault(entity)); } else { content = Content.NO_CONTENT; } return content; }
public HttpResponse returnResponse() throws IOException { assertNotConsumed(); try { HttpEntity entity = this.response.getEntity(); if (entity != null) { this.response.setEntity( new ByteArrayEntity(EntityUtils.toByteArray(entity), ContentType.getOrDefault(entity))); } return this.response; } finally { this.consumed = true; } }
private CoverallsResponse parseResponse(final HttpResponse response) throws ProcessingException, IOException { HttpEntity entity = response.getEntity(); ContentType contentType = ContentType.getOrDefault(entity); InputStreamReader reader = null; try { reader = new InputStreamReader(entity.getContent(), contentType.getCharset()); CoverallsResponse cr = objectMapper.readValue(reader, CoverallsResponse.class); if (cr.isError()) { throw new ProcessingException(getResponseErrorMessage(response, cr.getMessage())); } return cr; } catch (JsonProcessingException ex) { throw new ProcessingException(getResponseErrorMessage(response, ex.getMessage()), ex); } catch (IOException ex) { throw new IOException(getResponseErrorMessage(response, ex.getMessage()), ex); } finally { IOUtil.close(reader); } }
/** Loads the content of this page from a fetched HttpEntity. */ public void load(HttpEntity entity) throws Exception { contentType = null; Header type = entity.getContentType(); if (type != null) { contentType = type.getValue(); } contentEncoding = null; Header encoding = entity.getContentEncoding(); if (encoding != null) { contentEncoding = encoding.getValue(); } Charset charset = ContentType.getOrDefault(entity).getCharset(); if (charset != null) { contentCharset = charset.displayName(); } contentData = EntityUtils.toByteArray(entity); }
/** * Gets content type of response * * @param response request response * @return content type */ protected static ContentType getContentType(HttpResponse response) { return ContentType.getOrDefault(response.getEntity()); }
@Test public void testHttpContent() throws Exception { final String[] patterns = { "0123456789ABCDEF", "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" + "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that" }; // Initialize the server-side request handler this.server.registerHandler( "*", new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { int n = 1; String s = request.getRequestLine().getUri(); if (s.startsWith("/?n=")) { s = s.substring(4); try { n = Integer.parseInt(s); if (n <= 0) { throw new HttpException( "Invalid request: " + "number of repetitions cannot be negative or zero"); } } catch (final NumberFormatException ex) { throw new HttpException("Invalid request: " + "number of repetitions is invalid"); } } final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); final String line = EntityUtils.toString(incoming); final ContentType contentType = ContentType.getOrDefault(incoming); Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } final RepeatingEntity outgoing = new RepeatingEntity(line, charset, n); outgoing.setChunked(n % 2 == 0); response.setEntity(outgoing); } else { throw new HttpException("Invalid request: POST request expected"); } } }); this.server.start(); final DefaultBHttpClientConnection conn = client.createConnection(); final HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (final String pattern : patterns) { for (int n = 1000; n < 1020; n++) { if (!conn.isOpen()) { client.connect(host, conn); } final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/?n=" + n); final StringEntity outgoing = new StringEntity(pattern); outgoing.setChunked(n % 2 == 0); post.setEntity(outgoing); final HttpResponse response = this.client.execute(post, host, conn); final HttpEntity incoming = response.getEntity(); Assert.assertNotNull(incoming); final InputStream instream = incoming.getContent(); final ContentType contentType = ContentType.getOrDefault(incoming); Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } Assert.assertNotNull(instream); final BufferedReader reader = new BufferedReader(new InputStreamReader(instream, charset)); String line; int count = 0; while ((line = reader.readLine()) != null) { Assert.assertEquals(pattern, line); count++; } Assert.assertEquals(n, count); if (!this.client.keepAlive(response)) { conn.close(); } } } } finally { conn.close(); this.server.shutdown(); } }
@Override public AbstractStorageItem retrieveItem( final ProxyRepository repository, final ResourceStoreRequest request, final String baseUrl) throws ItemNotFoundException, RemoteStorageException { final URL remoteURL = appendQueryString( repository, request, getAbsoluteUrlFromBase(baseUrl, request.getRequestPath())); final String url = remoteURL.toExternalForm(); if (remoteURL.getPath().endsWith("/")) { // NEXUS-5125 we do not want to fetch any collection // Even though it is unlikely that we actually see a request for a collection here, // requests for paths like this over the REST layer will be localOnly not trigger a remote // request. // // The usual case is that there is a request for a directory that is redirected to '/', see // below behavior // for SC_MOVED_* throw new RemoteItemNotFoundException( request, repository, "remoteIsCollection", remoteURL.toString()); } final HttpGet method = new HttpGet(url); final HttpResponse httpResponse = executeRequest(repository, request, method, baseUrl, true); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream is; try { is = new Hc4InputStream( repository, new InterruptableInputStream(method, httpResponse.getEntity().getContent())); String mimeType = ContentType.getOrDefault(httpResponse.getEntity()).getMimeType(); if (mimeType == null) { mimeType = getMimeSupport() .guessMimeTypeFromPath(repository.getMimeRulesSource(), request.getRequestPath()); } final long entityLength = httpResponse.getEntity().getContentLength(); final DefaultStorageFileItem httpItem = new DefaultStorageFileItem( repository, request, CAN_READ, CAN_WRITE, new PreparedContentLocator( is, mimeType, entityLength != -1 ? entityLength : ContentLocator.UNKNOWN_LENGTH)); httpItem.setRemoteUrl(remoteURL.toString()); httpItem.setModified(makeDateFromHeader(httpResponse.getFirstHeader("last-modified"))); httpItem.setCreated(httpItem.getModified()); return httpItem; } catch (IOException ex) { release(httpResponse); throw new RemoteStorageException( "IO Error during response stream handling [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]!", ex); } catch (RuntimeException ex) { release(httpResponse); throw ex; } } else { release(httpResponse); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new RemoteItemNotFoundException( request, repository, "NotFound", remoteURL.toString()); } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY) { // NEXUS-5125 unfollowed redirect means collection (path.endsWith("/")) // see also HttpClientUtil#configure throw new RemoteItemNotFoundException( request, repository, "redirected", remoteURL.toString()); } else { throw new RemoteStorageException( "The method execution returned result code " + httpResponse.getStatusLine().getStatusCode() + " (expected 200). [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]"); } } }
@Override public ProblemAndTestCaseList importExercise(Course course, String exerciseHash) throws CloudCoderAuthenticationException { if (course == null || exerciseHash == null) { throw new IllegalArgumentException(); } // Make sure a user is authenticated User user = ServletUtil.checkClientIsAuthenticated( getThreadLocalRequest(), GetCoursesAndProblemsServiceImpl.class); // Find user's registration in the course: if user is not instructor, // import is not allowed CourseRegistrationList reg = Database.getInstance().findCourseRegistrations(user, course); if (!reg.isInstructor()) { throw new CloudCoderAuthenticationException( "Only an instructor can import a problem in a course"); } // Attempt to load the problem from the exercise repository. ConfigurationSetting repoUrlSetting = Database.getInstance().getConfigurationSetting(ConfigurationSettingName.PUB_REPOSITORY_URL); if (repoUrlSetting == null) { logger.error("Repository URL configuration setting is not set"); return null; } // GET the exercise from the repository HttpGet get = new HttpGet(repoUrlSetting.getValue() + "/exercisedata/" + exerciseHash); ProblemAndTestCaseList exercise = null; HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); ContentType contentType = ContentType.getOrDefault(entity); Reader reader = new InputStreamReader(entity.getContent(), contentType.getCharset()); exercise = new ProblemAndTestCaseList(); exercise.setTestCaseList(new TestCase[0]); JSONConversion.readProblemAndTestCaseData( exercise, ReflectionFactory.forClass(Problem.class), ReflectionFactory.forClass(TestCase.class), reader); // Set the course id exercise.getProblem().setCourseId(course.getId()); } catch (IOException e) { logger.error("Error importing exercise from repository", e); return null; } finally { client.getConnectionManager().shutdown(); } // Set "when assigned" and "when due" to reasonable default values long now = System.currentTimeMillis(); exercise.getProblem().setWhenAssigned(now); exercise.getProblem().setWhenDue(now + 48L * 60L * 60L * 1000L); // Set problem authorship as IMPORTED exercise.getProblem().setProblemAuthorship(ProblemAuthorship.IMPORTED); // For IMPORTED problems, parent_hash is actually the hash of the problem // itself. If the problem is modified (and the authorship changed // to IMPORTED_AND_MODIFIED), then the (unchanged) parent_hash value // really does reflect the "parent" problem. exercise.getProblem().setParentHash(exerciseHash); // Store the exercise in the database exercise = Database.getInstance().storeProblemAndTestCaseList(exercise, course, user); return exercise; }