List of usage examples for org.apache.http.entity ContentType getCharset
public Charset getCharset()
From source file:de.drv.dsrv.spoc.web.service.impl.SpocResponseHandler.java
/** * Versucht, das Charset des Payloads aus dem HTTP-Header * <code>Content-Type</code> zu bestimmen. * /*from ww w .j a va 2 s. c om*/ * @param httpResponseEntity * die Response des Fachverfahrens * * @return das in der Response verwendete Charset, oder <code>null</code>, * wenn kein Charset bestimmt werden konnte */ private Charset getCharsetFromResponse(final HttpEntity httpResponseEntity) { ContentType contentType; try { contentType = ContentType.get(httpResponseEntity); } catch (final RuntimeException exc) { LOG.warn("Fehler beim Auslesen des Content-Types aus der Response.", exc); return null; } if (contentType == null) { if (LOG.isInfoEnabled()) { LOG.info( "Es konnte kein Content-Type und somit auch kein Charset aus der Response gelesen werden."); } return null; } return contentType.getCharset(); }
From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.playback.GerritMissedEventsPlaybackManager.java
/** * * @param config Gerrit config for server. * @param url URL to use.//w w w .jav a 2 s . c om * @return String of gerrit events. */ protected String getEventsFromEventsLogPlugin(IGerritHudsonTriggerConfig config, String url) { logger.debug("({}) Going to GET: {}", serverName, url); HttpResponse execute = null; try { execute = HttpUtils.performHTTPGet(config, url); } catch (IOException e) { logger.warn(e.getMessage(), e); return ""; } int statusCode = execute.getStatusLine().getStatusCode(); logger.debug("Received status code: {} for server: {}", statusCode, serverName); if (statusCode == HttpURLConnection.HTTP_OK) { try { HttpEntity entity = execute.getEntity(); if (entity != null) { ContentType contentType = ContentType.get(entity); if (contentType == null) { contentType = ContentType.DEFAULT_TEXT; } Charset charset = contentType.getCharset(); if (charset == null) { charset = Charset.defaultCharset(); } InputStream bodyStream = entity.getContent(); String body = IOUtils.toString(bodyStream, charset.name()); logger.debug(body); return body; } } catch (IOException ioe) { logger.warn(ioe.getMessage(), ioe); } } logger.warn("Not successful at requesting missed events from {} plugin. (errorcode: {})", EVENTS_LOG_PLUGIN_NAME, statusCode); return ""; }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public void download(String url, ContentType contentType, String content, Header[] headers, final IFileHandler handler) throws Exception { RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create() .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET : contentType.getCharset().name()) .setContentType(contentType).setText(content).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); }/*w ww .java 2 s .co m*/ } __doExecHttpDownload(_reqBuilder, handler); }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse post(String url, ContentType contentType, byte[] content, Header[] headers) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {// w w w . ja v a 2s .co m RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create() .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET : contentType.getCharset().name()) .setContentType(contentType).setBinary(content).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java
@Test public void testPutRequestFormat() throws Exception { HttpServlet servlet = new HttpServlet() { @Override// www . ja va 2s . c o m protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ContentType contentType = ContentType.parse(req.getContentType()); if (!contentType.getMimeType().equals(EtcdClientImpl.FORM_URLENCODED.getMimeType())) { throw new IllegalArgumentException("wrong mime type"); } if (!contentType.getCharset().equals(EtcdClientImpl.FORM_URLENCODED.getCharset())) { throw new IllegalArgumentException("wrong content charset"); } String value = req.getParameter("value"); if (value == null) { throw new IllegalArgumentException("missing value parameter"); } String ttl = req.getParameter("ttl"); if (!"10".equals(ttl)) { throw new IllegalArgumentException("missing ttl parameter"); } res.setStatus(201); res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/action-3.json"))); } }; server1 = startServer(servlet, "/v2/keys/post/test"); buildEtcdClient(serverPort(server1)); KeyResponse response = etcdClient.putKey("/post/test", "test-data", Collections.singletonMap("ttl", "10")); Assert.assertNotNull(response); Assert.assertTrue(response.isAction()); }
From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java
@Test public void testPostRequestFormat() throws Exception { HttpServlet servlet = new HttpServlet() { @Override//from ww w .jav a 2 s. c o m protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ContentType contentType = ContentType.parse(req.getContentType()); if (!contentType.getMimeType().equals(EtcdClientImpl.FORM_URLENCODED.getMimeType())) { throw new IllegalArgumentException("wrong mime type"); } if (!contentType.getCharset().equals(EtcdClientImpl.FORM_URLENCODED.getCharset())) { throw new IllegalArgumentException("wrong content charset"); } String value = req.getParameter("value"); if (value == null) { throw new IllegalArgumentException("missing value parameter"); } String ttl = req.getParameter("ttl"); if (!"10".equals(ttl)) { throw new IllegalArgumentException("missing ttl parameter"); } res.setStatus(201); res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/action-3.json"))); } }; server1 = startServer(servlet, "/v2/keys/post/test"); buildEtcdClient(serverPort(server1)); KeyResponse response = etcdClient.postKey("/post/test", "test-data", Collections.singletonMap("ttl", "10")); Assert.assertNotNull(response); Assert.assertTrue(response.isAction()); }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse post(String url, ContentType contentType, String content, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {/*from w w w.j av a2 s. c om*/ RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create() .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET : contentType.getCharset().name()) .setContentType(contentType).setText(content).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse post(String url, ContentType contentType, InputStream content, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {//from w w w .j a v a 2 s .c o m RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create() .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET : contentType.getCharset().name()) .setContentType(contentType).setStream(content).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:org.cloudcoder.app.server.rpc.GetCoursesAndProblemsServiceImpl.java
@Override public ProblemAndTestCaseList importExercise(Course course, String exerciseHash) throws CloudCoderAuthenticationException { if (course == null || exerciseHash == null) { throw new IllegalArgumentException(); }//from w w w .ja v a2s .co m // 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; }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse post(String url, ContentType contentType, Map<String, String> params, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {/*from w w w . ja v a2 s .c o m*/ RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create() .setContentType(contentType) .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET : contentType.getCharset().name()) .setParameters(__doBuildNameValuePairs(params)).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }