-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSession.java
More file actions
1220 lines (1079 loc) · 29.1 KB
/
Copy pathSession.java
File metadata and controls
1220 lines (1079 loc) · 29.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.Arrays;
/**
* Abstract class for either server or client sessions.
* <p>
* This is threaded, so implementations can use {@link #start()} to start it in
* a new thread or run it normally by executing {@link #run()}.
*
* @author James Li
*/
abstract class Session extends Thread {
// About self
private boolean sessionActive;
private short sessionType;
// Options
private int timeout = Constants.defaultOperationTimeout;
private int maxAttempts = Constants.defaultMaxOperationAttempts;
private boolean sendExceptionMessage = false;
private boolean disableBlockAckMessages = false;
// Socket and packets
private DatagramSocket socket;
private int ownPort;
private IncomingPacket inPacket = null;
private OutgoingPacket outPacket = null;
// Delivery and addressing
private InetAddress deliveryAddress;
private int deliveryPort;
private String addrTIDPair = null;
// File stuff
private String filename;
private String fileMode;
private FileReader fileReader;
private FileWriter fileWriter;
private byte[] fileBuffer;
private int fileBufferSize;
// Block number
private BlockNumber blockNumber;
// Operation variables
private int packetSendRetryCount;
private int timeoutCount;
private boolean hasRespondedWithReadPrior = false;
// Properties and internal operation
/**
* Sets the delivery address.
*
* @param address
* `InetAddress`
* @return This object
*/
Session setDeliveryAddress(InetAddress address) {
this.deliveryAddress = address;
return this;
}
/**
* Sets the delivery port.
*
* @param port
* Port number
* @return This object
*/
Session setDeliveryPort(int port) {
this.deliveryPort = port;
return this;
}
/**
* Sets delivery information from the already stored incoming packet.
*
* @return This object
*/
Session setDeliveryInfo() {
// Obtain the sender IP and port for the session, reuse the originating
// port for replies
DatagramPacket datagramPacket = this.getInPacket().getDatagramPacket();
return this.setDeliveryAddress(datagramPacket.getAddress()).setDeliveryPort(datagramPacket.getPort());
}
/**
* Gets the delivery address.
*
* @return Delivery address
*/
InetAddress getDeliveryAddress() {
return this.deliveryAddress;
}
/**
* Gets the delivery port.
*
* @return Delivery port
*/
int getDeliveryPort() {
return this.deliveryPort;
}
/**
* Sets the Address-TID pair string.
* <p>
* Delivery information must be set prior.
*
* @return This object
*/
Session setAddrTID() {
// Simply "IP:Port" - used to prevent Addr-TID clashes
this.addrTIDPair = this.getDeliveryAddress().getHostAddress() + ":" + this.getDeliveryPort();
return this;
}
/**
* Gets the Address-TID pair string.
*
* @return Address-TID pair string
*/
String getAddrTID() {
return this.addrTIDPair;
}
/**
* Gets the packet send retry count.
*
* @return Packet send retry count
*/
private int getPacketSendRetryCount() {
return this.packetSendRetryCount;
}
/**
* Increments the timeout count.
*
* @return This object
*/
private Session incrPacketSendRetryCount() {
++this.packetSendRetryCount;
return this;
}
/**
* Resets the timeout count.
*
* @return This object
*/
private Session resetPacketSendRetryCount() {
this.packetSendRetryCount = 0;
return this;
}
/**
* Gets the timeout count.
*
* @return Timeout count
*/
private int getTimeoutCount() {
return this.timeoutCount;
}
/**
* Increments the timeout count.
*
* @return This object
*/
private Session incrTimeoutCount() {
++this.timeoutCount;
return this;
}
/**
* Resets the timeout count.
*
* @return This object
*/
private Session resetTimeoutCount() {
this.timeoutCount = 0;
return this;
}
/**
* Enables exception messages to be delivered with ERROR packets.
*
* @return This object
*/
Session enableExceptionMessageDelivery() {
this.sendExceptionMessage = true;
return this;
}
/**
* Sets timeout to specified value.
*
* @param timeout
* Timeout in milliseconds
* @return This object
*/
Session setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Sets maximum number of attempts of a single operation.
*
* @param maxAttempts
* Maximum number of attempts
* @return This object
*/
Session setMaxAttempts(int maxAttempts) {
this.maxAttempts = maxAttempts;
return this;
}
/**
* Disables printing of block ACK and DATA lines to STDOUT.
* <p>
* Other messages are not affected.
*
* @return This object
*/
Session disableBlockAckMessagePrinting() {
this.disableBlockAckMessages = true;
return this;
}
// Utils
/**
* Prints a message.
*
* @param error
* `true` to print to STDERR, otherwise STDOUT
* @param msg
* Message to print
* @return This object
*/
private Session print(boolean error, String msg) {
String outmsg = "[" + this.ownPort + "] " + msg;
if (error) {
// STDERR
System.err.println(outmsg);
} else {
// STDOUT
System.out.println(outmsg);
}
return this;
}
/**
* Prints a message to STDOUT.
*
* @param msg
* Message to print
* @return This object
*/
Session print(String msg) {
return this.print(false, msg);
}
// Sockets
/**
* Opens the session's socket.
*
* @return This object
* @throws Exception
*/
private Session openSocket() throws Exception {
// Receiver communicates with sender over new, random TID for remainder
// of session
// DatagramSocket will automatically attach to available ephemeral port
// on the machine
this.socket = new DatagramSocket();
this.socket.setSoTimeout(this.timeout); // Timeout
this.ownPort = this.socket.getLocalPort();
return this.print(String.format(Constants.strings.SOCKET_LOCAL_PORT_X_OPEN, this.ownPort));
}
/**
* Closes the session's socket.
*
* @return This object
*/
private Session closeSocket() {
this.socket.close();
return this.print(Constants.strings.SOCKET_CLOSED);
}
// Session
/**
* Sets session up for writing local files.
*
* @param isServer
* Indicates if the session instance is running on a server
* (otherwise, client)
* @param opcode
* Session type to be set
* @param localFile
* Local filename
* @return This object
* @throws IOException
*/
Session setupSessionForWritingToLocal(boolean isServer, short opcode, String localFile) throws Exception {
// Set the opcode, and initialise block number and file
this.setSessionType(opcode) //
.initBlockNumber() //
.setFilename(localFile) //
.createFile();
if (isServer) {
return this
.print("Client requested write to local file '" + localFile + "' with mode '" + this.getMode()
+ "'") //
.sendACK(Constants.strings.OUT_PACKET_INIT_ACK);
}
return this.print(
"Requested read from server to local file '" + localFile + "' with mode '" + this.getMode() + "'");
}
/**
* Sets session up for reading local files.
*
* @param isServer
* Indicates if the session instance is running on a server
* (otherwise, client)
* @param opcode
* Session type to be set
* @param localFile
* Local filename
* @return This object
* @throws Exception
*/
Session setupSessionForReadingFromLocal(boolean isServer, short opcode, String localFile) throws Exception {
// Set the opcode, and initialise block number and file
this.setSessionType(opcode) //
.initBlockNumber() //
.setFilename(localFile) //
.openFile();
if (isServer) {
// Immediately read and send data back to client
return this
.print("Client requested read from local file '" + localFile + "' with mode '" + this.getMode()
+ "'") //
.readAndReply(false);
}
return this.print(
"Requested write to server from local file '" + localFile + "' with mode '" + this.getMode() + "'");
}
/**
* Abstract method containing instance-specific session initialisation code,
* generally processing the request type and utilising the appropriate
* session set up method.
*
* @return This object
* @throws Exception
*/
abstract Session begin() throws Exception;
/**
* Cleans up session, ready for termination.
*
* @return This object
*/
private Session end() {
return this.closeFile() //
.closeSocket() //
.setSessionInactive() //
.print(Constants.strings.SESSION_ENDED);
}
/**
* Resets session internal variables.
*
* @return This object
*/
private Session reset() {
return this.setSessionInactive() //
.resetPacketSendRetryCount() //
.resetTimeoutCount() //
.setSessionType((short) 0) //
.setFilename(null) //
.nullFileBuffer();
}
/**
* Sets session active.
*
* @return This object
*/
private Session setSessionActive() {
this.sessionActive = true;
return this;
}
/**
* Sets session inactive.
*
* @return This object
*/
private Session setSessionInactive() {
this.sessionActive = false;
return this;
}
/**
* Returns if session is active or not.
*
* @return Session active state
*/
boolean isSessionActive() {
return this.sessionActive;
}
/**
* Sets the session type.
*
* @param sessionType
* Request opcode of the session type
* @return This object
*/
private Session setSessionType(short sessionType) {
this.sessionType = sessionType;
return this;
}
/**
* Gets the session type.
*
* @return Request opcode of the session type
*/
short getSessionType() {
return this.sessionType;
}
/**
* Checks if the transmission mode is supported.
*
* @param mode
* Mode string
* @return `true` if mode is supported; otherwise `false`
*/
private boolean isModeSupported(String mode) {
// Permit only netascii and octet
switch (mode.toLowerCase()) {
case Packet.modestr.NETASCII:
case Packet.modestr.OCTET:
return true;
}
return false;
}
/**
* Sets transmission mode of the session.
* <p>
* Throws exception when not supported.
*
* @param mode
* Mode string
* @return This object
* @throws Exception
*/
Session setMode(String mode) throws Exception {
// Convert to lowercase, and then check validity before saving
mode = mode.toLowerCase();
if (this.isModeSupported(mode)) {
this.fileMode = mode;
} else {
throw new Exception(String.format(Constants.strings.MODE_X_NOT_SUPPORTED, mode));
}
return this;
}
/**
* Gets the transmission mode.
*
* @return Mode string
*/
String getMode() {
return this.fileMode;
}
// Block number
/**
* Initialises the block number to a new instance.
*
* @return This object
*/
private Session initBlockNumber() {
this.blockNumber = new BlockNumber();
return this;
}
/**
* Increments the block number.
*
* @return This object
*/
private Session incrBlockNumber() {
this.blockNumber.incr();
return this;
}
// Packet sending and handling
/**
* Stores the incoming packet.
*
* @param packet
* Incoming packet
* @return This object
*/
Session setInPacket(IncomingPacket packet) {
this.inPacket = packet;
return this;
}
/**
* Gets the incoming packet.
*
* @return `IncomingPacket` instance
*/
IncomingPacket getInPacket() {
return this.inPacket;
}
/**
* Accepts the next incoming request and stores and processes the incoming
* packet to this session.
*
* @return This object
* @throws Exception
*/
private Session storeInPacket() throws Exception {
// Receives and processes the incoming packet, so that we can extract
// the info inside later
IncomingPacket newPacket = new IncomingPacket(this.socket).receive().process();
this.setInPacket(newPacket);
return this;
}
/**
* Abstract method for instance-specific packet processing code.
* <p>
* {@link #commonProcessInPacket(short requestTypeACK, short requestTypeDATA)}
* should be used at the end of this method.
*
* @return This object
* @throws Exception
*/
abstract Session processInPacket() throws Exception;
/**
* Common packet processing method across both client and server session
* instances.
* <p>
* Should be used at the end of the implemented {@link #processInPacket()}
* method.
*
* @param requestTypeACK
* The request type that this session instance expects for
* incoming ACK packets (e.g. RRQ for server)
* @param requestTypeDATA
* The request type that this session instance expects for
* incoming DATA packets (e.g. WRQ for server)
* @return This object
* @throws Exception
*/
Session commonProcessInPacket(short requestTypeACK, short requestTypeDATA) throws Exception {
// Need to check the opcode and see what to do next
switch (this.getInPacket().getOpcode()) {
case Packet.opcode.DATA:
if (this.getSessionType() != requestTypeDATA) {
throw new Exception(Constants.strings.CANNOT_ACCEPT_DATA_PACKETS);
}
return this.handleDATA();
case Packet.opcode.ACK:
if (this.getSessionType() != requestTypeACK) {
throw new Exception(Constants.strings.CANNOT_ACCEPT_ACK_PACKETS);
}
return this.handleACK();
case Packet.opcode.ERROR:
return this.handleERROR();
default:
throw new Exception(Constants.strings.PACKET_MALFORMED);
}
}
/**
* Creates and returns an `OutgoingPacket` object that is saved to this
* session with the current active socket and delivery address and port.
*
* @return An `OutgoingPacket` instance
*/
OutgoingPacket createOutPacket() {
return this.outPacket = new OutgoingPacket(this.socket, this.deliveryAddress, this.deliveryPort);
}
/**
* Gets the outgoing packet.
*
* @return `OutgoingPacket` instance
*/
private OutgoingPacket getOutPacket() {
return this.outPacket;
}
/**
* Sends a DATA packet with provided block number and data.
*
* @param blockNumber
* Block number to send
* @param data
* Data contents to send
* @return This object
* @throws Exception
*/
private Session sendDATA(BlockNumber blockNumber, byte[] data) throws Exception {
// Using int representation of block number because Java doesn't have
// unsigned shorts
if (!this.disableBlockAckMessages) {
this.print(String.format(Constants.strings.BLOCK_NUMBER_DATA_X_SIZE_X, blockNumber.intVal(), this.fileBufferSize));
}
this.createOutPacket() //
.addOpcode(Packet.opcode.DATA) //
.addBlockNumber(blockNumber) //
.addDataBytes(data) //
.send();
return this;
}
/**
* Sends a DATA packet with current block number and data in file buffer.
*
* @return This object
* @throws Exception
*/
private Session sendDATA() throws Exception {
return this.sendDATA(this.blockNumber, this.getFileBuffer());
}
/**
* Sends an ACK packet with the provided block number and print a message.
*
* @param blockNumber
* The block number to send with the ACK packet.
* @param message
* Message to print
* @return This object
* @throws Exception
*/
private Session sendACK(BlockNumber blockNumber, String message) throws Exception {
if (!this.disableBlockAckMessages) {
this.print(message);
}
this.createOutPacket() //
.addOpcode(Packet.opcode.ACK) //
.addBlockNumber(blockNumber) //
.send();
return this;
}
/**
* Sends an ACK packet with the provided block number.
*
* @param blockNumber
* The block number to send with the ACK packet.
* @return This object
* @throws Exception
*/
private Session sendACK(BlockNumber blockNumber) throws Exception {
// Using int representation of block number because Java doesn't have
// unsigned shorts
return this.sendACK(blockNumber, String.format(Constants.strings.BLOCK_NUMBER_ACK_X_SIZE_X, blockNumber.intVal(), this.fileBufferSize));
}
/**
* Sends an ACK packet with this object's current block number and print a
* message.
*
* @param message
* Message to print
* @return This object
* @throws Exception
*/
private Session sendACK(String message) throws Exception {
return this.sendACK(this.blockNumber, message);
}
/**
* Sends an ACK packet with this object's current block number.
*
* @return This object
* @throws Exception
*/
private Session sendACK() throws Exception {
return this.sendACK(this.blockNumber);
}
/**
* Resends the last outgoing packet.
*
* @return This object
* @throws Exception
*/
private Session resend() throws Exception {
// Just resends whatever was last stored as the outgoing packet
this.getOutPacket().send();
return this;
}
/**
* Method for handling ACK packets.
*
* @return This object
* @throws Exception
*/
private Session handleACK() throws Exception {
// If incoming block # = current block # - 1
// The recipient is calling for a resend, since the ACK is for the
// previous one
if (BlockNumber.isInSeq(this.getInPacket().getBlockNumber(), this.blockNumber)) {
return this.readAndReply(true);
}
// If the expected block number and the incoming one are not equal,
// they're out of order!
if (!BlockNumber.equals(this.blockNumber, this.getInPacket().getBlockNumber())) {
throw new Exception(Constants.strings.BLOCK_NUMBER_OUT_OF_ORDER);
}
// Incoming ACK means that this session is reading data and sending back
// DATA
return this.readAndReply(false);
}
/**
* Method for handling DATA packets.
*
* @return This object
* @throws Exception
*/
private Session handleDATA() throws Exception {
// If incoming block # = current block #
// The recipient resent the data again, but we don't need to write
// anything (since it has already been written) except for resending the
// ACK
if (BlockNumber.equals(this.blockNumber, this.getInPacket().getBlockNumber())) {
return this.writeAndReply(true);
}
// If the expected block number and the incoming one are not in
// sequence,
// they're out of order!
if (!BlockNumber.isInSeq(this.blockNumber, this.getInPacket().getBlockNumber())) {
throw new Exception(Constants.strings.BLOCK_NUMBER_OUT_OF_ORDER);
}
// Incoming DATA means that this session is writing data and sending
// back ACK
return this.writeAndReply(false);
}
/**
* Method for handling ERROR packets.
*
* @return This object
* @throws UnsupportedEncodingException
*/
private Session handleERROR() throws UnsupportedEncodingException {
// We don't raise an exception here, because an ERROR packet is part of
// normal behaviour
return this
.print("Sender error code " + this.getInPacket().getErrorCode() + "; '"
+ Utils.byteArrayToString(this.getInPacket().getContents()) + "'; terminating") //
.setSessionInactive();
}
// Handlers
/**
* Method to deal with timeouts.
*
* @return This object
* @throws Exception
*/
private Session handleTimeout() throws Exception {
// (Max attempts - 1) because we have (n-1) timeouts between n attempts
if (this.incrTimeoutCount().getTimeoutCount() > (this.maxAttempts - 1)) {
return this.setSessionInactive() //
.print(Constants.strings.MAX_ATTEMPTS_REACHED);
}
// Resend last outgoing packet
return this.print(Constants.strings.PACKET_TIMEOUT_RESEND).resend();
}
/**
* Basic exception handler that create the appropriate error packet, and
* optionally sends it to the sender.
* <p>
* To send the full exception message generated by Java, execute
* {@link #enableExceptionMessageDelivery()} on this object first.
*
* @param err
* Exception to handle
* @param send
* Indicates if the ERROR packet is to be sent immediately
*/
private void handleException(Exception err, boolean send) {
try {
// Get error information
short errcode = Packet.errcode.NOT_DEFINED; // No error code by
// default since most
// exceptions raised are
// not specific enough
String errmsg = err.getMessage();
String sentErrmsg = errmsg;
if (errmsg != null) {
// Support FILE EXISTS error
if (errmsg == Packet.errstr[Packet.errcode.FILE_EXISTS]) {
errcode = Packet.errcode.FILE_EXISTS;
}
}
// For security/privacy reasons, exception messages are sent only if
// explicitly enabled
if (!this.sendExceptionMessage || sentErrmsg == null) {
sentErrmsg = "";
}
// Construct error packet
this.print(true, errmsg) //
.createOutPacket() //
.addOpcode(Packet.opcode.ERROR) //
.addErrorCode(errcode) //
.addString(sentErrmsg) //
.addNullByte();
// Send only if told to
if (send) {
this.getOutPacket().send();
this.print(String.format(Constants.strings.PACKET_TYPE_X_SENT, "ERROR"));
}
} catch (Exception metaerr) {
// Give up trying to send an ERROR - since we have meta-errored
err.printStackTrace();
metaerr.printStackTrace();
}
}
/**
* Basic exception handler that sends the appropriate error packet back to
* the sender.
* <p>
* To send the full exception message generated by Java, execute
* {@link #enableExceptionMessageDelivery()} on this object first.
*
* @param err
* Exception to handle
*/
private void handleException(Exception err) {
this.handleException(err, true);
}
// Files
/**
* Sets local file in session.
*
* @param filename
* Local filename
* @return This object
*/
private Session setFilename(String filename) {
this.filename = filename;
return this;
}
/**
* Gets local file in session.
*
* @return Local filename
*/
private String getFilename() {
return this.filename;
}
/**
* Sets the file buffer with the input byte array.
*
* @param data
* Input byte array
* @return This object
*/
private Session setFileBuffer(byte[] data) {
this.fileBuffer = data;
// We set buffer size -1 in the null case because we can have 0 size
// buffers from edge cases (n % 512 = 0)
if (data == null) {
this.fileBufferSize = -1;
} else {
this.fileBufferSize = data.length;
}
return this;
}
/**
* Sets the file buffer with a copy of the input byte array, between indices
* [from, to).
*
* @param data
* Input byte array
* @param from
* Initial index, inclusive
* @param to
* Final index, exclusive
* @return This object
*/
private Session setFileBuffer(byte[] data, int from, int to) {
return this.setFileBuffer(Arrays.copyOfRange(data, from, to));
}
/**
* Gets the file buffer.
*
* @return Byte array of the file buffer
*/
private byte[] getFileBuffer() {
return this.fileBuffer;
}
/**
* Sets the contents of the file buffer to null.
*
* @return This object
*/
private Session nullFileBuffer() {
return this.setFileBuffer(null);
}
/**
* Opens a local file, ready for reading data from.
*
* @return This object
* @throws Exception
*/
private Session openFile() throws Exception {
this.fileReader = new FileReader(this.getMode(), this.getFilename());
return this;
}
/**
* Creates a local file, ready for writing data into.
* <p>
* Overwriting existing files will raise an exception.
*
* @return This object
* @throws FileNotFoundException
*/