List of usage examples for java.io DataInputStream readByte
public final byte readByte() throws IOException
readByte
method of DataInput
. From source file:VASSAL.tools.imports.adc2.MapBoard.java
/** * Information about the width, colour and style of hex sides and hex lines is read in. */// w w w .j a v a2s . c o m protected void readLineDefinitionBlock(DataInputStream in) throws IOException { ADC2Utils.readBlockHeader(in, "Line Definition"); int nLineDefinitions = in.readUnsignedByte(); lineDefinitions = new LineDefinition[nLineDefinitions]; for (int i = 0; i < nLineDefinitions; ++i) { int colorIndex = in.readUnsignedByte(); Color color = ADC2Utils.getColorFromIndex(colorIndex); int size = 0; for (int j = 0; j < 3; ++j) { int s = in.readByte(); if (j == zoomLevel) size = s; } // only used when editing ADC2 maps within ADC2. /* String name = */ readNullTerminatedString(in, 25); int styleByte = in.readUnsignedByte(); LineStyle style; switch (styleByte) { case 2: style = LineStyle.DOTTED; break; case 3: style = LineStyle.DASH_DOT; break; case 4: style = LineStyle.DASHED; break; case 5: style = LineStyle.DASH_DOT_DOT; break; default: style = LineStyle.SOLID; } if (size > 0) lineDefinitions[i] = new LineDefinition(color, size, style); else lineDefinitions[i] = null; } }
From source file:VASSAL.tools.imports.adc2.MapBoard.java
/** * Optional labels that can be added to hexes. Can also include a symbol that can be added with the label. *///w w w . j a v a 2 s. c o m protected void readPlaceNameBlock(DataInputStream in) throws IOException { ADC2Utils.readBlockHeader(in, "Place Name"); int nNames = ADC2Utils.readBase250Word(in); for (int i = 0; i < nNames; ++i) { int index = ADC2Utils.readBase250Word(in); // extra hex symbol SymbolSet.SymbolData symbol = getSet().getMapBoardSymbol(ADC2Utils.readBase250Word(in)); if (symbol != null && isOnMapBoard(index)) placeSymbols.add(new HexData(index, symbol)); String text = readNullTerminatedString(in, 25); Color color = ADC2Utils.getColorFromIndex(in.readUnsignedByte()); int size = 0; for (int z = 0; z < 3; ++z) { int b = in.readUnsignedByte(); if (z == zoomLevel) size = b; } PlaceNameOrientation orientation = null; for (int z = 0; z < 3; ++z) { int o = in.readByte(); if (z == zoomLevel) { switch (o) { case 1: orientation = PlaceNameOrientation.LOWER_CENTER; break; case 2: orientation = PlaceNameOrientation.UPPER_CENTER; break; case 3: orientation = PlaceNameOrientation.LOWER_RIGHT; break; case 4: orientation = PlaceNameOrientation.UPPER_RIGHT; break; case 5: orientation = PlaceNameOrientation.UPPER_LEFT; break; case 6: orientation = PlaceNameOrientation.LOWER_LEFT; break; case 7: orientation = PlaceNameOrientation.CENTER_LEFT; break; case 8: orientation = PlaceNameOrientation.CENTER_RIGHT; break; case 9: orientation = PlaceNameOrientation.HEX_CENTER; break; } } } int font = in.readUnsignedByte(); if (!isOnMapBoard(index) || text.length() == 0 || orientation == null) continue; placeNames.add(new PlaceName(index, text, color, orientation, size, font)); } }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * This assumes that authentication is the last piece of info in handshake */// w w w. j a va 2 s .c o m public void writeCredentials(DataOutputStream dos, DataInputStream dis, Properties p_credentials, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException { if (p_credentials == null) { // No credentials indicator heapdos.writeByte(CREDENTIALS_NONE); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return; } if (dhSKAlgo == null || dhSKAlgo.length() == 0) { // Normal credentials without encryption indicator heapdos.writeByte(CREDENTIALS_NORMAL); DataSerializer.writeProperties(p_credentials, heapdos); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return; } try { InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter(); securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo); boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0); if (requireAuthentication) { securityLogWriter.fine("HandShake: server authentication using digital " + "signature required"); } // Credentials with encryption indicator heapdos.writeByte(CREDENTIALS_DHENCRYPT); heapdos.writeBoolean(requireAuthentication); // Send the symmetric encryption algorithm name DataSerializer.writeString(dhSKAlgo, heapdos); // Send the DH public key byte[] keyBytes = dhPublicKey.getEncoded(); DataSerializer.writeByteArray(keyBytes, heapdos); byte[] clientChallenge = null; if (requireAuthentication) { // Authentication of server should be with the client supplied // challenge clientChallenge = new byte[64]; random.nextBytes(clientChallenge); DataSerializer.writeByteArray(clientChallenge, heapdos); } heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); // Expect the alias and signature in the reply byte acceptanceCode = dis.readByte(); if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) { // Ignore the useless data dis.readByte(); dis.readInt(); if (!isNotification) { DataSerializer.readByteArray(dis); } readMessage(dis, dos, acceptanceCode, member); } else if (acceptanceCode == REPLY_OK) { // Get the public key of the other side keyBytes = DataSerializer.readByteArray(dis); if (requireAuthentication) { String subject = DataSerializer.readString(dis); byte[] signatureBytes = DataSerializer.readByteArray(dis); if (!certificateMap.containsKey(subject)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0 .toLocalizedString(subject)); } // Check the signature with the public key X509Certificate cert = (X509Certificate) certificateMap.get(subject); Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert); sig.update(clientChallenge); // Check the challenge string if (!sig.verify(signatureBytes)) { throw new AuthenticationFailedException( "Mismatch in client " + "challenge bytes. Malicious server?"); } securityLogWriter .fine("HandShake: Successfully verified the " + "digital signature from server"); } byte[] challenge = DataSerializer.readByteArray(dis); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); // PublicKey pubKey = keyFact.generatePublic(x509KeySpec); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { DataSerializer.writeProperties(p_credentials, hdos); // Also add the challenge string DataSerializer.writeByteArray(challenge, hdos); // byte[] encBytes = encrypt.doFinal(hdos.toByteArray()); byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey)); DataSerializer.writeByteArray(encBytes, dos); } finally { hdos.close(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex); } dos.flush(); }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * This method writes what readCredential() method expects to read. (Note the use of singular * credential). It is similar to writeCredentials(), except that it doesn't write * credential-properties./*w w w .java2 s .com*/ */ public byte writeCredential(DataOutputStream dos, DataInputStream dis, String authInit, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException { if (!this.multiuserSecureMode && (authInit == null || authInit.length() == 0)) { // No credentials indicator heapdos.writeByte(CREDENTIALS_NONE); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return -1; } if (dhSKAlgo == null || dhSKAlgo.length() == 0) { // Normal credentials without encryption indicator heapdos.writeByte(CREDENTIALS_NORMAL); this.appSecureMode = CREDENTIALS_NORMAL; // DataSerializer.writeProperties(p_credentials, heapdos); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return -1; } byte acceptanceCode = -1; try { InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter(); securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo); boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0); if (requireAuthentication) { securityLogWriter.fine("HandShake: server authentication using digital " + "signature required"); } // Credentials with encryption indicator heapdos.writeByte(CREDENTIALS_DHENCRYPT); this.appSecureMode = CREDENTIALS_DHENCRYPT; heapdos.writeBoolean(requireAuthentication); // Send the symmetric encryption algorithm name DataSerializer.writeString(dhSKAlgo, heapdos); // Send the DH public key byte[] keyBytes = dhPublicKey.getEncoded(); DataSerializer.writeByteArray(keyBytes, heapdos); byte[] clientChallenge = null; if (requireAuthentication) { // Authentication of server should be with the client supplied // challenge clientChallenge = new byte[64]; random.nextBytes(clientChallenge); DataSerializer.writeByteArray(clientChallenge, heapdos); } heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); // Expect the alias and signature in the reply acceptanceCode = dis.readByte(); if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) { // Ignore the useless data dis.readByte(); dis.readInt(); if (!isNotification) { DataSerializer.readByteArray(dis); } readMessage(dis, dos, acceptanceCode, member); } else if (acceptanceCode == REPLY_OK) { // Get the public key of the other side keyBytes = DataSerializer.readByteArray(dis); if (requireAuthentication) { String subject = DataSerializer.readString(dis); byte[] signatureBytes = DataSerializer.readByteArray(dis); if (!certificateMap.containsKey(subject)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0 .toLocalizedString(subject)); } // Check the signature with the public key X509Certificate cert = (X509Certificate) certificateMap.get(subject); Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert); sig.update(clientChallenge); // Check the challenge string if (!sig.verify(signatureBytes)) { throw new AuthenticationFailedException( "Mismatch in client " + "challenge bytes. Malicious server?"); } securityLogWriter .fine("HandShake: Successfully verified the " + "digital signature from server"); } // Read server challenge bytes byte[] serverChallenge = DataSerializer.readByteArray(dis); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); // PublicKey pubKey = keyFact.generatePublic(x509KeySpec); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { // Add the challenge string DataSerializer.writeByteArray(serverChallenge, hdos); // byte[] encBytes = encrypt.doFinal(hdos.toByteArray()); byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey)); DataSerializer.writeByteArray(encBytes, dos); } finally { hdos.close(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex); } dos.flush(); return acceptanceCode; }
From source file:org.apache.hadoop.hdfs.server.namenode.IngestLocal.java
/** * Continue to ingest transaction logs until the currentState is * no longer INGEST. If lastScan is set to true, then we process * till the end of the file and return.//from ww w.jav a 2s. c o m */ int ingestFSEdits(File fname, DataInputStream in, int logVersion) throws IOException { FSNamesystem fsNamesys = FSNamesystem.getFSNamesystem(); FSDirectory fsDir = fsNamesys.dir; int numEdits = 0; String clientName = null; String clientMachine = null; String path = null; int numOpAdd = 0, numOpClose = 0, numOpDelete = 0, numOpRename = 0, numOpSetRepl = 0, numOpMkDir = 0, numOpSetPerm = 0, numOpSetOwner = 0, numOpSetGenStamp = 0, numOpTimes = 0, numOpOther = 0; long startTime = FSNamesystem.now(); boolean error = false; boolean quitAfterScan = false; while (running && !quitAfterScan) { // if the application requested that we make a final pass over // the transaction log, then we remember it here. We close and // reopen the file to ensure that we can see all the data in the // file, one reason being that NFS has open-to-close cache // coherancy and the edit log could be stored in NFS. // if (lastScan) { LOG.info("Ingest: Starting last scan of transaction log " + fname); quitAfterScan = true; fp.close(); rp = new RandomAccessFile(fname, "r"); fp = new FileInputStream(rp.getFD()); // open for reads fc = rp.getChannel(); // discard older buffers and start a fresh one. fc.position(currentPosition); in = new DataInputStream(fp); } // // Verify that signature of file matches. This is imporatant in the // case when the Primary NN was configured to write transactions to // to devices (local and NFS) and the Primary had encountered errors // to the NFS device and has continued writing transactions to its // device only. In this case, the rollEditLog() RPC would return the // modtime of the edits file of the Primary's local device and will // not match with the timestamp of our local log from where we are // ingesting. // CheckpointSignature signature = getLastCheckpointSignature(); if (signature != null) { long localtime = fname.lastModified(); LOG.info("editLog : " + fname.getPath()); LOG.info("editLog.lastModifiedTime : " + localtime); if (localtime == signature.editsTime) { LOG.debug("Ingest: Matched modification time of edits log. "); } else if (localtime < signature.editsTime) { LOG.info("Ingest: Timestamp of transaction log on local machine is " + localtime + " and on remote namenode is " + signature.editsTime); String msg = "Ingest: Timestamp of transaction log on local machine is " + DATE_FORM.format(new Date(localtime)) + " and on remote namenode is " + DATE_FORM.format(new Date(signature.editsTime)); LOG.info(msg); throw new IOException(msg); } else { LOG.info("Ingest: Timestamp of transaction log on local machine is " + localtime + " and on remote namenode is " + signature.editsTime); String msg = "Ingest: Timestamp of transaction log on localmachine is " + DATE_FORM.format(new Date(localtime)) + " and on remote namenode is " + DATE_FORM.format(new Date(signature.editsTime)) + ". But this can never happen."; LOG.info(msg); throw new IOException(msg); } } // // Process all existing transactions till end of file // while (running) { currentPosition = fc.position(); // record the current file offset. try { long timestamp = 0; long mtime = 0; long atime = 0; long blockSize = 0; byte opcode = -1; error = false; try { opcode = in.readByte(); if (opcode == OP_INVALID) { FSNamesystem.LOG.debug("Ingest: Invalid opcode, reached end of log " + "Number of transactions found " + numEdits); break; // No more transactions. } } catch (EOFException e) { break; // No more transactions. } switch (opcode) { case OP_ADD: case OP_CLOSE: { // versions > 0 support per file replication // get name and replication int length = in.readInt(); if (-7 == logVersion && length != 3 || -17 < logVersion && logVersion < -7 && length != 4 || logVersion <= -17 && length != 5) { throw new IOException("Ingest: Incorrect data format." + " logVersion is " + logVersion + " but writables.length is " + length + ". "); } path = FSImage.readString(in); short replication = readShort(in); mtime = readLong(in); if (logVersion <= -17) { atime = readLong(in); } if (logVersion < -7) { blockSize = readLong(in); } // get blocks Block blocks[] = null; if (logVersion <= -14) { blocks = readBlocks(in); } else { BlockTwo oldblk = new BlockTwo(); int num = in.readInt(); blocks = new Block[num]; for (int i = 0; i < num; i++) { oldblk.readFields(in); blocks[i] = new Block(oldblk.blkid, oldblk.len, Block.GRANDFATHER_GENERATION_STAMP); } } // Older versions of HDFS does not store the block size in inode. // If the file has more than one block, use the size of the // first block as the blocksize. Otherwise use the default // block size. if (-8 <= logVersion && blockSize == 0) { if (blocks.length > 1) { blockSize = blocks[0].getNumBytes(); } else { long first = ((blocks.length == 1) ? blocks[0].getNumBytes() : 0); blockSize = Math.max(fsNamesys.getDefaultBlockSize(), first); } } PermissionStatus permissions = fsNamesys.getUpgradePermission(); if (logVersion <= -11) { permissions = PermissionStatus.read(in); } // clientname, clientMachine and block locations of last block. if (opcode == OP_ADD && logVersion <= -12) { clientName = FSImage.readString(in); clientMachine = FSImage.readString(in); if (-13 <= logVersion) { readDatanodeDescriptorArray(in); } } else { clientName = ""; clientMachine = ""; } // The open lease transaction re-creates a file if necessary. // Delete the file if it already exists. if (FSNamesystem.LOG.isDebugEnabled()) { FSNamesystem.LOG.debug(opcode + ": " + path + " numblocks : " + blocks.length + " clientHolder " + clientName + " clientMachine " + clientMachine); } fsDir.unprotectedDelete(path, mtime); // add to the file tree INodeFile node = (INodeFile) fsDir.unprotectedAddFile(path, permissions, blocks, replication, mtime, atime, blockSize); if (opcode == OP_ADD) { numOpAdd++; // // Replace current node with a INodeUnderConstruction. // Recreate in-memory lease record. // INodeFileUnderConstruction cons = new INodeFileUnderConstruction( node.getLocalNameBytes(), node.getReplication(), node.getModificationTime(), node.getPreferredBlockSize(), node.getBlocks(), node.getPermissionStatus(), clientName, clientMachine, null); fsDir.replaceNode(path, node, cons); fsNamesys.leaseManager.addLease(cons.clientName, path); } break; } case OP_SET_REPLICATION: { numOpSetRepl++; path = FSImage.readString(in); short replication = readShort(in); fsDir.unprotectedSetReplication(path, replication, null); break; } case OP_RENAME: { numOpRename++; int length = in.readInt(); if (length != 3) { throw new IOException("Ingest: Incorrect data format. " + "Mkdir operation."); } String s = FSImage.readString(in); String d = FSImage.readString(in); timestamp = readLong(in); FileStatus dinfo = fsDir.getFileInfo(d); fsDir.unprotectedRenameTo(s, d, timestamp); fsNamesys.changeLease(s, d, dinfo); break; } case OP_DELETE: { numOpDelete++; int length = in.readInt(); if (length != 2) { throw new IOException("Ingest: Incorrect data format. " + "delete operation."); } path = FSImage.readString(in); timestamp = readLong(in); fsDir.unprotectedDelete(path, timestamp); break; } case OP_MKDIR: { numOpMkDir++; PermissionStatus permissions = fsNamesys.getUpgradePermission(); int length = in.readInt(); if (-17 < logVersion && length != 2 || logVersion <= -17 && length != 3) { throw new IOException("Ingest: Incorrect data format. " + "Mkdir operation."); } path = FSImage.readString(in); timestamp = readLong(in); // The disk format stores atimes for directories as well. // However, currently this is not being updated/used because of // performance reasons. if (logVersion <= -17) { atime = readLong(in); } if (logVersion <= -11) { permissions = PermissionStatus.read(in); } fsDir.unprotectedMkdir(path, permissions, timestamp); break; } case OP_SET_GENSTAMP: { numOpSetGenStamp++; long lw = in.readLong(); fsDir.namesystem.setGenerationStamp(lw); break; } case OP_DATANODE_ADD: { numOpOther++; FSImage.DatanodeImage nodeimage = new FSImage.DatanodeImage(); nodeimage.readFields(in); //Datnodes are not persistent any more. break; } case OP_DATANODE_REMOVE: { numOpOther++; DatanodeID nodeID = new DatanodeID(); nodeID.readFields(in); //Datanodes are not persistent any more. break; } case OP_SET_PERMISSIONS: { numOpSetPerm++; if (logVersion > -11) throw new IOException( "Ingest: Unexpected opcode " + opcode + " for version " + logVersion); fsDir.unprotectedSetPermission(FSImage.readString(in), FsPermission.read(in)); break; } case OP_SET_OWNER: { numOpSetOwner++; if (logVersion > -11) throw new IOException( "Ingest: Unexpected opcode " + opcode + " for version " + logVersion); fsDir.unprotectedSetOwner(FSImage.readString(in), FSImage.readString_EmptyAsNull(in), FSImage.readString_EmptyAsNull(in)); break; } case OP_SET_NS_QUOTA: { if (logVersion > -16) { throw new IOException( "Ingest: Unexpected opcode " + opcode + " for version " + logVersion); } fsDir.unprotectedSetQuota(FSImage.readString(in), readLongWritable(in), FSConstants.QUOTA_DONT_SET); break; } case OP_CLEAR_NS_QUOTA: { if (logVersion > -16) { throw new IOException( "Ingest: Unexpected opcode " + opcode + " for version " + logVersion); } fsDir.unprotectedSetQuota(FSImage.readString(in), FSConstants.QUOTA_RESET, FSConstants.QUOTA_DONT_SET); break; } case OP_SET_QUOTA: fsDir.unprotectedSetQuota(FSImage.readString(in), readLongWritable(in), readLongWritable(in)); break; case OP_TIMES: { numOpTimes++; int length = in.readInt(); if (length != 3) { throw new IOException("Ingest: Incorrect data format. " + "times operation."); } path = FSImage.readString(in); mtime = readLong(in); atime = readLong(in); fsDir.unprotectedSetTimes(path, mtime, atime, true); break; } default: { throw new IOException("Ingest: Never seen opcode " + opcode); } } numEdits++; LOG.info("Ingest: Processed transaction from " + fname + " opcode " + opcode + " file offset " + currentPosition); } //rty--- catch (IOException e) { error = true; // if we haven't reached eof, then error. break; } } // while (running)----- // if we failed to read the entire transaction from disk, // then roll back to the offset where there was a last good // read, sleep for sometime for new transaction to // appear in the file and then continue; // if (error || running) { // discard older buffers and start a fresh one. fc.position(currentPosition); in = new DataInputStream(fp); if (error) { LOG.info("Ingest: Incomplete transaction record at offset " + fc.position() + " but the file is of size " + fc.size() + ". Continuing...."); } if (running && !lastScan) { try { Thread.sleep(1000); // sleep for a second } catch (InterruptedException e) { // break out of waiting if we receive an interrupt. } } } } //while (running && !quitAfterScan)------------- LOG.info("Ingest: Edits file " + fname.getName() + " numedits " + numEdits + " loaded in " + (FSNamesystem.now() - startTime) / 1000 + " seconds."); // If the last Scan was completed, then stop the Ingest thread. if (lastScan && quitAfterScan) { LOG.info("Ingest: lastScan completed."); running = false; } return numEdits; // total transactions consumed }
From source file:org.apache.geode.internal.cache.Oplog.java
private void validateOpcode(DataInputStream dis, byte expect) throws IOException { byte opCode = dis.readByte(); if (opCode != expect) { if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY)) { logger.trace(LogMarker.PERSIST_RECOVERY, "expected opcode id absent: {}", expect); }/* w w w . j a v a2 s. c om*/ throw new IllegalStateException(); } }
From source file:com.codename1.impl.android.AndroidImplementation.java
public static void firePendingPushes(final PushCallback c, final Context a) { try {/*from w ww .j a v a 2s.c om*/ if (c != null) { InputStream i = a.openFileInput("CN1$AndroidPendingNotifications"); if (i == null) { return; } DataInputStream is = new DataInputStream(i); int count = is.readByte(); for (int iter = 0; iter < count; iter++) { boolean hasType = is.readBoolean(); String actualType = null; if (hasType) { actualType = is.readUTF(); } final String t; final String b; final String category; final String image; if ("99".equals(actualType)) { // This was a rich push Map<String, String> vals = splitQuery(is.readUTF()); t = vals.get("type"); b = vals.get("body"); category = vals.get("category"); image = vals.get("image"); } else { t = actualType; b = is.readUTF(); category = null; image = null; } long s = is.readLong(); Display.getInstance().callSerially(new Runnable() { @Override public void run() { Display.getInstance().setProperty("pendingPush", "true"); Display.getInstance().setProperty("pushType", t); initPushContent(b, image, t, category, a); if (t != null && ("3".equals(t) || "6".equals(t))) { String[] a = b.split(";"); c.push(a[0]); c.push(a[1]); } else if (t != null && ("101".equals(t))) { c.push(b.substring(b.indexOf(" ") + 1)); } else { c.push(b); } Display.getInstance().setProperty("pendingPush", null); } }); } a.deleteFile("CN1$AndroidPendingNotifications"); } } catch (IOException err) { } }
From source file:com.codename1.impl.android.AndroidImplementation.java
public static String[] getPendingPush(String type, Context a) { InputStream i = null;// ww w . j a va 2s. c om try { i = a.openFileInput("CN1$AndroidPendingNotifications"); if (i == null) { return null; } DataInputStream is = new DataInputStream(i); int count = is.readByte(); Vector v = new Vector<String>(); for (int iter = 0; iter < count; iter++) { boolean hasType = is.readBoolean(); String actualType = null; if (hasType) { actualType = is.readUTF(); } final String t; final String b; if ("99".equals(actualType)) { // This was a rich push Map<String, String> vals = splitQuery(is.readUTF()); t = vals.get("type"); b = vals.get("body"); //category = vals.get("category"); //image = vals.get("image"); } else { t = actualType; b = is.readUTF(); //category = null; //image = null; } long s = is.readLong(); if (t != null && ("3".equals(t) || "6".equals(t))) { String[] m = b.split(";"); v.add(m[0]); } else if (t != null && "4".equals(t)) { String[] m = b.split(";"); v.add(m[1]); } else if (t != null && "2".equals(t)) { continue; } else if (t != null && "101".equals(t)) { v.add(b.substring(b.indexOf(" ") + 1)); } else { v.add(b); } } String[] retVal = new String[v.size()]; for (int j = 0; j < retVal.length; j++) { retVal[j] = (String) v.get(j); } return retVal; } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (i != null) { i.close(); } } catch (IOException ex) { } } return null; }
From source file:bankingclient.ChonThaoTacFrame.java
public ChonThaoTacFrame(NewOrOldAccFrame acc) { initComponents();// w ww. jav a 2 s. c o m jTextField1.setText(""); jLabel4.setVisible(false); jComboBox2.setVisible(false); jLabel2.setVisible(false); jLabel3.setVisible(false); jTextField1.setVisible(false); jBt_xn1.setVisible(false); jBt_xn2.setVisible(false); this.accList = null; this.cusList = null; this.noAcc = acc; this.tt = new Thong_Tin_TK(this); this.setVisible(false); jBt_xn1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (NumberUtils.isNumber(jTextField1.getText()) && (Long.parseLong(jTextField1.getText()) > 0)) { long currentMoney = 0; try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(8); dout.writeUTF((String) jComboBox1.getSelectedItem()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); Scanner lineScanner = new Scanner(din.readUTF()); currentMoney = Long.parseLong(lineScanner.nextLine()); System.out.println(currentMoney); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "Li kt ni mng,bn cn kim tra kt ni"); } if (jCheck_gt.isSelected()) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(5); dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + jTextField1.getText() + "\n" + (noAcc.getCustomer())); dout.flush(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy ra...."); } JOptionPane.showMessageDialog(rootPane, "Gi Ti?n Thnh Cng..."); } if (jCheck_rt.isSelected()) { if ((Long.parseLong(jTextField1.getText()) <= currentMoney)) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(6); dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + jTextField1.getText() + "\n" + (noAcc.getCustomer())); dout.flush(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy Ra....."); } JOptionPane.showMessageDialog(rootPane, "Rt Ti?n Thnh Cng ..."); } else { System.out.println("Khng Ti?n Trong ti khon.." + currentMoney); JOptionPane.showMessageDialog(null, "Ti Khon Khng ? ? Rt ..."); } } noAcc.setVisible(true); ChonThaoTacFrame.this.setVisible(false); } else { JOptionPane.showMessageDialog(rootPane, "Cn Nhp Li S Ti?n Cn Gi Hoc Rt.."); } } }); jBt_tt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tt.setTk((String) jComboBox1.getSelectedItem()); tt.hienTenTk(); long currentMoney = 0; try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(8); dout.writeUTF((String) jComboBox1.getSelectedItem()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); Scanner lineScanner = new Scanner(din.readUTF()); currentMoney = Long.parseLong(lineScanner.nextLine()); // System.out.println(currentMoney); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "Li kt ni mng,bn cn kim tra kt ni"); } tt.hienSoDu(((Long) currentMoney).toString()); tt.setVisible(true); try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(10); dout.writeUTF((String) jComboBox1.getSelectedItem()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); Scanner cusScanner = new Scanner(din.readUTF()); while (cusScanner.hasNextLine()) { tt.addCus(cusScanner.nextLine()); } } catch (Exception ee) { ee.printStackTrace(); } tt.hienChuTaiKhoan(); try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(12); dout.writeUTF((String) jComboBox1.getSelectedItem()); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); Scanner dateScanner = new Scanner(din.readUTF()); int day = Integer.parseInt(dateScanner.nextLine()); int month = Integer.parseInt(dateScanner.nextLine()); int year = Integer.parseInt(dateScanner.nextLine()); String date = (day + "-" + month + "-" + year); tt.hienNgayLapTaiKhoan(date); while (dateScanner.hasNextLine()) { // System.out.println("aaa"); tt.addGiaoDich(dateScanner.nextLine()); } tt.hienGiaoDich(); } catch (Exception ex) { ex.printStackTrace(); } ChonThaoTacFrame.this.setVisible(false); } }); jBt_xn2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jCheck_tctk.isSelected()) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(7); dout.writeUTF((String) jComboBox1.getSelectedItem() + "\n" + (String) jComboBox2.getSelectedItem()); dout.flush(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Xy Ra\n Thm Ch Tht Bi..."); } JOptionPane.showMessageDialog(rootPane, "Thm Ch Ti Khon Thnh Cng.."); } else { System.out.println("nothing to do..."); } } }); jBt_xtk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Socket client = new Socket("113.22.46.207", 6013); DataOutputStream dout = new DataOutputStream(client.getOutputStream()); dout.writeByte(11); String sent = (String) (jComboBox1.getSelectedItem()) + "\n" + noAcc.getCustomer(); dout.writeUTF(sent); dout.flush(); DataInputStream din = new DataInputStream(client.getInputStream()); byte check = din.readByte(); if (check == 1) { JOptionPane.showMessageDialog(rootPane, "xoa tai khoan thanh cong"); } else { JOptionPane.showMessageDialog(rootPane, "<html>xoa tai khoan <b>khong</b> thanh cong <br> chi chu chinh moi co the xoa tai khoan</html>"); } } catch (Exception ee) { ee.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "Li Kt Ni ,Vui Lng Kim Tra Li.."); } } }); /*dont touch*/ jBt_ql.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { noAcc.setVisible(true); ChonThaoTacFrame.this.setVisible(false); } }); /*dont touch*/ jComboBox1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); jComboBox2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); /*dont touch jcheckbox*/ jCheck_tctk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jCheck_tctk.isSelected()) { jLabel4.setVisible(true); jComboBox2.setVisible(true); jBt_xn2.setVisible(true); } else { jLabel4.setVisible(false); jComboBox2.setVisible(false); jBt_xn2.setVisible(false); } } }); jCheck_gt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jCheck_gt.isSelected()) { if (jCheck_rt.isSelected()) { jCheck_rt.setSelected(false); } jLabel2.setVisible(true); jLabel3.setVisible(true); jTextField1.setVisible(true); jBt_xn1.setVisible(true); } else { jLabel2.setVisible(false); jLabel3.setVisible(false); jTextField1.setVisible(false); jBt_xn1.setVisible(false); } } }); jCheck_rt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jCheck_rt.isSelected()) { if (jCheck_gt.isSelected()) { jCheck_gt.setSelected(false); } jLabel2.setVisible(true); jLabel3.setVisible(true); jTextField1.setVisible(true); jBt_xn1.setVisible(true); } else { jLabel2.setVisible(false); jLabel3.setVisible(false); jTextField1.setVisible(false); jBt_xn1.setVisible(false); } } }); /*dont touch jcheckbox*/ }
From source file:org.apache.geode.internal.cache.Oplog.java
private boolean readKrf(OplogEntryIdSet deletedIds, boolean recoverValues, boolean recoverValuesSync, Set<Oplog> oplogsNeedingValueRecovery, boolean latestOplog) { File f = new File(this.diskFile.getPath() + KRF_FILE_EXT); if (!f.exists()) { return false; }//from ww w. j a va2 s.c om if (!getParent().getDiskInitFile().hasKrf(this.oplogId)) { logger.info(LocalizedMessage.create(LocalizedStrings.Oplog_REMOVING_INCOMPLETE_KRF, new Object[] { f.getName(), this.oplogId, getParent().getName() })); f.delete(); } // Set krfCreated to true since we have a krf. this.krfCreated.set(true); // Fix for 42741 - we do this after creating setting the krfCreated flag // so that we don't try to recreate the krf. if (recoverValuesSync) { return false; } FileInputStream fis; try { fis = new FileInputStream(f); } catch (FileNotFoundException ignore) { return false; } try { if (getParent().isOffline() && !getParent().FORCE_KRF_RECOVERY) { return false; } logger.info(LocalizedMessage.create(LocalizedStrings.DiskRegion_RECOVERING_OPLOG_0_1_2, new Object[] { toString(), f.getAbsolutePath(), getParent().getName() })); this.recoverNewEntryId = DiskStoreImpl.INVALID_ID; this.recoverModEntryId = DiskStoreImpl.INVALID_ID; this.recoverModEntryIdHWM = DiskStoreImpl.INVALID_ID; long oplogKeyIdHWM = DiskStoreImpl.INVALID_ID; int krfEntryCount = 0; DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 1024 * 1024)); final Version version = getProductVersionIfOld(); final ByteArrayDataInput in = new ByteArrayDataInput(); try { try { validateOpcode(dis, OPLOG_MAGIC_SEQ_ID); readOplogMagicSeqRecord(dis, f, OPLOG_TYPE.KRF); validateOpcode(dis, OPLOG_DISK_STORE_ID); readDiskStoreRecord(dis, f); } catch (DiskAccessException ignore) { // Failed to read the file. There are two possibilities. Either this // file is in old format which does not have a magic seq in the // beginning or this is not a valid file at all. Try reading it as a // file in old format fis.close(); fis = new FileInputStream(f); dis = new DataInputStream(new BufferedInputStream(fis, 1024 * 1024)); readDiskStoreRecord(dis, f); } catch (IllegalStateException ignore) { // Failed to read the file. There are two possibilities. Either this // is in new format which has a magic seq in the beginning or this is // not a valid file at all fis.close(); fis = new FileInputStream(f); dis = new DataInputStream(new BufferedInputStream(fis, 1024 * 1024)); readDiskStoreRecord(dis, f); } readGemfireVersionRecord(dis, f); readTotalCountRecord(dis, f); readRVVRecord(dis, f, false, latestOplog); long lastOffset = 0; byte[] keyBytes = DataSerializer.readByteArray(dis); while (keyBytes != null) { byte userBits = dis.readByte(); int valueLength = InternalDataSerializer.readArrayLength(dis); byte[] valueBytes = null; long drId = DiskInitFile.readDiskRegionID(dis); DiskRecoveryStore drs = getOplogSet().getCurrentlyRecovering(drId); // read version VersionTag tag = null; if (EntryBits.isWithVersions(userBits)) { tag = readVersionsFromOplog(dis); if (drs != null && !drs.getDiskRegionView().getFlags() .contains(DiskRegionFlag.IS_WITH_VERSIONING)) { // 50044 Remove version tag from entry if we don't want versioning // for this region tag = null; userBits = EntryBits.setWithVersions(userBits, false); } else { // Update the RVV with the new entry if (drs != null) { drs.recordRecoveredVersionTag(tag); } } } long oplogKeyId = InternalDataSerializer.readVLOld(dis); long oplogOffset; if (EntryBits.isAnyInvalid(userBits) || EntryBits.isTombstone(userBits)) { oplogOffset = -1; } else { oplogOffset = lastOffset + InternalDataSerializer.readVLOld(dis); lastOffset = oplogOffset; } if (oplogKeyId > oplogKeyIdHWM) { oplogKeyIdHWM = oplogKeyId; } if (okToSkipModifyRecord(deletedIds, drId, drs, oplogKeyId, true, tag).skip()) { if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY)) { logger.trace(LogMarker.PERSIST_RECOVERY, "readNewEntry skipping oplogKeyId=<{}> drId={} userBits={} oplogOffset={} valueLen={}", oplogKeyId, drId, userBits, oplogOffset, valueLength); } this.stats.incRecoveryRecordsSkipped(); incSkipped(); } else { if (EntryBits.isAnyInvalid(userBits)) { if (EntryBits.isInvalid(userBits)) { valueBytes = DiskEntry.INVALID_BYTES; } else { valueBytes = DiskEntry.LOCAL_INVALID_BYTES; } } else if (EntryBits.isTombstone(userBits)) { valueBytes = DiskEntry.TOMBSTONE_BYTES; } Object key = deserializeKey(keyBytes, version, in); { Object oldValue = getRecoveryMap().put(oplogKeyId, key); if (oldValue != null) { throw new AssertionError( LocalizedStrings.Oplog_DUPLICATE_CREATE.toLocalizedString(oplogKeyId)); } } DiskEntry de = drs.getDiskEntry(key); if (de == null) { if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY)) { logger.trace(LogMarker.PERSIST_RECOVERY, "readNewEntry oplogKeyId=<{}> drId={} userBits={} oplogOffset={} valueLen={}", oplogKeyId, drId, userBits, oplogOffset, valueLength); } DiskEntry.RecoveredEntry re = createRecoveredEntry(valueBytes, valueLength, userBits, getOplogId(), oplogOffset, oplogKeyId, false, version, in); if (tag != null) { re.setVersionTag(tag); } initRecoveredEntry(drs.getDiskRegionView(), drs.initializeRecoveredEntry(key, re)); drs.getDiskRegionView().incRecoveredEntryCount(); this.stats.incRecoveredEntryCreates(); krfEntryCount++; } else { DiskId curdid = de.getDiskId(); // assert curdid.getOplogId() != getOplogId(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY)) { logger.trace(LogMarker.PERSIST_RECOVERY, "ignore readNewEntry because getOplogId()={} != curdid.getOplogId()={} for drId={} key={}", getOplogId(), curdid.getOplogId(), drId, key); } } } keyBytes = DataSerializer.readByteArray(dis); } // while setRecoverNewEntryId(oplogKeyIdHWM); } catch (IOException ex) { try { fis.close(); fis = null; } catch (IOException ignore) { } throw new DiskAccessException("Unable to recover from krf file for oplogId=" + oplogId + ", file=" + f.getName() + ". This file is corrupt, but may be safely deleted.", ex, getParent()); } if (recoverValues && krfEntryCount > 0) { oplogsNeedingValueRecovery.add(this); // TODO optimize this code and make it async // It should also honor the lru limit // The fault in logic might not work until // the region is actually created. // Instead of reading the crf it might be better to iterate the live // entry // list that was built during KRF recovery. Just fault values in until // we // hit the LRU limit (if we have one). Only fault in values for entries // recovered from disk that are still in this oplog. // Defer faulting in values until all oplogs for the ds have been // recovered. } } finally { // fix for bug 42776 if (fis != null) { try { fis.close(); fis = null; } catch (IOException ignore) { } } } return true; }