List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:com.wooki.test.unit.ConversionsTest.java
@Test(enabled = true) public void docbookConversion() { String result = "<book> <bookinfo> <title>An Example Book</title> <author> <firstname>Your first name</firstname> <surname>Your surname</surname> <affiliation> <address><email>foo@example.com</email></address> </affiliation> </author> <copyright> <year>2000</year> <holder>Copyright string here</holder> </copyright> <abstract> <para>If your book has an abstract then it should go here.</para> </abstract> </bookinfo> <preface> <title>Preface</title> <para>Your book may have a preface, in which case it should be placed here.</para> </preface> <chapter> <title>My First Chapter</title> <para>This is the first chapter in my book.</para> <sect1> <title>My First Section</title> <para>This is the first section in my book.</para> </sect1> </chapter> </book>"; Resource resource = new ByteArrayResource(result.getBytes()); InputStream xhtml = fromDocbookConvertor.performTransformation(resource); File htmlFile = null;//from www .j ava 2 s . c o m try { htmlFile = File.createTempFile("wooki", ".html"); FileOutputStream fos = new FileOutputStream(htmlFile); logger.debug("HTML File is " + htmlFile.getAbsolutePath()); byte[] content = null; int available = 0; while ((available = xhtml.available()) > 0) { content = new byte[available]; xhtml.read(content); fos.write(content); } fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return; } logger.debug("Docbook to xhtml ok"); SAXParserFactory factory = SAXParserFactory.newInstance(); // cration d'un parseur SAX SAXParser parser; try { parser = factory.newSAXParser(); parser.parse(new InputSource(new FileInputStream(htmlFile)), htmlParser); } catch (ParserConfigurationException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } catch (SAXException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } Book book = htmlParser.getBook(); logger.debug("The book title is " + book.getTitle()); }
From source file:com.wooki.test.unit.ConversionsTest.java
@Test(enabled = true) public void testAptConversion() { String result = " ------\n Title\n ------\n Author\n ------\n Date\n\n Paragraph 1, line 1.\n Paragraph 1, line 2.\n\n Paragraph 2, line 1.\n Paragraph 2, line 2.\n\nSection title\n\n* Sub-section title\n\n** Sub-sub-section title\n\n*** Sub-sub-sub-section title\n\n**** Sub-sub-sub-sub-section title\n\n * List item 1.\n\n * List item 2.\n\n Paragraph contained in list item 2.\n\n * Sub-list item 1.\n\n * Sub-list item 2.\n\n * List item 3.\n Force end of list:\n\n []\n\n+------------------------------------------+\nVerbatim text not contained in list item 3\n+------------------------------------------+\n\n [[1]] Numbered item 1.\n\n [[A]] Numbered item A.\n\n [[B]] Numbered item B.\n\n [[2]] Numbered item 2.\n\n List numbering schemes: [[1]], [[a]], [[A]], [[i]], [[I]].\n\n [Defined term 1] of definition list.\n\n [Defined term 2] of definition list.\n\n+-------------------------------+\nVerbatim text\n in a box\n+-------------------------------+\n\n --- instead of +-- suppresses the box around verbatim text.\n\n[Figure name] Figure caption\n\n*----------*--------------+----------------:\n| Centered | Left-aligned | Right-aligned |\n| cell 1,1 | cell 1,2 | cell 1,3 |\n*----------*--------------+----------------:\n| cell 2,1 | cell 2,2 | cell 2,3 |\n*----------*--------------+----------------:\nTable caption\n\n No grid, no caption:\n\n*-----*------*\n cell | cell\n*-----*------*\n cell | cell\n*-----*------*\n\n Horizontal line:\n\n=======================================================================\n\n^L\n New page.\n\n <Italic> font. <<Bold>> font. <<<Monospaced>>> font.\n\n {Anchor}. Link to {{anchor}}. Link to {{http://www.pixware.fr}}.\n Link to {{{anchor}showing alternate text}}.\n Link to {{{http://www.pixware.fr}Pixware home page}}.\n\n Force line\\\n break.\n\n Non\\ breaking\\ space.\n\n Escaped special characters: \\~, \\=, \\-, \\+, \\*, \\[, \\], \\<, \\>, \\{, \\}, \\\\.\n\n Copyright symbol: \\251, \\xA9, \\u00a9.\n\n~~Commented out."; File aptFile = null;/*www . j a v a2 s. c o m*/ String from = "apt"; File out = null; try { out = File.createTempFile("fromAptToXHTML", ".html"); InputStream apt = new ByteArrayInputStream(result.getBytes()); try { aptFile = File.createTempFile("wooki", ".apt"); FileOutputStream fos = new FileOutputStream(aptFile); logger.debug("APT File is " + aptFile.getAbsolutePath()); byte[] content = null; int available = 0; while ((available = apt.available()) > 0) { content = new byte[available]; apt.read(content); fos.write(content); } fos.flush(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String to = "xhtml"; Converter converter = new DefaultConverter(); InputFileWrapper input = InputFileWrapper.valueOf(aptFile.getAbsolutePath(), from, "ISO-8859-1", converter.getInputFormats()); OutputFileWrapper output = OutputFileWrapper.valueOf(out.getAbsolutePath(), to, "UTF-8", converter.getOutputFormats()); converter.convert(input, output); } catch (UnsupportedFormatException e) { e.printStackTrace(); } catch (ConverterException e) { e.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream newHTML = fromAptToDocbook.performTransformation(new FileSystemResource(out)); SAXParserFactory factory = SAXParserFactory.newInstance(); // cration d'un parseur SAX SAXParser parser; try { parser = factory.newSAXParser(); parser.parse(new InputSource(newHTML), htmlParser); } catch (ParserConfigurationException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } catch (SAXException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } Book book = htmlParser.getBook(); logger.debug("The book title is " + book.getTitle()); }
From source file:com.wooki.test.unit.ConversionsTest.java
@Test(enabled = true) public void testAPTConversion() { String result = /* * generator .adaptContent( */"<h2>SubTitle</h2><p>Lorem ipsum</p><h3>SubTitle2</h3><p>Lorem ipsum</p>"/* ) */; Resource resource = new ByteArrayResource(result.getBytes()); InputStream xhtml = toXHTMLConvertor.performTransformation(resource); logger.debug("Document to xhtml ok"); InputStream apt = toAPTConvertor.performTransformation(new InputStreamResource(xhtml)); logger.debug("xhtml to apt ok"); File aptFile;//from ww w.j a v a 2s. co m try { aptFile = File.createTempFile("wooki", ".apt"); FileOutputStream fos = new FileOutputStream(aptFile); logger.debug("APT File is " + aptFile.getAbsolutePath()); byte[] content = null; int available = 0; while ((available = apt.available()) > 0) { content = new byte[available]; apt.read(content); fos.write(content); } fos.flush(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.apache.cxf.transport.http.asyncclient.SharedOutputBuffer.java
public int copy(InputStream in) throws IOException { this.lock.lock(); int total = 0; try {/*from w w w .j a v a2s. c o m*/ if (this.shutdown || this.endOfStream) { throw new IllegalStateException("Buffer already closed for writing"); } setInputMode(); int i = 0; boolean yielded = false; while (i != -1) { if (!this.buffer.hasRemaining()) { flushContent(); setInputMode(); } i = in.available(); if (i == 0 && !yielded) { //nothing avail right now, we'll attempt an //output, but not really force a flush. if (buffer.position() != 0 && this.ioctrl != null) { this.ioctrl.requestOutput(); } try { condition.awaitNanos(1); } catch (InterruptedException e) { //ignore } setInputMode(); yielded = true; } else { int p = this.buffer.position(); i = in.read(this.buffer.array(), this.buffer.position(), this.buffer.remaining()); yielded = false; if (i != -1) { total += i; buffer.position(p + i); } /* System.out.println("p: " + p + " " + i + " " + this.buffer.position() + " " + this.buffer.hasRemaining()); */ } } } finally { this.lock.unlock(); } return total; }
From source file:com.wooki.test.unit.ConversionsTest.java
@Test(enabled = true) public void testLatexConversion() { String result = /* * generator .adaptContent( */"<h2>SubTitle</h2><p>Lorem ipsum</p><h3>SubTitle2</h3><p>Lorem ipsum</p>"/* ) */; Resource resource = new ByteArrayResource(result.getBytes()); /** Generate Latex */ InputStream xhtml = toXHTMLConvertor.performTransformation(resource); InputStream improvedXhtml = toImprovedXHTML4LatexConvertor .performTransformation(new InputStreamResource(xhtml)); InputStream latex = toLatexConvertor.performTransformation(new InputStreamResource(improvedXhtml)); logger.debug("xhtml to apt ok"); File latexFile;//from w w w .j a v a2 s. co m try { latexFile = File.createTempFile("wooki", ".latex"); FileOutputStream fos = new FileOutputStream(latexFile); logger.debug("latex File is " + latexFile.getAbsolutePath()); byte[] content = null; int available = 0; while ((available = latex.available()) > 0) { content = new byte[available]; latex.read(content); fos.write(content); } fos.flush(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.wso2.carbon.ml.rest.api.ModelApiV10.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 * @return JSON array of predictions//from w w w . ja v a 2s .c o 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) { 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); 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:org.wso2.carbon.ml.rest.api.ModelApiV10.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 * @return A file as a {@link javax.ws.rs.core.StreamingOutput} *//*from w ww . j av a2 s . com*/ @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) { 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.BAD_REQUEST).entity(new MLErrorBean(msg)).build(); } final String predictions = mlModelHandler.streamingPredict(tenantId, userName, modelId, dataFormat, columnHeader, inputStream); 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())).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:com.farmerbb.notepad.activity.MainActivity.java
private boolean importNote(Uri uri) { try {/*from w ww . jav a 2s . com*/ File importedFile = new File(getFilesDir(), Long.toString(System.currentTimeMillis())); long suffix = 0; // Handle cases where a note may have a duplicate title while (importedFile.exists()) { suffix++; importedFile = new File(getFilesDir(), Long.toString(System.currentTimeMillis() + suffix)); } InputStream is = getContentResolver().openInputStream(uri); byte[] data = new byte[is.available()]; if (data.length > 0) { OutputStream os = new FileOutputStream(importedFile); is.read(data); os.write(data); is.close(); os.close(); } return true; } catch (IOException e) { return false; } }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
private double doUpload(String phpFile, InputStream uploadFileIs, String fileName) { URLConnection conn = null;/*from w w w . j a va2s . co m*/ OutputStream os = null; InputStream is = null; double bw = 0.0; try { String response = ""; Date oldTime = new Date(); URL url = new URL(amazonDomain + "/" + phpFile); String boundary = "---------------------------4664151417711"; conn = url.openConnection(); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); byte[] fileData = new byte[uploadFileIs.available()]; uploadFileIs.read(fileData); uploadFileIs.close(); String message1 = "--" + boundary + CrLf; message1 += "Content-Disposition: form-data;"; message1 += "name=\"uploadedfile\"; filename=\"" + fileName + "\"" + CrLf; message1 += "Content-Type: text/plain; charset=UTF-8" + CrLf + CrLf; // the file is sent between the messages in the multipart message. String message2 = CrLf + "--" + boundary + "--" + CrLf; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); int contentLenght = message1.length() + message2.length() + fileData.length; // might not need to specify the content-length when sending chunked data. conn.setRequestProperty("Content-Length", String.valueOf(contentLenght)); os = conn.getOutputStream(); os.write(message1.getBytes()); // SEND THE IMAGE int index = 0; int size = 1024; do { if ((index + size) > fileData.length) { size = fileData.length - index; } os.write(fileData, index, size); index += size; } while (index < fileData.length); os.write(message2.getBytes()); os.flush(); is = conn.getInputStream(); char buff = 512; int len; byte[] data = new byte[buff]; do { len = is.read(data); if (len > 0) { response += new String(data, 0, len); } } while (len > 0); if (response.equals("200")) { Date newTime = new Date(); double milliseconds = newTime.getTime() - oldTime.getTime(); bw = ((double) contentLenght * 8) / (milliseconds * (double) 1000); } } catch (Exception e) { System.out.println("Exception is fired in upload test. error:" + e.getMessage()); } finally { try { os.close(); } catch (Exception e) { //System.out.println("Exception is fired in os.close. error:" + e.getMessage()); } try { is.close(); } catch (Exception e) { //System.out.println("Exception is fired in is.close. error:" + e.getMessage()); } } return bw; }
From source file:com.esofthead.mycollab.module.file.servlet.UserAvatarHttpServletRequestHandler.java
@Override protected void onHandleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!StorageFactory.getInstance().isFileStorage()) { throw new MyCollabException("This servlet support file system setting only"); }// ww w. j a v a 2 s. c o m String path = request.getPathInfo(); if (path != null) { path = FilenameUtils.getBaseName(path); int lastIndex = path.lastIndexOf("_"); if (lastIndex > 0) { String username = path.substring(0, lastIndex); int size = Integer.valueOf(path.substring(lastIndex + 1, path.length())); FileStorage fileStorage = (FileStorage) StorageFactory.getInstance(); File avatarFile = fileStorage.getAvatarFile(username, size); InputStream avatarInputStream; if (avatarFile != null) { avatarInputStream = new FileInputStream(avatarFile); } else { String userAvatarPath = String.format("assets/icons/default_user_avatar_%d.png", size); avatarInputStream = UserAvatarHttpServletRequestHandler.class.getClassLoader() .getResourceAsStream(userAvatarPath); if (avatarInputStream == null) { LOG.error("Error to get avatar", new MyCollabException("Invalid request for avatar " + path)); return; } } response.setHeader("Content-Type", "image/png"); response.setHeader("Content-Length", String.valueOf(avatarInputStream.available())); try (BufferedInputStream input = new BufferedInputStream(avatarInputStream); BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream())) { byte[] buffer = new byte[8192]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } } else { LOG.error("Invalid path " + path); } } }