List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:it.pronetics.madstore.server.test.servlet.DataServlet.java
public void init(ServletConfig config) throws ServletException { try {//from w ww . j a v a2 s. c o m super.init(config); ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); Map collectionRepositories = ctx.getBeansOfType(CollectionRepository.class); Map entryRepositories = ctx.getBeansOfType(EntryRepository.class); if (collectionRepositories.size() != 1 || entryRepositories.size() != 1) { throw new IllegalStateException(); } else { collectionRepository = (CollectionRepository) collectionRepositories.values().toArray()[0]; entryRepository = (EntryRepository) entryRepositories.values().toArray()[0]; } InputStream collectionStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("entriesCollection.xml"); InputStream entryStream1 = Thread.currentThread().getContextClassLoader() .getResourceAsStream("entry1.xml"); InputStream entryStream2 = Thread.currentThread().getContextClassLoader() .getResourceAsStream("entry2.xml"); InputStream entryStream3 = Thread.currentThread().getContextClassLoader() .getResourceAsStream("entry3.xml"); byte[] bytes = new byte[collectionStream.available()]; collectionStream.read(bytes); Element collection = DomHelper.getDomFromString(new String(bytes)); bytes = new byte[entryStream1.available()]; entryStream1.read(bytes); Element entry1 = DomHelper.getDomFromString(new String(bytes)); bytes = new byte[entryStream2.available()]; entryStream2.read(bytes); Element entry2 = DomHelper.getDomFromString(new String(bytes)); bytes = new byte[entryStream3.available()]; entryStream3.read(bytes); Element entry3 = DomHelper.getDomFromString(new String(bytes)); collectionKey = collectionRepository.putIfAbsent(collection); entryRepository.put(collectionKey, entry1); entryRepository.put(collectionKey, entry2); entryRepository.put(collectionKey, entry3); } catch (Exception ex) { throw new ServletException(ex.getMessage(), ex); } }
From source file:com.stepsdk.android.api.APIClient.java
private MultipartEntity addFile(MultipartEntity mpEntity, String key, String fromPath) throws IOException { String filepath;// w ww . j a v a 2s .c o m try { filepath = URLDecoder.decode(fromPath, "UTF-8"); // handle special character } catch (Exception e) { filepath = fromPath; } String fromFilename = filepath.substring(filepath.lastIndexOf("/") + 1); String filename = ""; long filesize = 0; ContentBody cbFile = null; log(TAG, "from upload path: " + fromPath); // upload from content uri if (fromPath.indexOf("content://") > -1) { Uri uri = Uri.parse(fromPath); String mime = mContext.getContentResolver().getType(uri); String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime); String mediatype = mime.substring(0, mime.indexOf('/')); InputStream is = mContext.getContentResolver().openInputStream(uri); filesize = is.available(); filename = mediatype + fromFilename + "." + extension; cbFile = new InputStreamBody(is, mime, filename); } else { //upload from file uri File file = new File(filepath); filesize = file.length(); filename = fromFilename; cbFile = new FileBody(file, FileUtil.getMimeTypeFromFilePath(fromPath)); } //final String finalfilename = filename; final long finalfilesize = filesize; //final int task_id = params[1].getIntExtra("cancel_task_id", 0); //final Intent cancelintent = params[1]; //final Intent doneintent = params[2]; mpEntity.addPart(key, cbFile); return mpEntity; }
From source file:calliope.db.CouchConnection.java
/** * Fetch a resource from the server, or try to. * @param db the name of the database/*from ww w.j a v a 2 s. c o m*/ * @param docID the docid of the reputed resource * @return the response as a string or null if not found */ @Override public String getFromDb(String db, String docID) throws AeseException { try { //long startTime = System.currentTimeMillis(); String login = (user == null) ? "" : user + ":" + password + "@"; docID = convertDocID(docID); URL u = new URL("http://" + login + host + ":" + dbPort + "/" + db + "/" + docID); URLConnection conn = u.openConnection(); InputStream is = conn.getInputStream(); ByteHolder bh = new ByteHolder(); long timeTaken = 0, start = System.currentTimeMillis(); // HttpURLConnection seems to use non-blocking I/O while (timeTaken < bigTimeout && (is.available() > 0 || timeTaken < smallTimeout)) { if (is.available() > 0) { byte[] data = new byte[is.available()]; is.read(data); bh.append(data); // restart timeout timeTaken = 0; } else timeTaken = System.currentTimeMillis() - start; } is.close(); if (bh.isEmpty()) throw new FileNotFoundException("failed to fetch resource " + db + "/" + docID); //System.out.println("time taken to fetch from couch: " //+(System.currentTimeMillis()-startTime) ); else return new String(bh.getData(), "UTF-8"); } catch (Exception e) { throw new AeseException(e); } }
From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java
protected final void readAvailable(InputStream in, ByteArrayOutputStream sink) { byte[] buf = new byte[1024]; try {//from ww w .j a v a2 s . c o m int len = -1; while (in.available() > 0 && (len = in.read(buf, 0, buf.length)) > 0) { sink.write(buf, 0, len); } } catch (IOException e) { log.warn("IOException reading serial data: {}", e.getMessage()); } if (eventLog.isTraceEnabled()) { eventLog.trace("Finished reading data: {}", asciiDebugValue(sink.toByteArray())); } }
From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java
/** * Read from the InputStream until it is empty. * /* ww w .j a v a 2s. c o m*/ * @param in */ protected void drainInputStream(InputStream in) { byte[] buf = new byte[1024]; int len = -1; int total = 0; try { final int max = Math.min(in.available(), buf.length); eventLog.trace("Attempting to drain {} bytes from serial port", max); while (max > 0 && (len = in.read(buf, 0, max)) > 0) { // keep draining total += len; } } catch (IOException e) { // ignore this } eventLog.trace("Drained {} bytes from serial port", total); }
From source file:org.dataone.proto.trove.mn.service.v1.impl.MNReadImpl.java
@Override public InputStream get(Identifier pid) throws InvalidToken, NotAuthorized, NotImplemented, ServiceFailure, NotFound, InsufficientResources { InputStream inputStream = null; try {// w w w.j a v a 2 s . c o m ObjectList objectList = new ObjectList(); inputStream = (InputStream) dataoneDataObjectDirectory.get(pid); // logger.info("get filepath: " + filePath); // inputStream = new FileInputStream(new File(filePath)); logger.debug("is it available? " + inputStream.available()); } catch (FileNotFoundException ex) { logger.warn(ex); NotFound exception = new NotFound("000", ex.getMessage()); throw exception; } catch (IOException ex) { logger.warn(ex); ServiceFailure exception = new ServiceFailure("001", ex.getMessage()); throw exception; } return inputStream; }
From source file:org.dataone.proto.trove.mn.rest.v1.ObjectController.java
/** * update the object requested//from w w w .ja va 2 s . c om * * @param request * @param response * @param pid * @throws InvalidToken * @throws ServiceFailure * @throws IOException * @throws NotAuthorized * @throws NotFound * @throws NotImplemented */ @RequestMapping(value = "/v1/object/{pid}", method = RequestMethod.PUT) public void update(MultipartHttpServletRequest fileRequest, HttpServletResponse response, @PathVariable String pid) throws InvalidToken, ServiceFailure, IOException, NotAuthorized, NotFound, NotImplemented, InvalidRequest, InsufficientResources, InvalidSystemMetadata, IdentifierNotUnique, UnsupportedType { debugRequest(fileRequest); Identifier id = new Identifier(); try { id.setValue(urlCodec.decode(pid, "UTF-8")); } catch (DecoderException ex) { throw new ServiceFailure("20000", ex.getMessage()); } catch (UnsupportedEncodingException ex) { throw new ServiceFailure("20001", ex.getMessage()); } if (!this.logRequest(fileRequest, Event.UPDATE, id)) { throw new ServiceFailure("20001", "unable to log request"); } Session session = new Session(); InputStream objectInputStream = null; MultipartFile sytemMetaDataMultipart = null; MultipartFile objectMultipart = null; SystemMetadata systemMetadata = null; Set<String> keys = fileRequest.getFileMap().keySet(); for (String key : keys) { if (key.equalsIgnoreCase("sysmeta")) { sytemMetaDataMultipart = fileRequest.getFileMap().get(key); } else { objectMultipart = fileRequest.getFileMap().get(key); } } if (sytemMetaDataMultipart != null) { try { systemMetadata = (SystemMetadata) TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, sytemMetaDataMultipart.getInputStream()); } catch (IOException ex) { throw new InvalidSystemMetadata("15001", ex.getMessage()); } catch (JiBXException ex) { throw new InvalidSystemMetadata("15002", ex.getMessage()); } catch (InstantiationException ex) { throw new InvalidSystemMetadata("15003", ex.getMessage()); } catch (IllegalAccessException ex) { throw new InvalidSystemMetadata("15004", ex.getMessage()); } } else { throw new InvalidSystemMetadata("15005", "System Metadata was not found as Part of Multipart Mime message"); } if (objectMultipart != null && !(objectMultipart.isEmpty())) { try { objectInputStream = objectMultipart.getInputStream(); } catch (IOException ex) { throw new InvalidRequest("15006", ex.getMessage()); } } else { throw new InvalidRequest("15007", "Object to be created is not attached"); } id.setValue(systemMetadata.getIdentifier().getValue()); DateTime dt = new DateTime(); systemMetadata.setDateSysMetadataModified(dt.toDate()); mnStorage.update(id, null, id, null); InputStream in = mnRead.get(id); OutputStream out = response.getOutputStream(); try { byte[] buffer = null; int filesize = in.available(); if (filesize < 250000) { buffer = new byte[SMALL_BUFF_SIZE]; } else if (filesize >= 250000 && filesize <= 500000) { buffer = new byte[MED_BUFF_SIZE]; } else { buffer = new byte[LARGE_BUFF_SIZE]; } while (true) { int amountRead = in.read(buffer); if (amountRead == -1) { break; } out.write(buffer, 0, amountRead); out.flush(); } } finally { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } } }
From source file:J2MESecondExample.java
private void downloadPage(String url) throws IOException { StringBuffer b = new StringBuffer(); InputStream is = null; HttpConnection c = null;//w w w. j a va 2 s .c om TextBox t = null; try { long len = 0; int ch = 0; c = (HttpConnection) Connector.open(url); is = c.openInputStream(); len = c.getLength(); if (len != -1) { // Read exactly Content-Length bytes for (int i = 0; i < len; i++) if ((ch = is.read()) != -1) b.append((char) ch); } else { // Read till the connection is closed. while ((ch = is.read()) != -1) { len = is.available(); b.append((char) ch); } } t = new TextBox("hello again....", b.toString(), 1024, 0); } finally { is.close(); c.close(); } display.setCurrent(t); }
From source file:com.ikon.servlet.admin.RepositoryViewServlet.java
/** * Get properties from node//w ww.j av a 2 s. co m */ private Collection<HashMap<String, String>> getProperties(Node node) throws ValueFormatException, RepositoryException { ArrayList<HashMap<String, String>> al = new ArrayList<HashMap<String, String>>(); for (PropertyIterator pi = node.getProperties(); pi.hasNext();) { HashMap<String, String> hm = new HashMap<String, String>(); Property p = pi.nextProperty(); PropertyDefinition pd = p.getDefinition(); hm.put("pName", p.getName()); hm.put("pProtected", Boolean.toString(pd.isProtected())); hm.put("pMultiple", Boolean.toString(pd.isMultiple())); hm.put("pType", NODE_TYPE[pd.getRequiredType()]); if (pd.getRequiredType() == PropertyType.BINARY) { InputStream is = p.getStream(); try { hm.put("pValue", "DATA: " + FormatUtil.formatSize(is.available())); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(is); } } else { if (pd.isMultiple()) { hm.put("pValue", toString(p.getValues(), "<br/>")); } else { if (p.getName().equals(Scripting.SCRIPT_CODE)) { hm.put("pValue", p.getString()); } else { hm.put("pValue", p.getString()); } } } al.add(hm); } // Add universal node id HashMap<String, String> hm = new HashMap<String, String>(); hm.put("pName", "jcr:aid"); hm.put("pProtected", Boolean.toString(true)); hm.put("pMultiple", Boolean.toString(false)); hm.put("pType", "VIRTUAL"); hm.put("pValue", ((NodeImpl) node).getId().toString()); al.add(hm); Collections.sort(al, new PropertyCmp()); return al; }
From source file:org.rapidandroid.activity.FormReviewer.java
private void doCsvDirectBednetsInjection() { String rawMessageText = ""; try {//from w w w . j a va 2 s . com InputStream is = this.getAssets().open("testdata/rawdata.csv"); int size = is.available(); // Read the entire asset into a local byte buffer. byte[] buffer = new byte[size]; is.read(buffer); is.close(); // Convert the buffer into a Java string. String text = new String(buffer); rawMessageText = text; } catch (IOException e) { // Should never happen! throw new RuntimeException(e); } StringReader sr = new StringReader(rawMessageText); BufferedReader bufRdr = new BufferedReader(sr); String line = null; // int row = 0; // int col = 0; Vector<String[]> lines = new Vector<String[]>(); // read each line of text file try { while ((line = bufRdr.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, ","); int tokCount = st.countTokens(); String[] tokenizedLine = new String[tokCount]; int toki = 0; while (st.hasMoreTokens()) { tokenizedLine[toki] = st.nextToken(); toki++; } lines.add(tokenizedLine); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { sr.close(); bufRdr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } int len = lines.size(); for (int i = 0; i < len; i++) { String[] csvline = lines.get(i); String datestr = csvline[0]; Date dateval = new Date(); try { dateval = Message.SQLDateFormatter.parse(datestr); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sender = csvline[1]; String text = csvline[2]; Monitor monitor = MessageTranslator.GetMonitorAndInsertIfNew(this, sender); ContentValues messageValues = new ContentValues(); messageValues.put(RapidSmsDBConstants.Message.MESSAGE, text); messageValues.put(RapidSmsDBConstants.Message.MONITOR, monitor.getID()); messageValues.put(RapidSmsDBConstants.Message.TIME, Message.SQLDateFormatter.format(dateval)); messageValues.put(RapidSmsDBConstants.Message.RECEIVE_TIME, Message.SQLDateFormatter.format(dateval)); messageValues.put(RapidSmsDBConstants.Message.IS_OUTGOING, false); Uri msgUri = null; msgUri = this.getContentResolver().insert(RapidSmsDBConstants.Message.CONTENT_URI, messageValues); Vector<IParseResult> results = ParsingService.ParseMessage(mForm, text); ParsedDataTranslator.InsertFormData(this, mForm, Integer.valueOf(msgUri.getPathSegments().get(1)).intValue(), results); } }