List of usage examples for java.io DataInputStream close
public void close() throws IOException
From source file:com.xperia64.timidityae.PlaylistFragment.java
public ArrayList<String> parsePlist(String path) { ArrayList<String> plist = new ArrayList<String>(); try {//from w w w . j a v a 2s .c o m FileInputStream fstream = new FileInputStream(path); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { if (!TextUtils.isEmpty(strLine)) plist.add(strLine); } in.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } return plist; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore.java
private void loadRMSequentialNumberState(RMState rmState) throws Exception { byte[] seqData = getData(dtSequenceNumberPath); if (seqData != null) { ByteArrayInputStream seqIs = new ByteArrayInputStream(seqData); DataInputStream seqIn = new DataInputStream(seqIs); try {//from w w w.j a va 2 s.c om rmState.rmSecretManagerState.dtSequenceNumber = seqIn.readInt(); } finally { seqIn.close(); } } }
From source file:SortMixedRecordDataTypeExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/* w w w. j a v a2 s.c om*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); } catch (Exception error) { alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { byte[] outputRecord; String outputString[] = { "Mary", "Bob", "Adam" }; int outputInteger[] = { 15, 10, 5 }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); } outputStream.close(); outputDataStream.close(); } catch (Exception error) { alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { String[] inputString = new String[3]; int z = 0; byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); StringBuffer buffer = new StringBuffer(); comparator = new Comparator(); recordEnumeration = recordstore.enumerateRecords(null, comparator, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append(inputDataStream.readInt()); buffer.append("\n"); inputDataStream.reset(); } alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); inputDataStream.close(); inputStream.close(); } catch (Exception error) { alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } try { recordstore.closeRecordStore(); } catch (Exception error) { alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } if (RecordStore.listRecordStores() != null) { try { RecordStore.deleteRecordStore("myRecordStore"); comparator.compareClose(); recordEnumeration.destroy(); } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } } }
From source file:org.motechproject.mobile.web.OXDFormUploadServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w ww.java2s. c om*/ * * @param request * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ @RequestMapping(method = RequestMethod.POST) public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); IMPService impService = (IMPService) appCtx.getBean("impService"); StudyProcessor studyProcessor = (StudyProcessor) appCtx.getBean("studyProcessor"); InputStream input = request.getInputStream(); OutputStream output = response.getOutputStream(); ZOutputStream zOutput = null; // Wrap the streams for compression // Wrap the streams so for logical types DataInputStream dataInput = null; DataOutputStream dataOutput = null; // Set the MIME type so clients don't misinterpret response.setContentType("application/octet-stream"); try { zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION); dataInput = new DataInputStream(input); dataOutput = new DataOutputStream(zOutput); if (rawUploadLog.isInfoEnabled()) { byte[] rawPayload = IOUtils.toByteArray(dataInput); String hexEncodedPayload = Hex.encodeHexString(rawPayload); rawUploadLog.info(hexEncodedPayload); // Replace the original input stream with one using read payload dataInput.close(); dataInput = new DataInputStream(new ByteArrayInputStream(rawPayload)); } String name = dataInput.readUTF(); String password = dataInput.readUTF(); String serializer = dataInput.readUTF(); String locale = dataInput.readUTF(); byte action = dataInput.readByte(); // TODO Authentication of usename and password. Possible M6 // enhancement log.info("uploading: name=" + name + ", password=" + password + ", serializer=" + serializer + ", locale=" + locale + ", action=" + action); EpihandyXformSerializer serObj = new EpihandyXformSerializer(); serObj.addDeserializationListener(studyProcessor); try { Map<Integer, String> formVersionMap = formService.getXForms(); serObj.deserializeStudiesWithEvents(dataInput, formVersionMap); } catch (FormNotFoundException fne) { String msg = "failed to deserialize forms: "; log.error(msg + fne.getMessage()); dataOutput.writeByte(ResponseHeader.STATUS_FORMS_STALE); response.setStatus(HttpServletResponse.SC_OK); return; } catch (Exception e) { String msg = "failed to deserialize forms"; log.error(msg, e); dataOutput.writeByte(ResponseHeader.STATUS_ERROR); response.setStatus(HttpServletResponse.SC_OK); return; } String[][] studyForms = studyProcessor.getConvertedStudies(); int numForms = studyProcessor.getNumForms(); log.debug("upload contains: studies=" + studyForms.length + ", forms=" + numForms); // Starting processing here, only process until we run out of time int processedForms = 0; int faultyForms = 0; if (studyForms != null && numForms > 0) { formprocessing: for (int i = 0; i < studyForms.length; i++) { for (int j = 0; j < studyForms[i].length; j++, processedForms++) { if (maxProcessingTime > 0 && System.currentTimeMillis() - startTime > maxProcessingTime) break formprocessing; try { studyForms[i][j] = impService.processXForm(studyForms[i][j]); } catch (Exception ex) { log.error("processing form failed", ex); studyForms[i][j] = ex.getMessage(); } if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[i][j])) { faultyForms++; } } } } // Write out usual upload response dataOutput.writeByte(ResponseHeader.STATUS_SUCCESS); dataOutput.writeInt(processedForms); dataOutput.writeInt(faultyForms); for (int s = 0; s < studyForms.length; s++) { for (int f = 0; f < studyForms[s].length; f++) { if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[s][f])) { dataOutput.writeByte((byte) s); dataOutput.writeShort((short) f); dataOutput.writeUTF(studyForms[s][f]); } } } response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { log.error("failure during upload", e); } finally { if (dataOutput != null) dataOutput.flush(); if (zOutput != null) zOutput.finish(); response.flushBuffer(); } }
From source file:org.apache.pdfbox.tools.imageio.TestImageIOUtils.java
/** * checks whether the resolution of a BMP image file is as expected. * * @param filename the name of the BMP file * @param expectedResolution the expected resolution * * @throws IOException if something goes wrong */// w w w . jav a 2 s . c om private void checkBmpResolution(String filename, int expectedResolution) throws FileNotFoundException, IOException { // BMP format explained here: // http://www.javaworld.com/article/2077561/learn-java/java-tip-60--saving-bitmap-files-in-java.html // we skip 38 bytes and then read two 4 byte-integers and reverse the bytes DataInputStream dis = new DataInputStream(new FileInputStream(new File(filename))); int skipped = dis.skipBytes(38); assertEquals("Can't skip 38 bytes in image file " + filename, 38, skipped); int pixelsPerMeter = Integer.reverseBytes(dis.readInt()); int actualResolution = (int) Math.round(pixelsPerMeter / 100.0 * 2.54); assertEquals("X resolution doesn't match in image file " + filename, expectedResolution, actualResolution); pixelsPerMeter = Integer.reverseBytes(dis.readInt()); actualResolution = (int) Math.round(pixelsPerMeter / 100.0 * 2.54); assertEquals("Y resolution doesn't match in image file " + filename, expectedResolution, actualResolution); dis.close(); }
From source file:com.dream.library.utils.AbFileUtil.java
/** * ??byte[].//from w w w. ja v a 2 s .co m * * @param imgByte byte[] * @param fileName ?????.jpg * @param type ???AbConstant * @param desiredWidth * @param desiredHeight * @return Bitmap */ public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth, int desiredHeight) { FileOutputStream fos = null; DataInputStream dis = null; ByteArrayInputStream bis = null; Bitmap bitmap = null; File file = null; try { if (imgByte != null) { file = new File(AbDirUtils.getDownloadDir(), fileName); if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); int readLength = 0; bis = new ByteArrayInputStream(imgByte); dis = new DataInputStream(bis); byte[] buffer = new byte[1024]; while ((readLength = dis.read(buffer)) != -1) { fos.write(buffer, 0, readLength); try { Thread.sleep(500); } catch (Exception e) { } } fos.flush(); bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight); } } catch (Exception e) { e.printStackTrace(); } finally { if (dis != null) { try { dis.close(); } catch (Exception e) { } } if (bis != null) { try { bis.close(); } catch (Exception e) { } } if (fos != null) { try { fos.close(); } catch (Exception e) { } } } return bitmap; }
From source file:com.impetus.annovention.Discoverer.java
/** * that's my buddy! this is where all the discovery starts. *//* w ww . j a v a2 s. c om*/ public final void discover() { URL[] resources = findResources(); for (URL resource : resources) { log.debug("Scanning resource: " + resource.getPath()); try { ResourceIterator itr = getResourceIterator(resource, getFilter()); InputStream is = null; while ((is = itr.next()) != null) { // make a data input stream DataInputStream dstream = new DataInputStream(new BufferedInputStream(is)); try { // get java-assist class file ClassFile classFile = new ClassFile(dstream); log.debug("Scanning class: " + classFile.getName()); // discover class-level annotations discoverAndIntimateForClassAnnotations(classFile); // discover field annotations discoverAndIntimateForFieldAnnotations(classFile); // discover method annotations discoverAndIntimateForMethodAnnotations(classFile); } finally { dstream.close(); is.close(); } } } catch (IOException e) { // TODO: Do something with this exception e.printStackTrace(); } } }
From source file:org.apache.hadoop.hbase.migration.nineteen.regionserver.HStoreFile.java
/** * Reads in an info file//from www . ja v a 2 s.c om * * @param filesystem file system * @return The sequence id contained in the info file * @throws IOException */ public long loadInfo(final FileSystem filesystem) throws IOException { Path p = null; if (isReference()) { p = getInfoFilePath(reference.getEncodedRegionName(), this.reference.getFileId()); } else { p = getInfoFilePath(); } long length = filesystem.getFileStatus(p).getLen(); boolean hasMoreThanSeqNum = length > (Byte.SIZE + Bytes.SIZEOF_LONG); DataInputStream in = new DataInputStream(filesystem.open(p)); try { byte flag = in.readByte(); if (flag == INFO_SEQ_NUM) { if (hasMoreThanSeqNum) { flag = in.readByte(); if (flag == MAJOR_COMPACTION) { this.majorCompaction = in.readBoolean(); } } return in.readLong(); } throw new IOException("Cannot process log file: " + p); } finally { in.close(); } }
From source file:com.l2jfree.gameserver.util.JarClassLoader.java
private byte[] loadClassData(String name) throws IOException { byte[] classData = null; for (String jarFile : _jars) { ZipFile zipFile = null;/*from w w w .j av a 2 s . co m*/ DataInputStream zipStream = null; try { File file = new File(jarFile); zipFile = new ZipFile(file); String fileName = name.replace('.', '/') + ".class"; ZipEntry entry = zipFile.getEntry(fileName); if (entry == null) continue; classData = new byte[(int) entry.getSize()]; zipStream = new DataInputStream(zipFile.getInputStream(entry)); zipStream.readFully(classData, 0, (int) entry.getSize()); break; } catch (IOException e) { _log.warn(jarFile + ":", e); continue; } finally { try { if (zipFile != null) zipFile.close(); } catch (Exception e) { _log.warn("", e); } try { if (zipStream != null) zipStream.close(); } catch (Exception e) { _log.warn("", e); } } } if (classData == null) throw new IOException("class not found in " + _jars); return classData; }
From source file:openaf.AFCmdOS.java
/** * // ww w . j a va2s . c om * @param in * @param out * @param appoperation2 * @throws Exception */ protected com.google.gson.JsonObject execute(com.google.gson.JsonObject pmIn, String op, boolean processScript, StringBuilder theInput, boolean isolatePMs) throws Exception { // 3. Process input // INPUT_TYPE = inputtype.INPUT_SCRIPT; if (((!pipe) && (!filescript) && (!processScript) && (!injectcode) && (!injectclass))) { if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { /*injectscript = true; injectscriptfile = "/js/openafgui.js"; filescript = true;*/ injectclass = true; injectclassfile = "openafgui_js"; filescript = false; silentMode = true; } } if (processScript || filescript || injectcode || injectclass) { // Obtain script String script = null; if (filescript) { if (injectscript) { script = IOUtils.toString(getClass().getResourceAsStream(injectscriptfile), "UTF-8"); } else { boolean isZip = false; boolean isOpack = false; com.google.gson.JsonObject pm = null; ZipFile tmpZip = null; // Determine if it's opack/zip DataInputStream dis = new DataInputStream( new BufferedInputStream(new FileInputStream(scriptfile.replaceFirst("::[^:]+$", "")))); int test = dis.readInt(); dis.close(); if (test == 0x504b0304) { isZip = true; try { tmpZip = new ZipFile(scriptfile.replaceFirst("::[^:]+$", "")); isOpack = tmpZip.getEntry(OPACK) != null; zip = tmpZip; } catch (Exception e) { } if (isOpack) { if (scriptfile.indexOf("::") <= 0) { pm = new Gson().fromJson( IOUtils.toString(zip.getInputStream(zip.getEntry(OPACK)), (Charset) null), JsonObject.class); try { pm.get("main"); } catch (Exception e) { isZip = false; } } } } // Read normal script or opack/zip if (isZip) { if (scriptfile.indexOf("::") <= 0 && isOpack) { if (pm.get("main").getAsString().length() > 0) { script = IOUtils.toString( zip.getInputStream(zip.getEntry(pm.get("main").getAsString())), "UTF-8"); scriptfile = scriptfile + "/" + pm.get("main").getAsString(); } else { throw new Exception("Can't execute main script in " + scriptfile); } } else { try { script = IOUtils.toString( zip.getInputStream(zip.getEntry(scriptfile.replaceFirst(".+::", ""))), "UTF-8"); } catch (NullPointerException e) { throw new Exception("Can't find " + scriptfile.replaceFirst(".+::", "")); } } } else { script = FileUtils.readFileToString(new File(scriptfile), (Charset) null); zip = null; } } } else { if (!injectclass) script = theInput.toString(); } if (script != null) { script = script.replaceAll("^#.*", "//"); script = script.replaceFirst(PREFIX_SCRIPT, ""); if (daemon) script = "ow.loadServer().simpleCheckIn('" + scriptfile + "'); " + script + "; ow.loadServer().daemon();"; if (injectcode) script += code; } Context cx = (Context) jse.getNotSafeContext(); cx.setErrorReporter(new OpenRhinoErrorReporter()); String includeScript = ""; NativeObject jsonPMOut = new NativeObject(); synchronized (this) { Object opmIn; opmIn = AFBase.jsonParse(pmIn.toString()); Object noSLF4JErrorOnly = Context.javaToJS(__noSLF4JErrorOnly, (Scriptable) jse.getGlobalscope()); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__noSLF4JErrorOnly", noSLF4JErrorOnly); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "pmIn", opmIn); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__pmIn", opmIn); // Add pmOut object Object opmOut = Context.javaToJS(jsonPMOut, (Scriptable) jse.getGlobalscope()); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "pmOut", opmOut); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__pmOut", opmOut); // Add expr object Object opmExpr = Context.javaToJS(exprInput, (Scriptable) jse.getGlobalscope()); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "expr", opmExpr); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__expr", opmExpr); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__args", args); // Add scriptfile object if (filescript) { Object scriptFile = Context.javaToJS(scriptfile, (Scriptable) jse.getGlobalscope()); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__scriptfile", scriptFile); ScriptableObject.putProperty((Scriptable) jse.getGlobalscope(), "__iszip", (zip == null) ? false : true); } // Add AF class ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), AFBase.class, false, true); // Add DB class ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), DB.class, false, true); // Add CSV class ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), CSV.class, false, true); // Add IO class ScriptableObject.defineClass((Scriptable) jse.getGlobalscope(), IOBase.class, false, true); // Add this object Scriptable afScript = null; //if (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "AF")) { afScript = (Scriptable) jse.newObject((Scriptable) jse.getGlobalscope(), "AF"); //} if (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "af")) ((IdScriptableObject) jse.getGlobalscope()).put("af", (Scriptable) jse.getGlobalscope(), afScript); // Add the IO object if (!ScriptableObject.hasProperty((Scriptable) jse.getGlobalscope(), "io")) ((IdScriptableObject) jse.getGlobalscope()).put("io", (Scriptable) jse.getGlobalscope(), jse.newObject(jse.getGlobalscope(), "IO")); } // Compile & execute script /*try { InputStream in1 = getClass().getResourceAsStream("/js/openaf.js"); includeScript = IOUtils.toString(in1, (Charset) null); numberOfIncludedLines = numberOfIncludedLines + includeScript.split("\r\n|\r|\n").length; AFCmdBase.jse.addNumberOfLines(includeScript); } catch (Exception e) { SimpleLog.log(logtype.DEBUG, "Error including openaf.js", e); }*/ AFBase.runFromClass(Class.forName("openaf_js").getDeclaredConstructor().newInstance()); cx.setErrorReporter(new OpenRhinoErrorReporter()); if (isolatePMs) { script = "(function(__pIn) { var __pmOut = {}; var __pmIn = __pIn; " + script + "; return __pmOut; })(" + pmIn.toString() + ")"; } Object res = null; if (injectscript || filescript || injectcode || processScript) { Context cxl = (Context) jse.enterContext(); org.mozilla.javascript.Script compiledScript = cxl.compileString(includeScript + script, scriptfile, 1, null); res = compiledScript.exec(cxl, (Scriptable) jse.getGlobalscope()); jse.exitContext(); } if (injectclass) { res = AFBase.runFromClass(Class.forName(injectclassfile).getDeclaredConstructor().newInstance()); } if (isolatePMs && res != null && !(res instanceof Undefined)) { jsonPMOut = (NativeObject) res; } else { // Obtain pmOut as output jsonPMOut = (NativeObject) ((ScriptableObject) jse.getGlobalscope()).get("__pmOut"); } // Convert to ParameterMap Object stringify = NativeJSON.stringify(cx, (Scriptable) jse.getGlobalscope(), jsonPMOut, null, null); com.google.gson.Gson gson = new com.google.gson.Gson(); pmOut = gson.fromJson(stringify.toString(), com.google.gson.JsonObject.class); // Leave Rhino //org.mozilla.javascript.Context.exit(); //jse.exitContext(); } return pmOut; }