下面列出了java.io.DataInputStream#reset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private SwapDeserializer createSwapDeserializer(final DataInputStream dis) throws IOException {
dis.mark(MAGIC_HEADER.length);
final byte[] magicHeader = new byte[MAGIC_HEADER.length];
try {
StreamUtils.fillBuffer(dis, magicHeader);
} catch (final EOFException eof) {
throw new IOException("Failed to read swap file because the file contained less than 4 bytes of data");
}
if (Arrays.equals(magicHeader, MAGIC_HEADER)) {
final String serializationName = dis.readUTF();
if (serializationName.equals(SchemaSwapDeserializer.getSerializationName())) {
return new SchemaSwapDeserializer();
}
throw new IOException("Cannot find a suitable Deserializer for swap file, written with Serialization Name '" + serializationName + "'");
} else {
// SimpleSwapDeserializer is old and did not write out a magic header.
dis.reset();
return new SimpleSwapDeserializer();
}
}
/**
* Read the header of fsedit log
* @param in fsedit stream
* @return the edit log version number
* @throws IOException if error occurs
*/
static int readLogVersion(DataInputStream in) throws IOException,
LogHeaderCorruptException {
int logVersion = 0;
// Read log file version. Could be missing.
in.mark(4);
// If edits log is greater than 2G, available method will return negative
// numbers, so we avoid having to call available
boolean available = true;
try {
logVersion = in.readByte();
} catch (EOFException e) {
available = false;
}
if (available) {
in.reset();
logVersion = in.readInt();
if (logVersion < FSConstants.LAYOUT_VERSION) { // future version
throw new LogHeaderCorruptException(
"Unexpected version of the file system log file: " + logVersion
+ ". Current version = " + FSConstants.LAYOUT_VERSION + ".");
}
}
return logVersion;
}
private SwapDeserializer createSwapDeserializer(final DataInputStream dis) throws IOException {
dis.mark(MAGIC_HEADER.length);
final byte[] magicHeader = new byte[MAGIC_HEADER.length];
try {
StreamUtils.fillBuffer(dis, magicHeader);
} catch (final EOFException eof) {
throw new IOException("Failed to read swap file because the file contained less than 4 bytes of data");
}
if (Arrays.equals(magicHeader, MAGIC_HEADER)) {
final String serializationName = dis.readUTF();
if (serializationName.equals(SchemaSwapDeserializer.getSerializationName())) {
return new SchemaSwapDeserializer();
}
throw new IOException("Cannot find a suitable Deserializer for swap file, written with Serialization Name '" + serializationName + "'");
} else {
// SimpleSwapDeserializer is old and did not write out a magic header.
dis.reset();
return new SimpleSwapDeserializer();
}
}
@Override
public MessageStoreSerializer newInstance(final DataInputStream data) throws IOException
{
// All encodings should start 0x00 << int length of the version string>> << version string in UTF-8 >>
data.mark(50);
if (data.read() != 0)
{
throw new IllegalArgumentException("Invalid format for upload");
}
int stringLength = data.readInt();
byte[] stringBytes = new byte[stringLength];
data.readFully(stringBytes);
String version = new String(stringBytes, StandardCharsets.UTF_8);
data.reset();
Map<String, MessageStoreSerializer> serializerMap =
new QpidServiceLoader().getInstancesByType(MessageStoreSerializer.class);
MessageStoreSerializer serializer = serializerMap.get(version);
if(serializer == null)
{
throw new IllegalArgumentException("Message store import uses version '"
+ version + "' which is not supported");
}
else
{
return serializer;
}
}
public static CompressionType detectType(InputStream is) throws IOException{
DataInputStream in = new DataInputStream(is);
if(in.markSupported())
in.mark(256);
byte firstByte = in.readByte();
CompressionType type;
switch(firstByte){
case -1:
throw new EOFException();
case 0x0a: //NBT Compund tag identifier
type = CompressionType.NONE;
break;
case 0x1F: //GZip magic number
type = CompressionType.GZIP;
break;
case 0x78: //ZLib header
type = CompressionType.ZLIB;
break;
default:
throw new InvalidParameterException("Could not auto detect the compression format.");
}
if(in.markSupported())
in.reset();
return type;
}
public void restoreContent(DataInputStream din, TableBackupInfo table, boolean pass) throws Exception {
din.readUTF();
Supplier<Object[]> rowReader = ()-> {
try {
din.mark(4);
if (din.readInt() == 0) {
return null;
}
din.reset();
Object[] row = new Object[table.columns.length];
for (int i=0; i<table.columns.length; i++) {
row[i] = readValue(din);
}
return row;
}
catch (Exception x) {
throw new RuntimeException(x);
}
};
if (pass) {
skipContent(table, rowReader);
}
else {
long count = restoreContent(table, rowReader);
println(" " + count + " rows");
}
}
protected Map<String, Integer> readFileHeader(DataInputStream ds) throws Exception {
Map<String, Integer> header = new HashMap<>();
long magicNumber = 0;
try {
// reset the position
ds.reset();
// magic number
magicNumber = ds.readInt() & UINT;
if (magicNumber != MAGIC_NUMBER && magicNumber != LE_MAGIC_NUMBER) {
throw new Exception("Invalid magic number");
}
// little endian?
isLittleEndian = (magicNumber == LE_MAGIC_NUMBER);
// revision
header.put("revision", swapInteger(ds.readInt()));
// string count
header.put("stringCount", swapInteger(ds.readInt()));
// original string offset
header.put("originalStringOffset", swapInteger(ds.readInt()));
// translation string offset
header.put("translationStringOffset", swapInteger(ds.readInt()));
// hash table size
header.put("hashTableSize", swapInteger(ds.readInt()));
// hash table offset
header.put("hashTableOffset", swapInteger(ds.readInt()));
} catch(Exception e) {
throw e;
}
return header;
}
/**
* Reads a MIDI track chunk
*
* @param DataInputStream
* dis - the input stream to read from
* @exception IOException
*/
private void readTrackChunk(DataInputStream dis) throws IOException {
// local variables for Track class
Track track = new Track();
// Insert new Track into a list of tracks
this.trackList.addElement(track);
int deltaTime = 0;
// Read track header
if (dis.readInt() != 0x4D54726B) {// If MTrk read is wrong
throw new IOException("Track started in wrong place!!!! ABORTING");
} else {// If MTrk read ok get bytesRemaining
dis.readInt();
}
// loop variables
int status, oldStatus = 0, eventLength = 0;
// Start gathering event data
Event event = null;
while (true) {
try {
// get variable length timestamp
deltaTime = MidiUtil.readVarLength(dis);
// mark stream so we can return if we need running status
dis.mark(2);
status = dis.readUnsignedByte();
// decide on running status
if (status < 0x80) { // set running status
status = oldStatus;
// return stream to before status read
dis.reset();
}
// create default event of correct type
if (status >= 0xFF) { // Meta Event
int type = dis.readUnsignedByte();
eventLength = MidiUtil.readVarLength(dis);
event = jm.midi.MidiUtil.createMetaEvent(type);
} else if (status >= 0xF0) { // System Exclusive --- NOT
// SUPPORTED
eventLength = MidiUtil.readVarLength(dis);
} else if (status >= 0x80) { // MIDI voice event
short selection = (short) (status / 0x10);
short midiChannel = (short) (status - (selection * 0x10));
VoiceEvt evt = (VoiceEvt) MidiUtil.createVoiceEvent(selection);
if (evt == null) {
throw new IOException("MIDI file read error: invalid voice event type!");
}
evt.setMidiChannel(midiChannel);
event = evt;
}
oldStatus = status;
} catch (EOFException ex) {
logger.warn("EOFException (" + ex.getMessage() + ") encountered in SMFTools");
} catch (Exception e) {
throw new IllegalStateException(e);
}
if (event != null) {
// read data into the new event and
// add the new event to the Track object
event.setTime(deltaTime);
event.read(dis);
track.addEvent(event);
// event.print();
if (event instanceof EndTrack)
break;
} else {
// skip the stream ahead to next valid event
dis.skipBytes(eventLength);
}
}
}
/**
* Called from the JavaSound MIDI Input Port for each new MIDI event
*/
public void send(MidiMessage message, long deltaTime){
System.out.println("New MIDI message");
Event event = null;
ByteArrayInputStream bais=new ByteArrayInputStream(message.getMessage());
DataInputStream dis = new DataInputStream(bais);
try{
dis.mark(2);
int status = dis.readUnsignedByte();
int length = 0;
//check running status
if(status < 0x80){
status = oldStatus;
dis.reset();
}
if(status >= 0xFF){//MetaEvent
int type = dis.readUnsignedByte();
length = MidiUtil.readVarLength(dis);
event = MidiUtil.createMetaEvent(type);
}else if(status >= 0xF0){ //System Exclusive -- Not Supported
System.out.println("SysEX---");
length = MidiUtil.readVarLength(dis);
}else if(status >= 0x80){ //MIDI voice event
short selection = (short) (status /0x10);
short midiChannel = (short) (status - (selection * 0x10));
VoiceEvt evt = (VoiceEvt)MidiUtil.createVoiceEvent(selection);
evt.setMidiChannel(midiChannel);
event = evt;
if(event == null){
throw new IOException("Read Error");
}
}
if(event != null){
event.setTime((int)deltaTime);
event.read(dis);
}
oldStatus = status;
}catch(Exception e){
e.printStackTrace();
System.exit(1);
}
this.notifyListeners(event);
}
/**
* Reads a MIDI track chunk
* @param DataInputStream dis - the input stream to read from
* @exception IOException
*/
private void readTrackChunk(DataInputStream dis)
throws IOException{
//local variables for Track class
Track track = new Track();
//Insert new Track into a list of tracks
this.trackList.addElement(track);
int deltaTime = 0;
if(VERBOSE) System.out.println("Reading Track ..........");
//Read track header
if(dis.readInt() != 0x4D54726B){//If MTrk read is wrong
throw new IOException
("Track started in wrong place!!!! ABORTING");
}else{//If MTrk read ok get bytesRemaining
dis.readInt();
}
//loop variables
int status, oldStatus =0, eventLength = 0;
//Start gathering event data
Event event = null;
while(true){
try{
//get variable length timestamp
deltaTime = MidiUtil.readVarLength(dis);
//mark stream so we can return if we need running status
dis.mark(2);
status = dis.readUnsignedByte();
//decide on running status
if(status < 0x80){ //set running status
status = oldStatus;
//return stream to before status read
dis.reset();
}
//create default event of correct type
if(status >= 0xFF){ //Meta Event
int type = dis.readUnsignedByte();
eventLength = MidiUtil.readVarLength(dis);
event = MidiUtil.createMetaEvent(type);
}else if(status >= 0xF0){ //System Exclusive --- NOT SUPPORTED
System.out.println("SysEX---");
eventLength = MidiUtil.readVarLength( dis);
}else if(status >= 0x80){ //MIDI voice event
short selection = (short) (status / 0x10);
short midiChannel = (short) (status - (selection * 0x10));
VoiceEvt evt = (VoiceEvt)MidiUtil.createVoiceEvent(selection);
evt.setMidiChannel(midiChannel);
event = evt;
if(event == null){
throw new IOException("MIDI file read error: invalid voice event type!");
}
}
oldStatus = status;
}catch(Exception e){
e.printStackTrace();
System.exit(1);
}
if(event != null){
//read data into the new event and
//add the new event to the Track object
event.setTime(deltaTime);
event.read(dis);
//if (VERBOSE) event.print();
track.addEvent(event);
//event.print();
if(event instanceof EndTrack)
break;
}else{
//skip the stream ahead to next valid event
dis.skipBytes(eventLength);
}
}
}
private void connectSerial() throws Exception {
logger.debug("Initializing serial port {}", serialPortName);
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
serialPort = (SerialPort) commPort;
try {
serialPort.setSerialPortParams(4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.enableReceiveThreshold(1);
serialPort.disableReceiveTimeout();
} catch (UnsupportedCommOperationException unimportant) {
// We might have a perfectly usable PTY even if above operations are unsupported
}
;
inStream = new DataInputStream(serialPort.getInputStream());
outStream = serialPort.getOutputStream();
outStream.flush();
if (inStream.markSupported()) {
inStream.reset();
}
logger.debug("Starting DataListener for {}", PrimareSerialConnector.this.toString());
dataListener = new DataListener();
dataListener.start();
logger.debug("Starting DataListener for {}", PrimareSerialConnector.this.toString());
sendInitMessages();
} catch (NoSuchPortException e) {
logger.error("No such port: {}", serialPortName);
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
if (portList.hasMoreElements()) {
StringBuilder sb = new StringBuilder();
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
sb.append(String.format("%s ", portId.getName()));
}
logger.error("The following communications ports are available: {}", sb.toString().trim());
} else {
logger.error("There are no communications ports available");
}
logger.error("You may consider OpenHAB startup parameter [ -Dgnu.io.rxtx.SerialPorts={} ]", serialPortName);
throw e;
}
}
/**
* Check an fsimage datainputstream's version number.
*
* The datainput stream is returned at the same point as it was passed in;
* this method has no effect on the datainputstream's read pointer.
*
* @param in Datainputstream of fsimage
* @return Filesystem layout version of fsimage represented by stream
* @throws IOException If problem reading from in
*/
private int findImageVersion(DataInputStream in) throws IOException {
in.mark(42); // arbitrary amount, resetting immediately
int version = in.readInt();
in.reset();
return version;
}
/**
* Check an fsimage datainputstream's version number.
*
* The datainput stream is returned at the same point as it was passed in;
* this method has no effect on the datainputstream's read pointer.
*
* @param in Datainputstream of fsimage
* @return Filesystem layout version of fsimage represented by stream
* @throws IOException If problem reading from in
*/
private int findImageVersion(DataInputStream in) throws IOException {
in.mark(42); // arbitrary amount, resetting immediately
int version = in.readInt();
in.reset();
return version;
}
/**
* Check an fsimage datainputstream's version number.
*
* The datainput stream is returned at the same point as it was passed in;
* this method has no effect on the datainputstream's read pointer.
*
* @param in Datainputstream of fsimage
* @return Filesystem layout version of fsimage represented by stream
* @throws IOException If problem reading from in
*/
private int findImageVersion(DataInputStream in) throws IOException {
in.mark(42); // arbitrary amount, resetting immediately
int version = in.readInt();
in.reset();
return version;
}