List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:com.marklogic.shell.Shell.java
private void run(String[] args) { CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/* www .j a v a 2s . co m*/ try { cmd = parser.parse(options, args); } catch (ParseException e) { exitWithError(e.getMessage()); } if (cmd.hasOption("h")) { printHelp(); } String user = cmd.getOptionValue("u"); String password = cmd.getOptionValue("p"); String host = cmd.getOptionValue("H"); String database = cmd.getOptionValue("d"); Integer port = null; try { port = new Integer(cmd.getOptionValue("P")); } catch (NumberFormatException ignored) { } if (user == null) user = properties.getString("user"); if (password == null) password = properties.getString("password"); if (host == null) host = properties.getString("host"); if (port == null) { try { port = new Integer(properties.getInt("port", DEFAULT_PORT)); } catch (ConversionException e) { printHelp("Invalid port number: " + properties.getString("port")); } } if (user == null || password == null || port == null || host == null) { printHelp("You must provide a user, password, host and port."); } properties.setProperty("user", user); properties.setProperty("password", password); properties.setProperty("host", host); properties.setProperty("database", database); properties.setProperty("port", port.toString()); if (properties.getString("scroll") == null || properties.getString("scroll").length() <= 0) { properties.setProperty("scroll", String.valueOf(DEFAULT_SCROLL)); } if (cmd.hasOption("F")) { properties.setProperty("pretty-print-xml", "true"); } String xqueryFile = cmd.getOptionValue("f"); InputStream in = null; if (xqueryFile != null) { try { in = new FileInputStream(new File(xqueryFile)); } catch (FileNotFoundException e) { exitWithError("File " + xqueryFile + " not found: " + e.getMessage()); } } else { in = System.in; } int stdinBytes = 0; try { stdinBytes = in.available(); } catch (IOException ignored) { } if (cmd.hasOption("l")) { // XXX this is a hack to support loading from command line without // duplication of code // XXX make sure load command doesn't have conflicting args load loader = new load(this.options); loader.execute(this, args); } else if (stdinBytes > 0) { StringBuffer xquery = new StringBuffer(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); char[] b = new char[4 * 1024]; int n; while ((n = reader.read(b)) > 0) { xquery.append(b, 0, n); } } catch (IOException e) { exitWithError("Failed to read query from stdin: " + e.getMessage()); } Session session = getContentSource().newSession(); AdhocQuery request = session.newAdhocQuery(xquery.toString()); try { outputResultSequence(session.submitRequest(request), false); } catch (RequestException e) { outputException(e); } } else { try { checkConnection(properties.getString("user"), properties.getString("password"), properties.getString("host"), properties.getInt("port", DEFAULT_PORT)); } catch (ShellException e) { outputLine("Failed to connect to Mark Logic. Invalid connection information."); outputException(e); exitWithError("Goodbye."); } printWelcome(); outputLine(""); try { startShell(); } catch (Exception e) { e.printStackTrace(); outputLine("Shell exited abnormally with exception: " + e.getClass().toString()); outputLine("Error message: " + e.getMessage()); outputLine("Goodbye."); } } }
From source file:com.echopf.ECHOQuery.java
/** * Sends a HTTP request with optional request contents/parameters. * @param path a request url path// w w w.j a v a 2 s .c o m * @param httpMethod a request method (GET/POST/PUT/DELETE) * @param data request contents/parameters * @param multipart use multipart/form-data to encode the contents * @throws ECHOException */ public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart) throws ECHOException { final String secureDomain = ECHO.secureDomain; if (secureDomain == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); String baseUrl = new StringBuilder("https://").append(secureDomain).toString(); String url = new StringBuilder(baseUrl).append("/").append(path).toString(); HttpsURLConnection httpClient = null; try { URL urlObj = new URL(url); StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/"); // Append the QueryString contained in path boolean isContainQuery = urlObj.getQuery() != null; if (isContainQuery) apiUrl.append("?").append(urlObj.getQuery()); // Append the QueryString from data if (httpMethod.equals("GET") && data != null) { boolean firstItem = true; Iterator<?> iter = data.keys(); while (iter.hasNext()) { if (firstItem && !isContainQuery) { firstItem = false; apiUrl.append("?"); } else { apiUrl.append("&"); } String key = (String) iter.next(); String value = data.optString(key); apiUrl.append(key); apiUrl.append("="); apiUrl.append(value); } } URL urlConn = new URL(apiUrl.toString()); httpClient = (HttpsURLConnection) urlConn.openConnection(); } catch (IOException e) { throw new ECHOException(e); } final String appId = ECHO.appId; final String appKey = ECHO.appKey; final String accessToken = ECHO.accessToken; if (appId == null || appKey == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); InputStream responseInputStream = null; try { httpClient.setRequestMethod(httpMethod); httpClient.addRequestProperty("X-ECHO-APP-ID", appId); httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey); // Set access token if (accessToken != null && !accessToken.isEmpty()) httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken); // Build content if (!httpMethod.equals("GET") && data != null) { httpClient.setDoOutput(true); httpClient.setChunkedStreamingMode(0); // use default chunk size if (multipart == false) { // application/json httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); BufferedWriter wrBuffer = new BufferedWriter( new OutputStreamWriter(httpClient.getOutputStream())); wrBuffer.write(data.toString()); wrBuffer.close(); } else { // multipart/form-data final String boundary = "*****" + UUID.randomUUID().toString() + "*****"; final String twoHyphens = "--"; final String lineEnd = "\r\n"; final int maxBufferSize = 1024 * 1024 * 3; httpClient.setRequestMethod("POST"); httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary); final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream()); try { JSONObject postData = new JSONObject(); postData.putOpt("method", httpMethod); postData.putOpt("data", data); new Object() { public void post(JSONObject data, List<String> currentKeys) throws JSONException, IOException { Iterator<?> keys = data.keys(); while (keys.hasNext()) { String key = (String) keys.next(); List<String> newKeys = new ArrayList<String>(currentKeys); newKeys.add(key); Object val = data.get(key); // convert JSONArray into JSONObject if (val instanceof JSONArray) { JSONArray array = (JSONArray) val; JSONObject val2 = new JSONObject(); for (Integer i = 0; i < array.length(); i++) { val2.putOpt(i.toString(), array.get(i)); } val = val2; } // build form-data name String name = ""; for (int i = 0; i < newKeys.size(); i++) { String key2 = newKeys.get(i); name += (i == 0) ? key2 : "[" + key2 + "]"; } if (val instanceof ECHOFile) { ECHOFile file = (ECHOFile) val; if (file.getLocalBytes() == null) continue; InputStream fileInputStream = new ByteArrayInputStream( file.getLocalBytes()); if (fileInputStream != null) { String mimeType = URLConnection .guessContentTypeFromName(file.getFileName()); // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + mimeType + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); // write content int bytesAvailable, bufferSize, bytesRead; do { bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (bytesRead <= 0) break; outputStream.write(buffer, 0, bufferSize); } while (true); fileInputStream.close(); outputStream.writeBytes(lineEnd); } } else if (val instanceof JSONObject) { this.post((JSONObject) val, newKeys); } else { String data2 = null; try { // in case of boolean boolean bool = data.getBoolean(key); data2 = bool ? "true" : ""; } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false". data2 = val.toString().trim(); } // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes( "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd); outputStream .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd); outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd); outputStream.writeBytes(lineEnd); // write content byte[] bytes = data2.getBytes(); for (int i = 0; i < bytes.length; i++) { outputStream.writeByte(bytes[i]); } outputStream.writeBytes(lineEnd); } } } }.post(postData, new ArrayList<String>()); } catch (JSONException e) { throw new ECHOException(e); } finally { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.flush(); outputStream.close(); } } } else { httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); } if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) { responseInputStream = httpClient.getInputStream(); } } catch (IOException e) { // get http response code int errorCode = -1; try { errorCode = httpClient.getResponseCode(); } catch (IOException e1) { throw new ECHOException(e1); } // get error contents JSONObject responseObj; try { String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream()); responseObj = new JSONObject(jsonStr); } catch (JSONException e1) { if (errorCode == 404) { throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found."); } throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format."); } // if (responseObj != null) { int code = responseObj.optInt("error_code"); String message = responseObj.optString("error_message"); if (code != 0 || !message.equals("")) { JSONObject details = responseObj.optJSONObject("error_details"); if (details == null) { throw new ECHOException(code, message); } else { throw new ECHOException(code, message, details); } } } throw new ECHOException(e); } return responseInputStream; }
From source file:com.gcrm.action.crm.EditDocumentAction.java
/** * Saves entity field/*from ww w .j a v a 2s.co m*/ * * @return original document record * @throws ParseException */ private Document saveEntity() throws Exception { Document originalDocument = null; if (document.getId() == null) { UserUtil.permissionCheck("create_document"); } else { UserUtil.permissionCheck("update_document"); originalDocument = baseService.getEntityById(Document.class, document.getId()); document.setAttachment(originalDocument.getAttachment()); document.setContacts(originalDocument.getContacts()); document.setCases(originalDocument.getCases()); document.setAccounts(originalDocument.getAccounts()); document.setOpportunities(originalDocument.getOpportunities()); document.setCreated_on(originalDocument.getCreated_on()); document.setCreated_by(originalDocument.getCreated_by()); } DocumentStatus status = null; if (statusID != null) { status = documentStatusService.getEntityById(DocumentStatus.class, statusID); } document.setStatus(status); DocumentCategory category = null; if (categoryID != null) { category = documentCategoryService.getEntityById(DocumentCategory.class, categoryID); } document.setCategory(category); DocumentSubCategory subCategory = null; if (subCategoryID != null) { subCategory = documentSubCategoryService.getEntityById(DocumentSubCategory.class, subCategoryID); } document.setSub_category(subCategory); User assignedTo = null; if (this.getAssignedToID() != null) { assignedTo = userService.getEntityById(User.class, this.getAssignedToID()); } document.setAssigned_to(assignedTo); User owner = null; if (this.getOwnerID() != null) { owner = userService.getEntityById(User.class, this.getOwnerID()); } document.setOwner(owner); Document relatedDocument = null; if (relatedDocumentID != null) { relatedDocument = baseService.getEntityById(Document.class, relatedDocumentID); } document.setRelated_document(relatedDocument); SimpleDateFormat dateFormat = new SimpleDateFormat(Constant.DATE_EDIT_FORMAT); Date publishDate = null; if (!CommonUtil.isNullOrEmpty(publishDateS)) { publishDate = dateFormat.parse(publishDateS); } document.setPublish_date(publishDate); Date expirationDate = null; if (!CommonUtil.isNullOrEmpty(expirationDateS)) { expirationDate = dateFormat.parse(expirationDateS); } document.setExpiration_date(expirationDate); File file = this.getUpload(); if (file != null) { InputStream stream = null; byte[] input = null; try { stream = new BufferedInputStream(new FileInputStream(file)); input = new byte[stream.available()]; stream.read(input); } finally { stream.close(); } Attachment attachment = null; attachment = document.getAttachment(); if (attachment == null) { attachment = new Attachment(); document.setAttachment(attachment); } attachment.setName(this.uploadFileName); document.setFileName(this.uploadFileName); attachment.setContent(input); } if ("Account".equals(this.getRelationKey())) { Account account = accountService.getEntityById(Account.class, Integer.valueOf(this.getRelationValue())); Set<Account> accounts = document.getAccounts(); if (accounts == null) { accounts = new HashSet<Account>(); } accounts.add(account); } else if ("Contact".equals(this.getRelationKey())) { Contact contact = contactService.getEntityById(Contact.class, Integer.valueOf(this.getRelationValue())); Set<Contact> contacts = document.getContacts(); if (contacts == null) { contacts = new HashSet<Contact>(); } contacts.add(contact); } else if ("Opportunity".equals(this.getRelationKey())) { Opportunity opportunity = opportunityService.getEntityById(Opportunity.class, Integer.valueOf(this.getRelationValue())); Set<Opportunity> opportunities = document.getOpportunities(); if (opportunities == null) { opportunities = new HashSet<Opportunity>(); } opportunities.add(opportunity); } else if ("CaseInstance".equals(this.getRelationKey())) { CaseInstance caseInstance = caseService.getEntityById(CaseInstance.class, Integer.valueOf(this.getRelationValue())); Set<CaseInstance> cases = document.getCases(); if (cases == null) { cases = new HashSet<CaseInstance>(); } cases.add(caseInstance); } super.updateBaseInfo(document); return originalDocument; }
From source file:com.amazon.alexa.avs.AVSAudioPlayer.java
/** * Play items from the speech play queue *//* ww w . j a v a 2 s . c o m*/ private void startSpeech() { final SpeakItem speak = speakQueue.peek(); // This addresses the possibility of the queue being cleared // between the time of this function call and this line of code. if (speak == null) { return; } notifyAlexaSpeechStarted(); speechState = SpeechState.PLAYING; latestToken = speak.getToken(); controller.sendRequest(RequestFactory.createSpeechSynthesizerSpeechStartedEvent(latestToken)); Thread thread = new Thread() { @Override public void run() { synchronized (playLock) { try { InputStream inpStream = speak.getAudio(); interruptAlertsAndContent(); play(inpStream); while (inpStream.available() > 0) { playLock.wait(TIMEOUT_IN_MS); } } catch (InterruptedException | IOException e) { } finishedSpeechItem(); } } }; thread.start(); }
From source file:org.wso2.carbon.ml.rest.api.ModelApiV11.java
/** * Predict using a file and return as a list of predicted values. * * @param modelId Unique id of the model * @param dataFormat Data format of the file (CSV or TSV) * @param inputStream File input stream generated from the file used for predictions * @param percentile a threshold value used to identified cluster boundaries * @param skipDecoding whether the decoding should not be done (true or false) * @return JSON array of predictions//from w w w . j a v a2s .co m */ @POST @Path("/predict") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.MULTIPART_FORM_DATA) public Response predict(@Multipart("modelId") long modelId, @Multipart("dataFormat") String dataFormat, @Multipart("file") InputStream inputStream, @QueryParam("percentile") double percentile, @QueryParam("skipDecoding") boolean skipDecoding) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); int tenantId = carbonContext.getTenantId(); String userName = carbonContext.getUsername(); try { // validate input parameters // if it is a file upload, check whether the file is sent if (inputStream == null || inputStream.available() == 0) { String msg = String.format( "Error occurred while reading the file for model [id] %s of tenant [id] %s and [user] %s .", modelId, tenantId, userName); logger.error(msg); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new MLErrorBean(msg)).build(); } List<?> predictions = mlModelHandler.predict(tenantId, userName, modelId, dataFormat, inputStream, percentile, skipDecoding); return Response.ok(predictions).build(); } catch (IOException e) { String msg = MLUtils.getErrorMsg(String.format( "Error occurred while reading the file for model [id] %s of tenant [id] %s and [user] %s.", modelId, tenantId, userName), e); logger.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(new MLErrorBean(e.getMessage())).build(); } catch (MLModelHandlerException e) { String msg = MLUtils.getErrorMsg(String.format( "Error occurred while predicting from model [id] %s of tenant [id] %s and [user] %s.", modelId, tenantId, userName), e); logger.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new MLErrorBean(e.getMessage())) .build(); } }
From source file:ru.emdev.ldap.util.EmDevSchemaLdifExtractor.java
/** * Extracts the LDIF schema resource from a Jar. * * @param resource the LDIF schema resource * @throws IOException if there are IO errors *///from w w w . j av a 2 s. c o m private void extractFromJar(String resource) throws IOException { byte[] buf = new byte[512]; InputStream in = DefaultSchemaLdifExtractor.getUniqueResourceAsStream(resource, "LDIF file in schema repository"); try { File destination = new File(outputDirectory, resource); /* * Do not overwrite an LDIF file if it has already been extracted. */ if (destination.exists()) { return; } if (!destination.getParentFile().exists() && !destination.getParentFile().mkdirs()) { throw new IOException( I18n.err("Directory Creation Failed: " + destination.getParentFile().getAbsolutePath())); } FileOutputStream out = new FileOutputStream(destination); try { while (in.available() > 0) { int readCount = in.read(buf); out.write(buf, 0, readCount); } out.flush(); } finally { out.close(); } } finally { in.close(); } }
From source file:org.wso2.carbon.ml.rest.api.ModelApiV11.java
/** * Predict using a file and return predictions as a CSV. * * @param modelId Unique id of the model * @param dataFormat Data format of the file (CSV or TSV) * @param columnHeader Whether the file contains the column header as the first row (YES or NO) * @param inputStream Input stream generated from the file used for predictions * @param percentile a threshold value used to identified cluster boundaries * @param skipDecoding whether the decoding should not be done (true or false) * @return A file as a {@link StreamingOutput} *//* w w w. j a v a 2 s. c om*/ @POST @Path("/predictionStreams") @Produces(MediaType.APPLICATION_OCTET_STREAM) @Consumes(MediaType.MULTIPART_FORM_DATA) public Response streamingPredict(@Multipart("modelId") long modelId, @Multipart("dataFormat") String dataFormat, @Multipart("columnHeader") String columnHeader, @Multipart("file") InputStream inputStream, @QueryParam("percentile") double percentile, @QueryParam("skipDecoding") boolean skipDecoding) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); int tenantId = carbonContext.getTenantId(); String userName = carbonContext.getUsername(); try { // validate input parameters // if it is a file upload, check whether the file is sent if (inputStream == null || inputStream.available() == 0) { String msg = String.format( "No file found to predict with model [id] %s of tenant [id] %s and [user] %s .", modelId, tenantId, userName); logger.error(msg); return Response.status(Response.Status.BAD_REQUEST).entity(new MLErrorBean(msg)) .type(MediaType.APPLICATION_JSON).build(); } final String predictions = mlModelHandler.streamingPredict(tenantId, userName, modelId, dataFormat, columnHeader, inputStream, percentile, skipDecoding); StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream outputStream) throws IOException { Writer writer = new BufferedWriter( new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)); writer.write(predictions); writer.flush(); writer.close(); } }; return Response.ok(stream).header("Content-disposition", "attachment; filename=Predictions_" + modelId + "_" + MLUtils.getDate() + MLConstants.CSV) .build(); } catch (IOException e) { String msg = MLUtils.getErrorMsg(String.format( "Error occurred while reading the file for model [id] %s of tenant [id] %s and [user] %s.", modelId, tenantId, userName), e); logger.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(new MLErrorBean(e.getMessage())) .type(MediaType.APPLICATION_JSON).build(); } catch (MLModelHandlerException e) { String msg = MLUtils.getErrorMsg(String.format( "Error occurred while predicting from model [id] %s of tenant [id] %s and [user] %s.", modelId, tenantId, userName), e); logger.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new MLErrorBean(e.getMessage())) .type(MediaType.APPLICATION_JSON).build(); } }
From source file:com.adobe.phonegap.contentsync.Sync.java
private void copyRootAppByManifest(String outputDirectory, String manifestFile, boolean wwwExists) throws IOException, JSONException { File fp = new File(outputDirectory); if (!fp.exists()) { fp.mkdirs();/*from www . j a v a2 s . c o m*/ } InputStream is = cordova.getActivity().getAssets().open("www/" + manifestFile); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); JSONObject obj = new JSONObject(new String(buffer, "UTF-8")); JSONArray files = obj.getJSONArray("files"); for (int i = 0; i < files.length(); i++) { Log.d(LOG_TAG, "file = " + files.getString(i)); copyAssetFile(outputDirectory, "www/" + files.getString(i), wwwExists); } }
From source file:com.eryansky.modules.disk.utils.DiskUtils.java
/** * /*from w ww. j av a 2 s . co m*/ * @param request * @param response * @param inputStream ? * @param displayName ?? * @throws IOException */ public static void download(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String displayName) throws IOException { response.reset(); WebUtils.setNoCacheHeader(response); String contentType = "application/x-download"; if (StringUtils.isNotBlank(displayName)) { if (displayName.endsWith(".doc")) { contentType = "application/msword"; } else if (displayName.endsWith(".docx")) { contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } else if (displayName.endsWith(".xls")) { contentType = "application/vnd.ms-excel"; } else if (displayName.endsWith(".xlsx")) { contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } else if (displayName.endsWith(".ppt")) { contentType = "application/vnd.ms-powerpoint"; } else if (displayName.endsWith(".pptx")) { contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; } else if (displayName.endsWith(".pdf")) { contentType = "application/pdf"; } else if (displayName.endsWith(".jpg") || displayName.endsWith(".jpeg")) { contentType = "image/jpeg"; } else if (displayName.endsWith(".gif")) { contentType = "image/gif"; } else if (displayName.endsWith(".bmp")) { contentType = "image/bmp"; } } response.setContentType(contentType); response.setContentLength((int) inputStream.available()); // String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1); // displayFilename = displayFilename.replace(" ", "_"); WebUtils.setDownloadableHeader(request, response, displayName); BufferedInputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new BufferedInputStream(inputStream); IOUtils.copy(is, os); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(is); } }