List of usage examples for org.apache.http.entity ContentType TEXT_PLAIN
ContentType TEXT_PLAIN
To view the source code for org.apache.http.entity ContentType TEXT_PLAIN.
Click Source Link
From source file:com.questdb.test.tools.HttpTestUtils.java
private static int upload(File file, String url, String schema, StringBuilder response) throws IOException { HttpPost post = new HttpPost(url); try (CloseableHttpClient client = HttpClients.createDefault()) { MultipartEntityBuilder b = MultipartEntityBuilder.create(); if (schema != null) { b.addPart("schema", new StringBody(schema, ContentType.TEXT_PLAIN)); }//from w ww. ja v a2s .c om b.addPart("data", new FileBody(file)); post.setEntity(b.build()); HttpResponse r = client.execute(post); if (response != null) { InputStream is = r.getEntity().getContent(); int n; while ((n = is.read()) > 0) { response.append((char) n); } is.close(); } return r.getStatusLine().getStatusCode(); } }
From source file:hspc.submissionsprogram.AppDisplay.java
AppDisplay() { this.setTitle("Dominion High School Programming Contest"); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.setResizable(false); WindowListener exitListener = new WindowAdapter() { @Override// www. j a v a 2 s . c o m public void windowClosing(WindowEvent e) { System.exit(0); } }; this.addWindowListener(exitListener); JTabbedPane pane = new JTabbedPane(); this.add(pane); JPanel submitPanel = new JPanel(null); submitPanel.setPreferredSize(new Dimension(500, 500)); UIManager.put("FileChooser.readOnly", true); JFileChooser fileChooser = new JFileChooser(); fileChooser.setBounds(0, 0, 500, 350); fileChooser.setVisible(true); FileNameExtensionFilter javaFilter = new FileNameExtensionFilter("Java files (*.java)", "java"); fileChooser.setFileFilter(javaFilter); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setControlButtonsAreShown(false); submitPanel.add(fileChooser); JSeparator separator1 = new JSeparator(); separator1.setBounds(12, 350, 476, 2); separator1.setForeground(new Color(122, 138, 152)); submitPanel.add(separator1); JLabel problemChooserLabel = new JLabel("Problem:"); problemChooserLabel.setBounds(12, 360, 74, 25); submitPanel.add(problemChooserLabel); String[] listOfProblems = Main.Configuration.get("problem_names") .split(Main.Configuration.get("name_delimiter")); JComboBox problems = new JComboBox<>(listOfProblems); problems.setBounds(96, 360, 393, 25); submitPanel.add(problems); JButton submit = new JButton("Submit"); submit.setBounds(170, 458, 160, 30); submit.addActionListener(e -> { try { File file = fileChooser.getSelectedFile(); try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost(Main.Configuration.get("submit_url")); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("accountID", Main.accountID, ContentType.TEXT_PLAIN); builder.addTextBody("problem", String.valueOf(problems.getSelectedItem()), ContentType.TEXT_PLAIN); builder.addBinaryBody("submission", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(uploadFile); HttpEntity responseEntity = response.getEntity(); String inputLine; BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent())); try { if ((inputLine = br.readLine()) != null) { int rowIndex = Integer.parseInt(inputLine); new ResultWatcher(rowIndex); } br.close(); } catch (IOException ex) { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } } catch (NullPointerException ex) { JOptionPane.showMessageDialog(this, "No file selected.\nPlease select a java file.", "Error", JOptionPane.WARNING_MESSAGE); } }); submitPanel.add(submit); JPanel clarificationsPanel = new JPanel(null); clarificationsPanel.setPreferredSize(new Dimension(500, 500)); cList = new JList<>(); cList.setBounds(12, 12, 476, 200); cList.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)), BorderFactory.createEmptyBorder(8, 8, 8, 8))); cList.setBackground(new Color(254, 254, 255)); clarificationsPanel.add(cList); JButton viewC = new JButton("View"); viewC.setBounds(12, 224, 232, 25); viewC.addActionListener(e -> { if (cList.getSelectedIndex() != -1) { int id = Integer.parseInt(cList.getSelectedValue().split("\\.")[0]); clarificationDatas.stream().filter(data -> data.getId() == id).forEach( data -> new ClarificationDisplay(data.getProblem(), data.getText(), data.getResponse())); } }); clarificationsPanel.add(viewC); JButton refreshC = new JButton("Refresh"); refreshC.setBounds(256, 224, 232, 25); refreshC.addActionListener(e -> updateCList(true)); clarificationsPanel.add(refreshC); JSeparator separator2 = new JSeparator(); separator2.setBounds(12, 261, 476, 2); separator2.setForeground(new Color(122, 138, 152)); clarificationsPanel.add(separator2); JLabel problemChooserLabelC = new JLabel("Problem:"); problemChooserLabelC.setBounds(12, 273, 74, 25); clarificationsPanel.add(problemChooserLabelC); JComboBox problemsC = new JComboBox<>(listOfProblems); problemsC.setBounds(96, 273, 393, 25); clarificationsPanel.add(problemsC); JTextArea textAreaC = new JTextArea(); textAreaC.setLineWrap(true); textAreaC.setWrapStyleWord(true); textAreaC.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)), BorderFactory.createEmptyBorder(8, 8, 8, 8))); textAreaC.setBackground(new Color(254, 254, 255)); JScrollPane areaScrollPane = new JScrollPane(textAreaC); areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setBounds(12, 312, 477, 134); clarificationsPanel.add(areaScrollPane); JButton submitC = new JButton("Submit Clarification"); submitC.setBounds(170, 458, 160, 30); submitC.addActionListener(e -> { if (textAreaC.getText().length() > 2048) { JOptionPane.showMessageDialog(this, "Clarification body is too long.\nMaximum of 2048 characters allowed.", "Error", JOptionPane.WARNING_MESSAGE); } else if (textAreaC.getText().length() < 20) { JOptionPane.showMessageDialog(this, "Clarification body is too short.\nClarifications must be at least 20 characters, but no more than 2048.", "Error", JOptionPane.WARNING_MESSAGE); } else { Connection conn = null; PreparedStatement stmt = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(Main.Configuration.get("jdbc_mysql_address"), Main.Configuration.get("mysql_user"), Main.Configuration.get("mysql_pass")); String sql = "INSERT INTO clarifications (team, problem, text) VALUES (?, ?, ?)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, Integer.parseInt(String.valueOf(Main.accountID))); stmt.setString(2, String.valueOf(problemsC.getSelectedItem())); stmt.setString(3, String.valueOf(textAreaC.getText())); textAreaC.setText(""); stmt.executeUpdate(); stmt.close(); conn.close(); updateCList(false); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception ex2) { ex2.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (Exception ex2) { ex2.printStackTrace(); } } } }); clarificationsPanel.add(submitC); pane.addTab("Submit", submitPanel); pane.addTab("Clarifications", clarificationsPanel); Timer timer = new Timer(); TimerTask updateTask = new TimerTask() { @Override public void run() { updateCList(false); } }; timer.schedule(updateTask, 10000, 10000); updateCList(false); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); }
From source file:com.qwazr.cluster.client.ClusterSingleClient.java
@Override public String getActiveNodeRandomByService(String service_name, String group) { try {/*from w ww . ja v a 2s . c o m*/ UBuilder uriBuilder = new UBuilder("/cluster/services/" + service_name + "/active/random") .setParameter("group", group); Request request = Request.Get(uriBuilder.build()); HttpResponse response = execute(request, null, null); HttpUtils.checkStatusCodes(response, 200); return IOUtils.toString(HttpUtils.checkIsEntity(response, ContentType.TEXT_PLAIN).getContent()); } catch (IOException e) { throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR); } }
From source file:org.wisdom.framework.vertx.FormTest.java
@Test public void testFormSubmissionAsMultipart() throws InterruptedException, IOException { Router router = prepareServer();//from ww w. ja va 2s . c om // Prepare the router with a controller Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result submit() { final Map<String, List<String>> form = context().form(); // String if (!form.get("key").get(0).equals("value")) { return badRequest("key is not equals to value"); } // Multiple values List<String> list = form.get("list"); if (!(list.contains("1") && list.contains("2"))) { return badRequest("list does not contains 1 and 2"); } return ok(context().header(HeaderNames.CONTENT_TYPE)); } }; Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "submit"); when(router.getRouteFor(anyString(), anyString(), any(org.wisdom.api.http.Request.class))) .thenReturn(route); server.start(); waitForStart(server); int port = server.httpPort(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("key", "value", ContentType.TEXT_PLAIN).addTextBody("list", "1", ContentType.TEXT_PLAIN) .addTextBody("list", "2", ContentType.TEXT_PLAIN); final HttpResponse response = Request.Post("http://localhost:" + port + "/").body(builder.build()).execute() .returnResponse(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); assertThat(EntityUtils.toString(response.getEntity())).contains(MimeTypes.MULTIPART); }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static List<Notification> getNotifications(String serverId, String mirthVersion, Map<String, String> extensionVersions, String[] protocols, String[] cipherSuites) throws Exception { CloseableHttpClient client = null;/*from w ww . j a v a 2 s .c om*/ HttpPost post = new HttpPost(); CloseableHttpResponse response = null; List<Notification> allNotifications = new ArrayList<Notification>(); try { ObjectMapper mapper = new ObjectMapper(); String extensionVersionsJson = mapper.writeValueAsString(extensionVersions); NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_GET), new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("extensionVersions", extensionVersionsJson) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { HttpEntity responseEntity = response.getEntity(); Charset responseCharset = null; try { responseCharset = ContentType.getOrDefault(responseEntity).getCharset(); } catch (Exception e) { responseCharset = ContentType.TEXT_PLAIN.getCharset(); } String responseContent = IOUtils.toString(responseEntity.getContent(), responseCharset).trim(); JsonNode rootNode = mapper.readTree(responseContent); for (JsonNode childNode : rootNode) { Notification notification = new Notification(); notification.setId(childNode.get("id").asInt()); notification.setName(childNode.get("name").asText()); notification.setDate(childNode.get("date").asText()); notification.setContent(childNode.get("content").asText()); allNotifications.add(notification); } } else { throw new ClientException("Status code: " + statusCode); } } catch (Exception e) { throw e; } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return allNotifications; }
From source file:com.salesforce.dva.argus.service.callback.DefaultCallbackService.java
private HttpEntity body(DefaultAlertService.NotificationContext context, CallbackService.Request request) { if (request.body() != null) { StringEntity entity;//from ww w. java 2 s . c o m String body = request.body(); if (request.template() == Template.ST4) { ST st = new ST(request.body(), delimiterStart, delimiterEnd); st.add("alert", context.getAlert()); st.add("trigger", context.getTrigger()); st.add("coolDownExpiration", context.getCoolDownExpiration()); st.add("notification", context.getNotification()); st.add("triggerFiredTime", context.getTriggerFiredTime()); st.add("triggerEventValue", context.getTriggerEventValue()); st.add("triggeredMetric", context.getTriggeredMetric()); body = st.render(); } if (request.header().containsKey(HttpHeaders.CONTENT_TYPE)) { entity = new StringEntity(body, ContentType.parse(request.header().get(HttpHeaders.CONTENT_TYPE))); } else { entity = new StringEntity(body, ContentType.TEXT_PLAIN); } return entity; } return null; }
From source file:com.qwazr.cluster.client.ClusterSingleClient.java
@Override public String getActiveNodeMasterByService(String service_name, String group) { try {/* w ww. j a v a 2 s . co m*/ UBuilder uriBuilder = new UBuilder("/cluster/services/" + service_name + "/active/master") .setParameter("group", group); Request request = Request.Get(uriBuilder.build()); HttpResponse response = execute(request, null, null); HttpUtils.checkStatusCodes(response, 200); return IOUtils.toString(HttpUtils.checkIsEntity(response, ContentType.TEXT_PLAIN).getContent()); } catch (IOException e) { throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR); } }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
public HttpResponse execute(HttpRequest request) throws IOException { URI uri = createURI(request); HttpRequestBase internalRequest;//from w ww. j av a 2 s . co m if (request.method == HttpMethod.HEAD) { internalRequest = new HttpHead(uri); } else { HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name()); if (request.hasBody()) { ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8)); String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE); if (Strings.hasLength(contentType)) { entity.setContentType(contentType); } else { entity.setContentType(ContentType.TEXT_PLAIN.toString()); } methodWithEntity.setEntity(entity); } internalRequest = methodWithEntity; } internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name()); // headers if (request.headers().isEmpty() == false) { for (Map.Entry<String, String> entry : request.headers.entrySet()) { internalRequest.setHeader(entry.getKey(), entry.getValue()); } } // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header! if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) { XContentType xContentType = XContentFactory.xContentType(request.body()); if (xContentType != null) { internalRequest.setHeader("Content-Type", xContentType.mediaType()); } } RequestConfig.Builder config = RequestConfig.custom(); setProxy(config, request, settingsProxy); HttpClientContext localContext = HttpClientContext.create(); // auth if (request.auth() != null) { ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port)); localContext.setCredentialsProvider(credentialsProvider); // preemptive auth, no need to wait for a 401 first AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth); localContext.setAuthCache(authCache); } // timeouts if (request.connectionTimeout() != null) { config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis())); } else { config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis())); } if (request.readTimeout() != null) { config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis())); } else { config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis())); } internalRequest.setConfig(config.build()); try (CloseableHttpResponse response = SocketAccess .doPrivileged(() -> client.execute(internalRequest, localContext))) { // headers Header[] headers = response.getAllHeaders(); Map<String, String[]> responseHeaders = new HashMap<>(headers.length); for (Header header : headers) { if (responseHeaders.containsKey(header.getName())) { String[] old = responseHeaders.get(header.getName()); String[] values = new String[old.length + 1]; System.arraycopy(old, 0, values, 0, old.length); values[values.length - 1] = header.getValue(); responseHeaders.put(header.getName(), values); } else { responseHeaders.put(header.getName(), new String[] { header.getValue() }); } } final byte[] body; // not every response has a content, i.e. 204 if (response.getEntity() == null) { body = new byte[0]; } else { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { try (InputStream is = new SizeLimitInputStream(maxResponseSize, response.getEntity().getContent())) { Streams.copy(is, outputStream); } body = outputStream.toByteArray(); } } return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders); } }
From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java
/** * Trains the ranker using the trainingdata.csv * //from ww w . ja v a2s .co m * @param ranker_url URL associated with the ranker Ex.) * "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers" * @param rankerName The name of the ranker, to be sent as metadata * @param client {@link HttpClient} to send the request to * @param training_file Path to the trainingdata.csv * @return JSON of the result: { "name": "example-ranker", "url": * "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers/6C76AF-ranker-43", * "ranker_id": "6C76AF-ranker-43", "created": "2015-09-21T18:01:57.393Z", "status": * "Training", "status_description": * "The ranker instance is in its training phase, not yet ready to accept requests" } * @throws IOException */ public static String trainRanker(String ranker_url, String rankerName, HttpClient client, StringBuffer training_data) throws IOException { // Create a POST request HttpPost post = new HttpPost(ranker_url); MultipartEntityBuilder postParams = MultipartEntityBuilder.create(); // Add data String metadata = "\"" + rankerName + "\""; StringBody metadataBody = new StringBody(metadata, ContentType.TEXT_PLAIN); postParams.addPart(RetrieveAndRankSearcherConstants.TRAINING_DATA_LABEL, new AnswerFileBody(training_data.toString())); postParams.addPart(RetrieveAndRankSearcherConstants.TRAINING_METADATA_LABEL, metadataBody); post.setEntity(postParams.build()); // Obtain and parse response HttpResponse response = client.execute(post); String result = getHttpResultString(response); return result; }