List of usage examples for java.io DataOutputStream write
public synchronized void write(int b) throws IOException
b
) to the underlying output stream. From source file:org.cloudata.core.client.scanner.SingleTabletScanner.java
protected SingleTabletScanner(final CloudataConf conf, final TabletInfo tabletInfo, final RowFilter rowFilter) throws IOException { this.tabletInfo = tabletInfo; //ScanFilter ? column? . if (rowFilter.getCellFilters().size() == 0) { throw new IOException("No column in RowFilter"); }/*w w w . ja v a2 s . c o m*/ this.rowFilter = rowFilter; this.columnName = rowFilter.getColumns()[0]; String hostName = tabletInfo.getAssignedHostName(); int index = hostName.indexOf(":"); String host = hostName.substring(0, index); InetSocketAddress targetAddr = null; try { DataServiceProtocol tabletServer = CTableManager.connectTabletServer(hostName, conf); String port = tabletServer.getTabletServerConf("tabletServer.scanner.port"); targetAddr = NetworkUtil.getAddress(host + ":" + port); } catch (IOException e) { LOG.error("Can't connect to " + hostName + "," + e.getMessage()); throw e; } try { socket = new Socket(); socket.connect(targetAddr, READ_TIMEOUT); socket.setSoTimeout(READ_TIMEOUT); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); out.write(Constants.OPEN_SCANNER); CWritableUtils.writeString(out, tabletInfo.getTabletName()); CWritableUtils.writeString(out, columnName); rowFilter.write(out); out.flush(); in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); byte successOpen = (byte) in.read(); if (successOpen == Constants.SCANNER_OPEN_FAIL) { String errorMessage = CWritableUtils.readString(in); in.close(); throw new IOException(errorMessage); } String scannerId = CWritableUtils.readString(in); touchThread = new Thread(new LeaseTouchThread(conf, tabletInfo.getAssignedHostName(), scannerId)); touchThread.setName( "ScannerLeaseTouchThread_" + tabletInfo.getTabletName() + "_" + System.currentTimeMillis()); touchThread.start(); } catch (SocketException e) { this.close(); //LOG.warn("Scan open error cause:" + e.getMessage() + ", tablet=" + tabletInfo); throw e; } catch (IOException e) { this.close(); //LOG.warn("Scan open error cause:" + e.getMessage() + ", tablet=" + tabletInfo, e); throw e; } catch (Exception e) { //LOG.warn("Scan open error cause:" + e.getMessage() + ", tablet=" + tabletInfo, e); throw new IOException(e.getMessage(), e); } }
From source file:com.amazon.alexa.avs.auth.companionapp.OAuth2ClientForPkce.java
JsonObject postRequest(HttpURLConnection connection, String data) throws IOException { int responseCode = -1; InputStream error = null;//from w w w .j a v a 2 s.co m InputStream response = null; DataOutputStream outputStream = null; connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(data.getBytes(StandardCharsets.UTF_8)); outputStream.flush(); outputStream.close(); responseCode = connection.getResponseCode(); try { response = connection.getInputStream(); JsonReader reader = Json.createReader(new InputStreamReader(response, StandardCharsets.UTF_8)); return reader.readObject(); } catch (IOException ioException) { error = connection.getErrorStream(); if (error != null) { LWAException lwaException = new LWAException(IOUtils.toString(error), responseCode); throw lwaException; } else { throw ioException; } } finally { IOUtils.closeQuietly(error); IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(response); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.GenericCandidaciesDA.java
public ActionForward downloadRecomendationFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final String confirmationCode = (String) getFromRequest(request, "confirmationCode"); final GenericApplicationLetterOfRecomentation file = getDomainObject(request, "fileExternalId"); if (file != null && file.getRecomentation() != null && file.getRecomentation().getConfirmationCode() != null && ((file.getRecomentation().getGenericApplication().getGenericApplicationPeriod() .isCurrentUserAllowedToMange()) || file.getRecomentation().getConfirmationCode().equals(confirmationCode))) { response.setContentType(file.getContentType()); response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\""); response.setContentLength(file.getSize().intValue()); final DataOutputStream dos = new DataOutputStream(response.getOutputStream()); dos.write(file.getContent()); dos.close();//from w w w . j av a 2 s .c o m } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST)); response.getWriter().close(); } return null; }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.GenericCandidaciesDA.java
public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final GenericApplication application = getDomainObject(request, "applicationExternalId"); final String confirmationCode = (String) getFromRequest(request, "confirmationCode"); final GenericApplicationFile file = getDomainObject(request, "fileExternalId"); if (application != null && file != null && file.getGenericApplication() == application && ((confirmationCode != null && application.getConfirmationCode() != null && application.getConfirmationCode().equals(confirmationCode)) || application.getGenericApplicationPeriod().isCurrentUserAllowedToMange())) { response.setContentType(file.getContentType()); response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\""); response.setContentLength(file.getSize().intValue()); final DataOutputStream dos = new DataOutputStream(response.getOutputStream()); dos.write(file.getContent()); dos.close();//from w w w . j ava 2 s. c o m } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST)); response.getWriter().close(); } return null; }
From source file:com.github.abilityapi.abilityapi.external.Metrics.java
/** * Sends the data to the bStats server./*ww w . ja va 2 s . co m*/ * * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(JsonObject data) throws Exception { Validate.notNull(data, "Data cannot be null"); HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); connection.getInputStream().close(); // We don't care about the response - Just send our data :) }
From source file:org.bibsonomy.rest.client.worker.impl.GetWorker.java
/** * Download the file// w w w . j ava2 s .c o m * @param url * @param file * @throws ErrorPerformingRequestException * @author Waldemar Biller */ public void performFileDownload(final String url, File file) throws ErrorPerformingRequestException { LOGGER.debug("GET: URL: " + url); // dirty but working if (this.proxyHost != null) { getHttpClient().getHostConfiguration().setProxy(this.proxyHost, this.proxyPort); } final GetMethod get = new GetMethod(url); get.addRequestHeader(HeaderUtils.HEADER_AUTHORIZATION, HeaderUtils.encodeForAuthorization(this.username, this.apiKey)); get.setDoAuthentication(true); get.setFollowRedirects(true); try { this.httpResult = getHttpClient().executeMethod(get); LOGGER.debug("HTTP result: " + this.httpResult); LOGGER.debug("Content-Type:" + get.getRequestHeaders("Content-Type")); LOGGER.debug("==================================================="); final InputStream in = get.getResponseBodyAsStream(); /* * FIXME: check for errors */ if (in != null) { // read the file from the source and write it to // the target given by the file parametetr final DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(file))); int bytesRead = 0; int b = 0; do { b = in.read(); dos.write(b); callCallback(bytesRead++, get.getResponseContentLength()); } while (b > -1); in.close(); dos.close(); return; } } catch (final IOException e) { LOGGER.debug(e.getMessage(), e); throw new ErrorPerformingRequestException(e); } finally { get.releaseConnection(); } throw new ErrorPerformingRequestException("No Answer."); }
From source file:com.machinelinking.api.client.APIClient.java
private InputStream sendRequest(String service, String group, Map<String, Object> properties) throws IOException { try {//from ww w .ja v a2 s.c o m URL url = new URL(service); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(connTimeout); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); properties.put(ParamsValidator.app_id, appId); properties.put(ParamsValidator.app_key, appKey); StringBuilder data = ParamsValidator.getInstance().buildRequest(group, properties); httpURLConnection.addRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(data.toString().getBytes()); dataOutputStream.close(); if (httpURLConnection.getResponseCode() == 200) { return httpURLConnection.getInputStream(); } else { return httpURLConnection.getErrorStream(); } } catch (MalformedURLException e) { throw new IllegalStateException(e); } }
From source file:com.facebook.infrastructure.db.Column.java
public void serialize(IColumn column, DataOutputStream dos) throws IOException { dos.writeUTF(column.name());/* ww w. j a v a2 s . c o m*/ dos.writeBoolean(column.isMarkedForDelete()); dos.writeLong(column.timestamp()); dos.writeInt(column.value().length); dos.write(column.value()); }
From source file:org.eclipse.smila.integration.solr.SolrIndexPipelet.java
@Override public String[] process(final Blackboard blackboard, final String[] recordIds) throws ProcessingException { final String updateURL = HTTP_LOCALHOST + SOLR_WEBAPP + UPDATE; String updateXMLMessage = null; URL url = null;//from w w w. j a v a2 s . c om HttpURLConnection conn = null; String logId = null; try { url = new URL(updateURL); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(POST); conn.setRequestProperty(CONTENT_TYPE, TEXT_XML_CHARSET + UTF8); conn.setUseCaches(false); conn.setDoOutput(true); conn.setDoInput(true); conn.setReadTimeout(10000); } catch (final Exception e) { final String msg = "Error while opening Solr connection: '" + e.getMessage() + "'"; _log.error(msg, e); throw new ProcessingException(msg, e); } try { final DOMImplementation impl = DOMImplementationImpl.getDOMImplementation(); final Document document = impl.createDocument(null, SolrResponseHandler.SOLR, null); Element add = null; if (_mode == ExecutionMode.ADD) { add = document.createElement(ADD); } else { add = document.createElement(DELETE); } if (_allowDoublets) { add.setAttribute(OVERWRITE, "false"); } else { add.setAttribute(OVERWRITE, "true"); } add.setAttribute(COMMIT_WITHIN, String.valueOf(_commitWithin)); for (final String id : recordIds) { logId = id; final Element doc = document.createElement(SolrResponseHandler.DOC); add.appendChild(doc); // Create id attribute Element field = document.createElement(FIELD); field.setAttribute(SolrResponseHandler.NAME, SolrResponseHandler.ID); final String idEncoded = URLEncoder.encode(id, UTF8); Text text = document.createTextNode(idEncoded); field.appendChild(text); doc.appendChild(field); // Create all other attributes final AnyMap record = blackboard.getMetadata(id); for (final String attrName : record.keySet()) { if (!attrName.startsWith(META_DATA) && !attrName.startsWith(RESPONSE_HEADER)) { final Any attributeValue = record.get(attrName); for (final Any any : attributeValue) { if (any.isValue()) { final Value value = (Value) any; String stringValue = null; if (value.isDate()) { final SimpleDateFormat df = new SimpleDateFormat( SolrResponseHandler.DATE_FORMAT_PATTERN); stringValue = df.format(value.asDate()); } else if (value.isDateTime()) { final SimpleDateFormat df = new SimpleDateFormat( SolrResponseHandler.DATE_FORMAT_PATTERN); stringValue = df.format(value.asDateTime()); } else { stringValue = replaceNonXMLChars(value.asString()); } field = document.createElement(FIELD); field.setAttribute(SolrResponseHandler.NAME, attrName); text = document.createTextNode(stringValue); field.appendChild(text); doc.appendChild(field); } } } } } final Transformer transformer = TRANSFORMER_FACTORY.newTransformer(); if (_log.isDebugEnabled()) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); } final DOMSource source = new DOMSource(add); final Writer w = new StringWriter(); final StreamResult streamResult = new StreamResult(w); transformer.transform(source, streamResult); updateXMLMessage = streamResult.getWriter().toString(); conn.setRequestProperty(CONTENT_LENGTH, Integer.toString(updateXMLMessage.length())); final DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.write(updateXMLMessage.getBytes(UTF8)); os.flush(); os.close(); final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; final StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); // System.out.println("Response:\n" + response.toString()); } catch (final Exception e) { final String msg = "Error while processing record '" + logId + "' for index '" + _indexName + "': " + e.getMessage() + "'."; _log.error(msg, e); if (_log.isDebugEnabled()) { try { final FileOutputStream fos = new FileOutputStream(DigestHelper.calculateDigest(logId) + ".xml"); fos.write(updateXMLMessage.getBytes(UTF8)); fos.flush(); fos.close(); } catch (final Exception ee) { throw new ProcessingException(msg, ee); } } throw new ProcessingException(msg, e); } finally { if (conn != null) { conn.disconnect(); } } return recordIds; }