List of usage examples for java.io DataInputStream readByte
public final byte readByte() throws IOException
readByte
method of DataInput
. From source file:com.isecpartners.gizmo.HttpResponse.java
public void processResponse(InputStream in) throws FailedRequestException { StringBuffer content = new StringBuffer(); DataInputStream inputStream = new DataInputStream(in); ArrayByteList blist = new ArrayByteList(); String header = null;/*from w w w.j a v a 2 s . co m*/ int contentLength = 0; boolean isChunked = false; String line; try { line = readline(inputStream); while (line != null && !line.equals(ENDL)) { content.append(line); if (line.toUpperCase().contains(CONTENT_LENGTH) && line.toUpperCase().indexOf(CONTENT_LENGTH) == 0) { String value = line.substring(line.indexOf(CONTENT_LENGTH) + CONTENT_LENGTH.length() + 2, line.indexOf('\r')); contentLength = Integer.parseInt(value.trim()); } else if (line.toUpperCase().contains(TRANSFER_ENCODING)) { if (line.toUpperCase() .substring( line.toUpperCase().indexOf(TRANSFER_ENCODING) + "Transfer-Encoding:".length()) .contains("CHUNKED")) { isChunked = true; } } else if (line.toUpperCase().contains(CONTENT_ENCODING)) { String value = line.substring(line.indexOf(CONTENT_ENCODING) + CONTENT_ENCODING.length() + 2, line.indexOf('\r')); value = value.trim(); if (value.toUpperCase().equals("GZIP")) { this.gzip = true; } else if (value.toUpperCase().equals("DEFLATE")) { this.deflate = true; } } line = readline(inputStream); } if (line == null) { GizmoView.log(content.toString()); throw new FailedRequestException(); } content.append("\r\n"); header = content.substring(0, content.indexOf("\r\n")); append(blist, content); if (contentLength != 0) { for (int ii = 0; ii < contentLength; ii++) { blist.add(inputStream.readByte()); } } if (isChunked) { boolean isDone = false; while (!isDone) { byte current = inputStream.readByte(); blist.add(current); int size = 0; while (current != '\n') { if (current != '\r') { size *= 16; if (Character.isLetter((char) current)) { current = (byte) Character.toLowerCase((char) current); } if ((current >= '0') && (current <= '9')) { size += (current - 48); } else if ((current >= 'a') && (current <= 'f')) { size += (10 + current - 97); } } current = inputStream.readByte(); while ((char) current == ' ') { current = inputStream.readByte(); } blist.add(current); } if (size != 0) { for (int ii = 0; ii < size; ii++) { int byte1 = inputStream.readByte(); byte blah = (byte) byte1; blist.add(blah); } blist.add(inputStream.readByte()); blist.add(inputStream.readByte()); } else { byte ch = (byte) inputStream.read(); StringBuffer endstuff = new StringBuffer(); blist.add(ch); endstuff.append((char) ch); while (ch != '\n') { ch = inputStream.readByte(); endstuff.append((char) ch); blist.add(ch); } isDone = true; } } } if (inputStream.available() > 0) { try { while (true) { blist.add(inputStream.readByte()); } } catch (EOFException e) { System.out.println(e); } } } catch (IOException ex) { Logger.getLogger(HttpResponse.class.getName()).log(Level.SEVERE, null, ex); } setBlist(blist); setHeader(header); if (this.gzip) { addContents(unzipData(blist.toArray())); } else if (this.deflate) { addContents(deflateData(blist.toArray())); } else { addContents(content.toString()); } }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * HandShake Constructor used by server side connection *//* w w w . ja v a 2 s. co m*/ public HandShake(Socket sock, int timeout, DistributedSystem sys, Version clientVersion, CommunicationMode communicationMode, SecurityService securityService) throws IOException, AuthenticationRequiredException { this.clientVersion = clientVersion; this.system = sys; this.securityService = securityService; { int soTimeout = -1; try { soTimeout = sock.getSoTimeout(); sock.setSoTimeout(timeout); InputStream is = sock.getInputStream(); int valRead = is.read(); // this.code = (byte)is.read(); if (valRead == -1) { throw new EOFException( LocalizedStrings.HandShake_HANDSHAKE_EOF_REACHED_BEFORE_CLIENT_CODE_COULD_BE_READ .toLocalizedString()); } this.code = (byte) valRead; if (this.code != REPLY_OK) { throw new IOException( LocalizedStrings.HandShake_HANDSHAKE_REPLY_CODE_IS_NOT_OK.toLocalizedString()); } try { DataInputStream dis = new DataInputStream(is); DataOutputStream dos = new DataOutputStream(sock.getOutputStream()); this.clientReadTimeout = dis.readInt(); if (clientVersion.compareTo(Version.CURRENT) < 0) { // versioned streams allow object serialization code to deal with older clients dis = new VersionedDataInputStream(dis, clientVersion); dos = new VersionedDataOutputStream(dos, clientVersion); } this.id = ClientProxyMembershipID.readCanonicalized(dis); // Note: credentials should always be the last piece in handshake for // Diffie-Hellman key exchange to work if (clientVersion.compareTo(Version.GFE_603) >= 0) { setOverrides(new byte[] { dis.readByte() }); } else { setClientConflation(dis.readByte()); } // Hitesh if (this.clientVersion.compareTo(Version.GFE_65) < 0 || communicationMode.isWAN()) { this.credentials = readCredentials(dis, dos, sys, this.securityService); } else { this.credentials = this.readCredential(dis, dos, sys); } } catch (IOException ioe) { this.code = -2; throw ioe; } catch (ClassNotFoundException cnfe) { this.code = -3; throw new IOException( LocalizedStrings.HandShake_CLIENTPROXYMEMBERSHIPID_CLASS_COULD_NOT_BE_FOUND_WHILE_DESERIALIZING_THE_OBJECT .toLocalizedString()); } } finally { if (soTimeout != -1) { try { sock.setSoTimeout(soTimeout); } catch (IOException ignore) { } } } } }
From source file:net.timewalker.ffmq4.storage.data.impl.AbstractBlockBasedDataStore.java
/** * Run an integrity check on the store files and fix them as necessary * @throws DataStoreException if the files could not be fixed *//*from w w w. j av a 2s .c o m*/ protected void integrityCheck() throws DataStoreException { try { //======================== // 1 - Check files sizes //======================== // -- Allocation table long atFileSize = allocationTableRandomAccessFile.length(); if (atFileSize < AT_HEADER_SIZE + AT_BLOCK_SIZE) /* Should have at least one entry */ throw new DataStoreException( "Allocation table is truncated : " + allocationTableFile.getAbsolutePath()); // Read some header fields FileInputStream inFile = new FileInputStream(allocationTableFile); DataInputStream in = new DataInputStream(new BufferedInputStream(inFile, 16384)); int blockCount = in.readInt(); int blockSize = in.readInt(); int firstBlock = in.readInt(); // Fix AT size long expectedATFileSize = AT_HEADER_SIZE + AT_BLOCK_SIZE * (long) blockCount; if (atFileSize != expectedATFileSize) { log.error("[" + descriptor.getName() + "] Allocation table has an invalid size (actual:" + atFileSize + ",expected:" + expectedATFileSize + "), fixing."); allocationTableRandomAccessFile.setLength(expectedATFileSize); } // Fix data size long dataFileSize = dataRandomAccessFile.length(); long expectedDataFileSize = (long) blockSize * blockCount; if (dataFileSize != expectedDataFileSize) { log.error("[" + descriptor.getName() + "] Data file has an invalid size (actual:" + dataFileSize + ",expected:" + expectedDataFileSize + "), fixing."); dataRandomAccessFile.setLength(expectedDataFileSize); } //============================ // 2 - Check allocation table //============================ // Read the AT into memory byte[] flags = new byte[blockCount]; int[] allocatedSize = new int[blockCount]; int[] previousBlock = new int[blockCount]; int[] nextBlock = new int[blockCount]; int blocksInUse = 0; int msgCount = 0; for (int n = 0; n < blockCount; n++) { flags[n] = in.readByte(); allocatedSize[n] = in.readInt(); previousBlock[n] = in.readInt(); nextBlock[n] = in.readInt(); if (allocatedSize[n] != -1) { blocksInUse++; if ((flags[n] & FLAG_START_BLOCK) > 0) msgCount++; } } in.close(); log.debug("[" + descriptor.getName() + "] Blocks in use before fix : " + blocksInUse); log.debug("[" + descriptor.getName() + "] Messages count before fix : " + msgCount); // Fix first block index boolean changed = false; if (firstBlock < -1 || firstBlock >= blockCount) { log.error("[" + descriptor.getName() + "] Invalid allocation table first block index (" + firstBlock + "), guessing new one ..."); firstBlock = guessFirstBlockIndex(blockCount, allocatedSize, nextBlock); log.debug("[" + descriptor.getName() + "] Guessed first block index : " + firstBlock); changed = true; } // Recover table if (msgCount == 0) { if (firstBlock == -1) { // Table is empty, cleanup dirty entries changed = changed || cleanupEmptyBlocks(blockCount, flags, allocatedSize, previousBlock, nextBlock); } else { log.error("[" + descriptor.getName() + "] First block index should be -1, clearing ..."); firstBlock = -1; changed = true; } } else { if (firstBlock == -1) { log.error("[" + descriptor.getName() + "] Invalid first block index, guessing value ..."); firstBlock = guessFirstBlockIndex(blockCount, allocatedSize, nextBlock); log.debug("[" + descriptor.getName() + "] Guessed first block index : " + firstBlock); changed = true; } changed = changed || fixBlocks(blockCount, blockSize, firstBlock, flags, allocatedSize, previousBlock, nextBlock); changed = changed || cleanupEmptyBlocks(blockCount, flags, allocatedSize, previousBlock, nextBlock); } // Update the allocation file table if (changed) { // Re-compute size msgCount = 0; blocksInUse = 0; for (int n = 0; n < blockCount; n++) { if (allocatedSize[n] != -1) { blocksInUse++; if ((flags[n] & FLAG_START_BLOCK) > 0) msgCount++; } } log.debug("[" + descriptor.getName() + "] Blocks in use after fix : " + blocksInUse); log.debug("[" + descriptor.getName() + "] Messages count after fix : " + msgCount); log.debug("[" + descriptor.getName() + "] Allocation table was altered, saving ..."); allocationTableRandomAccessFile.seek(AT_HEADER_FIRSTBLOCK_OFFSET); allocationTableRandomAccessFile.writeInt(firstBlock); for (int n = 0; n < blockCount; n++) { byte[] allocationBlock = new byte[AT_BLOCK_SIZE]; // Regroup I/O to improve performance allocationBlock[AB_FLAGS_OFFSET] = flags[n]; allocationBlock[AB_ALLOCSIZE_OFFSET] = (byte) ((allocatedSize[n] >>> 24) & 0xFF); allocationBlock[AB_ALLOCSIZE_OFFSET + 1] = (byte) ((allocatedSize[n] >>> 16) & 0xFF); allocationBlock[AB_ALLOCSIZE_OFFSET + 2] = (byte) ((allocatedSize[n] >>> 8) & 0xFF); allocationBlock[AB_ALLOCSIZE_OFFSET + 3] = (byte) ((allocatedSize[n] >>> 0) & 0xFF); allocationBlock[AB_PREVBLOCK_OFFSET] = (byte) ((previousBlock[n] >>> 24) & 0xFF); allocationBlock[AB_PREVBLOCK_OFFSET + 1] = (byte) ((previousBlock[n] >>> 16) & 0xFF); allocationBlock[AB_PREVBLOCK_OFFSET + 2] = (byte) ((previousBlock[n] >>> 8) & 0xFF); allocationBlock[AB_PREVBLOCK_OFFSET + 3] = (byte) ((previousBlock[n] >>> 0) & 0xFF); allocationBlock[AB_NEXTBLOCK_OFFSET] = (byte) ((nextBlock[n] >>> 24) & 0xFF); allocationBlock[AB_NEXTBLOCK_OFFSET + 1] = (byte) ((nextBlock[n] >>> 16) & 0xFF); allocationBlock[AB_NEXTBLOCK_OFFSET + 2] = (byte) ((nextBlock[n] >>> 8) & 0xFF); allocationBlock[AB_NEXTBLOCK_OFFSET + 3] = (byte) ((nextBlock[n] >>> 0) & 0xFF); allocationTableRandomAccessFile.seek(AT_HEADER_SIZE + n * AT_BLOCK_SIZE); allocationTableRandomAccessFile.write(allocationBlock); } allocationTableRandomAccessFile.getFD().sync(); } else log.debug("[" + descriptor.getName() + "] Allocation table was not altered"); } catch (IOException e) { throw new DataStoreException("Cannot check/fix store integrity : " + e); } }
From source file:VASSAL.tools.imports.adc2.MapBoard.java
/** * Read what order to draw the lines in. *//*from w w w . jav a2s . c o m*/ protected void readLineDrawPriorityBlock(DataInputStream in) throws IOException { ADC2Utils.readBlockHeader(in, "Line Draw Priority"); in.readByte(); // unused. // there can only be 10 line definitions. however drawning priorities for hex sides and hex lines // are completely independent for (int i = 1; i <= 10; ++i) { int index = in.readUnsignedByte(); if (index < lineDefinitions.length && lineDefinitions[index] != null) lineDefinitions[index].setHexLineDrawPriority(i); } for (int i = 1; i <= 10; ++i) { int index = in.readUnsignedByte(); if (index < lineDefinitions.length && lineDefinitions[index] != null) lineDefinitions[index].setHexSideDrawPriority(i); } }
From source file:VASSAL.tools.imports.adc2.MapBoard.java
/** * Crude version information. Comes near the end of the file! Actually it's just a flag to indicate whether * the version is < 2.08. In version 2.08, the hexes are abutted slightly differently. */// ww w . j a v a 2 s .c om protected void readVersionBlock(DataInputStream in) throws IOException { ADC2Utils.readBlockHeader(in, "File Format Version"); int version = in.readByte(); isPreV208 = version != 0; }
From source file:VASSAL.tools.imports.adc2.MapBoard.java
/** * The colour to fill before any elements are drawn. The fast-scroll flag is also read. *//* w ww. j a v a 2 s . co m*/ protected void readTableColorBlock(DataInputStream in) throws IOException { ADC2Utils.readBlockHeader(in, "Table Color"); /* int fastScrollFlag = */ in.readByte(); tableColor = ADC2Utils.getColorFromIndex(in.readUnsignedByte()); }
From source file:VASSAL.tools.imports.adc2.MapBoard.java
@Override public boolean isValidImportFile(File f) throws IOException { DataInputStream in = null; try {// ww w. j a v a 2 s. c om in = new DataInputStream(new FileInputStream(f)); boolean valid = in.readByte() == -3; in.close(); return valid; } finally { IOUtils.closeQuietly(in); } }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * Client-side handshake with a Server// ww w . j av a 2 s .com */ public ServerQueueStatus handshakeWithServer(Connection conn, ServerLocation location, CommunicationMode communicationMode) throws IOException, AuthenticationRequiredException, AuthenticationFailedException, ServerRefusedConnectionException { try { ServerQueueStatus serverQStatus = null; Socket sock = conn.getSocket(); DataOutputStream dos = new DataOutputStream(sock.getOutputStream()); final InputStream in = sock.getInputStream(); DataInputStream dis = new DataInputStream(in); DistributedMember member = getIDForSocket(sock); // if running in a loner system, use the new port number in the ID to // help differentiate from other clients DM dm = ((InternalDistributedSystem) this.system).getDistributionManager(); InternalDistributedMember idm = dm.getDistributionManagerId(); synchronized (idm) { if (idm.getPort() == 0 && dm instanceof LonerDistributionManager) { int port = sock.getLocalPort(); ((LonerDistributionManager) dm).updateLonerPort(port); updateProxyID(dm.getDistributionManagerId()); } } if (communicationMode.isWAN()) { this.credentials = getCredentials(member); } byte intermediateAcceptanceCode = write(dos, dis, communicationMode, REPLY_OK, this.clientReadTimeout, null, this.credentials, member, false); String authInit = this.system.getProperties().getProperty(SECURITY_CLIENT_AUTH_INIT); if (!communicationMode.isWAN() && intermediateAcceptanceCode != REPLY_AUTH_NOT_REQUIRED && (authInit != null && authInit.length() != 0)) { location.compareAndSetRequiresCredentials(true); } // Read the acceptance code byte acceptanceCode = dis.readByte(); if (acceptanceCode == (byte) 21 && !(sock instanceof SSLSocket)) { // This is likely the case of server setup with SSL and client not using // SSL throw new AuthenticationRequiredException( LocalizedStrings.HandShake_SERVER_EXPECTING_SSL_CONNECTION.toLocalizedString()); } if (acceptanceCode == REPLY_SERVER_IS_LOCATOR) { throw new GemFireConfigException("Improperly configured client detected. " + "Server at " + location + " is actually a locator. Use addPoolLocator to configure locators."); } // Successful handshake for GATEWAY_TO_GATEWAY mode sets the peer version in connection if (communicationMode.isWAN() && !(acceptanceCode == REPLY_EXCEPTION_AUTHENTICATION_REQUIRED || acceptanceCode == REPLY_EXCEPTION_AUTHENTICATION_FAILED)) { short wanSiteVersion = Version.readOrdinal(dis); conn.setWanSiteVersion(wanSiteVersion); // establish a versioned stream for the other site, if necessary if (wanSiteVersion < Version.CURRENT_ORDINAL) { dis = new VersionedDataInputStream(dis, Version.fromOrdinalOrCurrent(wanSiteVersion)); } } // No need to check for return value since DataInputStream already throws // EOFException in case of EOF byte epType = dis.readByte(); int qSize = dis.readInt(); // Read the server member member = readServerMember(dis); serverQStatus = new ServerQueueStatus(epType, qSize, member); // Read the message (if any) readMessage(dis, dos, acceptanceCode, member); // Read delta-propagation property value from server. // [sumedh] Static variable below? Client can connect to different // DSes with different values of this. It shoule be a member variable. if (!communicationMode.isWAN() && currentClientVersion.compareTo(Version.GFE_61) >= 0) { deltaEnabledOnServer = dis.readBoolean(); } // validate that the remote side has a different distributed system id. if (communicationMode.isWAN() && Version.GFE_66.compareTo(conn.getWanSiteVersion()) <= 0 && currentClientVersion.compareTo(Version.GFE_66) >= 0) { int remoteDistributedSystemId = in.read(); int localDistributedSystemId = ((InternalDistributedSystem) system).getDistributionManager() .getDistributedSystemId(); if (localDistributedSystemId >= 0 && localDistributedSystemId == remoteDistributedSystemId) { throw new GatewayConfigurationException( "Remote WAN site's distributed system id " + remoteDistributedSystemId + " matches this sites distributed system id " + localDistributedSystemId); } } // Read the PDX registry size from the remote size if (communicationMode.isWAN() && Version.GFE_80.compareTo(conn.getWanSiteVersion()) <= 0 && currentClientVersion.compareTo(Version.GFE_80) >= 0) { int remotePdxSize = dis.readInt(); serverQStatus.setPdxSize(remotePdxSize); } return serverQStatus; } catch (IOException ex) { CancelCriterion stopper = this.system.getCancelCriterion(); stopper.checkCancelInProgress(null); throw ex; } }
From source file:VASSAL.tools.imports.adc2.MapBoard.java
@Override protected void load(File f) throws IOException { super.load(f); DataInputStream in = null; try {/* w ww .j a v a 2 s . c o m*/ in = new DataInputStream(new BufferedInputStream(new FileInputStream(f))); baseName = stripExtension(f.getName()); path = f.getPath(); int header = in.readByte(); if (header != -3) throw new FileFormatException("Invalid Mapboard File Header"); // don't know what these do. in.readFully(new byte[2]); // get the symbol set String s = readWindowsFileName(in); String symbolSetFileName = forceExtension(s, "set"); set = new SymbolSet(); File setFile = action.getCaseInsensitiveFile(new File(symbolSetFileName), f, true, new ExtensionFileFilter(ADC2Utils.SET_DESCRIPTION, new String[] { ADC2Utils.SET_EXTENSION })); if (setFile == null) throw new FileNotFoundException("Unable to find symbol set file."); set.importFile(action, setFile); in.readByte(); // ignored columns = ADC2Utils.readBase250Word(in); rows = ADC2Utils.readBase250Word(in); // presumably, they're all the same size (and they're square) int hexSize = set.getMapBoardSymbolSize(); // each block read separately readHexDataBlock(in); readPlaceNameBlock(in); readHexSideBlock(in); readLineDefinitionBlock(in); readAttributeBlock(in); readMapSheetBlock(in); readHexLineBlock(in); readLineDrawPriorityBlock(in); // end of data blocks int orientation = in.read(); switch (orientation) { case 0: case 1: // vertical hex orientation or grid offset column if (set.getMapBoardSymbolShape() == SymbolSet.Shape.SQUARE) layout = new GridOffsetColumnLayout(hexSize, columns, rows); else layout = new VerticalHexLayout(hexSize, columns, rows); break; case 2: // horizontal hex orientation or grid offset row if (set.getMapBoardSymbolShape() == SymbolSet.Shape.SQUARE) layout = new GridOffsetRowLayout(hexSize, columns, rows); else layout = new HorizontalHexLayout(hexSize, columns, rows); break; default: // square grid -- no offset layout = new GridLayout(hexSize, columns, rows); } /* int saveMapPosition = */ in.readByte(); /* int mapViewingPosition = */ in.readShort(); // probably base-250 /* int mapViewingZoomLevel = */ in.readShort(); in.readByte(); // totally unknown // strangely, more blocks readTableColorBlock(in); readHexNumberingBlock(in); // TODO: default map item drawing order appears to be different for different maps. try { // optional blocks readMapBoardOverlaySymbolBlock(in); readVersionBlock(in); readMapItemDrawingOrderBlock(in); readMapItemDrawFlagBlock(in); } catch (ADC2Utils.NoMoreBlocksException e) { } in.close(); } finally { IOUtils.closeQuietly(in); } }
From source file:VASSAL.tools.imports.adc2.MapBoard.java
/** * Block of flags to indicate which elements are actually displayed. *//*from ww w . ja v a 2s . c om*/ protected void readMapItemDrawFlagBlock(DataInputStream in) throws IOException { ADC2Utils.readBlockHeader(in, "Map Item Draw Flag"); // obviously, element types can't be sorted before we do this. // TODO: check this! If they're turned off in the map, can they be turned on // again in the player? final ArrayList<MapLayer> elements = new ArrayList<MapLayer>(mapElements); if (in.readByte() == 0) mapElements.remove(elements.get(drawingPriorities[0])); if (in.readByte() == 0) mapElements.remove(elements.get(drawingPriorities[1])); if (in.readByte() == 0) mapElements.remove(elements.get(drawingPriorities[2])); if (in.readByte() == 0) mapElements.remove(elements.get(drawingPriorities[3])); if (in.readByte() == 0) mapElements.remove(elements.get(drawingPriorities[4])); if (in.readByte() == 0) mapElements.remove(elements.get(drawingPriorities[7])); if (in.readByte() == 0) mapElements.remove(elements.get(drawingPriorities[5])); }