playgrnd
@ HEAD
playgrnd / NIO / NIOUtils.java
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 |
/* * NIOUtils.java Sep 3, 2008 * * Copyright 2007 Kobie Marketing, Inc. All rights reserved. */ package com.kobie.alchemy.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.ParameterizedType; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import org.apache.log4j.Logger; /** * TODO class description * * @author Vlad Orzhekhovskiy */ public class NIOUtils { /** * This method is a wrapper around * {@link FileChannel#map(MapMode, long, long)} method because of the Sun's * bug# <code>6417205</code> leading to {@link OutOfMemoryError} problem. * * @param chin channel to map. * @param position position in the channel. * @param size number of bytes to read. * @return a byte buffer mapped to the channel. */ public static MappedByteBuffer mapChannel(FileChannel chin, long position, int size) throws IllegalStateException { // workaround for Sun's bug# 6417205 MappedByteBuffer buffer = null; try { buffer = chin.map(MapMode.READ_ONLY, position, size); } catch (IOException e) { System.gc(); System.runFinalization(); try { buffer = chin.map(MapMode.READ_ONLY, position, size); } catch (IOException e1) { throw new IllegalStateException(e1); } } return buffer; } /** * Collection of readers. * * @author Vlad Orzhekhovskiy */ public static class ReaderArray { private final int MAX_BYTES_TO_READ = 1024 * 1024; private final Logger log = Logger.getLogger(getClass()); private List<DataListener> listeners = new ArrayList<DataListener>(); private List<DataReader<?>> readers = new ArrayList<DataReader<?>>(); private Map<String, Integer> idxMap = new HashMap<String, Integer>(); private List<String> names = new ArrayList<String>(); private Object[] values = new Object[0]; public void addField(DataReader<?> reader) { addField(Integer.toString(readers.size()), reader); } public void addField(String name, DataReader<?> reader) { names.add(name); idxMap.put(name, readers.size()); readers.add(reader); ensureCapacity(); } public void addDataListener(DataListener listener) { listeners.add(listener); } public int getFieldCount() { return readers.size(); } public DataReader<?> getReader(int index) { return readers.get(index); } public String getName(int index) { return names.get(index); } public Object[] readRecord(ByteBuffer buffer) { for (int i = 0; i < readers.size(); i++) { DataReader<?> reader = readers.get(i); Object value = reader.read(buffer); values[i] = value; } return values; } public Object[] getValues() { return values; } public Object getValue(int index) { return values[index]; } public Object getValue(String name) { int index = idxMap.get(name); return values[index]; } public int getRecordSize() { int size = 0; for (DataReader<?> reader : readers) size += reader.getSize(); return size; } public void processFile(File file) throws IOException { processFile(file, 0); } public void processFile(File file, int limit) throws IOException { FileInputStream fis = new FileInputStream(file); FileChannel chin = fis.getChannel(); processFile(chin, limit); chin.close(); fis.close(); } public void processFile(FileChannel chin) throws IOException { processFile(chin, 0); } public void processFile(FileChannel chin, int limit) throws IOException { int recordSize = getRecordSize(); int recordsPerChunk = MAX_BYTES_TO_READ / recordSize; int chunkSize = recordSize * recordsPerChunk; long position = chin.position(); long channelSize = chin.size(); for (DataListener listener : listeners) listener.processingStarted(); int recordCount = 0; while (position < channelSize) { int size = (int) Math.min(chunkSize, channelSize - position); MappedByteBuffer buffer = NIOUtils.mapChannel(chin, position, size); if (log.isTraceEnabled()) log.trace("Reading data chunk at offset " + position + "... "); int records = size / recordSize; for (int i = 0; i < records; i++) { Object[] values = readRecord(buffer); for (DataListener listener : listeners) listener.recordRetrieved(values, recordCount); if (log.isTraceEnabled()) log.trace("Record # " + recordCount + " processed"); recordCount++; if (limit > 0 && recordCount >= limit) break; } if (limit > 0 && recordCount >= limit) break; position += size; } for (DataListener listener : listeners) listener.processingComplete(recordCount); } public void dumpRecord() { dumpRecord(System.out); } public void dumpRecord(PrintStream out) { for (String name : names) { Object value = getValue(name); String format = getFormat(value); out.printf("%s: " + format + "\n", name, value); } } private void ensureCapacity() { if (readers.size() != values.length) values = new Object[readers.size()]; } private static String getFormat(Object value) { if (value == null) return "%s"; else if (value instanceof Date) return "%tF"; else if (value instanceof Float || value instanceof Double || value instanceof BigDecimal) return "%,f"; else if (value instanceof Number) return "%,d"; else return "%s"; } } /** * Data listener. * * @author Vlad Orzhekhovskiy */ public static interface DataListener { public void processingStarted(); public void recordRetrieved(Object[] values, int recordCount); public void processingComplete(int recordCount); } /** * Abstract implementation of {@link DataListener}. * * @author Vlad Orzhekhovskiy */ public static abstract class DataAdapter implements DataListener { public void processingComplete(int recordCount) { } public void processingStarted() { } public void recordRetrieved(Object[] values, int recordCount) { } } /** * Reads data from byte buffer and converts the values to specified type. * * @author Vlad Orzhekhovskiy */ public static interface DataReader<T> { public int getSize(); public T read(ByteBuffer buffer); } /** * Abstract reader. Subclasses must implement {@link #convert(byte[])} method. * * @author Vlad Orzhekhovskiy */ public static abstract class AbstractDataReader<T> implements DataReader<T> { private final int size; protected AbstractDataReader(int size) { this.size = size; } public int getSize() { return size; } public abstract T read(ByteBuffer buffer); } /** * Filler class. Reads the specified number of bytes, always returns * <code>null</code>. * * @author Vlad Orzhekhovskiy */ public static class Filler extends AbstractDataReader<Object> { private final byte[] filler; public Filler(int size) { super(size); filler = new byte[size]; } @Override public Object read(ByteBuffer buffer) { buffer.get(filler); return null; } } /** * Abstract reader based on converting the read data into string, and then - * to the real data value. * * @author Vlad Orzhekhovskiy */ public static abstract class AsciiReader<T> extends AbstractDataReader<T> { private final ThreadLocal<byte[]> tl; protected AsciiReader(int size) { super(size); this.tl = new ThreadLocal<byte[]>(); } public T read(ByteBuffer buffer) { byte[] data = internalByteArray(); buffer.get(data); String str = new String(data); if (str == null) return null; str = str.trim(); if (str.length() == 0 || str.startsWith("NULL")) return null; return convert(str); } private byte[] internalByteArray() { byte[] data = tl.get(); if (data == null) { data = new byte[getSize()]; tl.set(data); } return data; } protected abstract T convert(String str); } /** * Reads numeric binary values. * * @author Vlad Orzhekhovskiy */ public abstract static class BinaryReader<T> extends AbstractDataReader<T> { private final ByteOrder byteOrder; public BinaryReader(int size) { this(size, null); } public BinaryReader(int size, ByteOrder byteOrder) { super(size); this.byteOrder = byteOrder; } @Override public T read(ByteBuffer buffer) { if (byteOrder != null) { ByteOrder bo = buffer.order(); buffer.order(byteOrder); T value = fromBuffer(buffer); buffer.order(bo); return value; } else return fromBuffer(buffer); } protected abstract T fromBuffer(ByteBuffer buffer); } /** * Reads literal values. * * @author Vlad Orzhekhovskiy */ public static class TextReader extends AsciiReader<String> { private final boolean intern; public TextReader(int size) { this(size, false); } public TextReader(int size, boolean intern) { super(size); this.intern = intern; } @Override protected String convert(String str) { return intern ? str.intern() : str; } } /** * Reads single characters. * * @author Vlad Orzhekhovskiy */ public static class CharReader extends AbstractDataReader<Character> { public CharReader() { super(1); } @Override public Character read(ByteBuffer buffer) { return (char) buffer.get(); } } /** * Reads integer values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class IntReader extends AsciiReader<Integer> { private final DecimalFormat fmt; public IntReader(int size) { super(size); this.fmt = null; } public IntReader(String format) { super(format.length()); fmt = new DecimalFormat(format); } @Override protected Integer convert(String str) { try { return fmt != null ? fmt.parse(str).intValue() : Integer .valueOf(Integer.parseInt(str)); } catch (Exception e) { throw new RuntimeException("Invalid integer: " + str); } } } /** * Reads 32-bit binary integer values. * * @author Vlad Orzhekhovskiy */ public static class BinaryIntReader extends BinaryReader<Integer> { public BinaryIntReader() { this(null); } public BinaryIntReader(ByteOrder byteOrder) { super(Integer.SIZE / 8, byteOrder); } @Override protected Integer fromBuffer(ByteBuffer buffer) { return buffer.getInt(); } } /** * Reads short values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class ShortReader extends AsciiReader<Short> { public ShortReader(int size) { super(size); } @Override protected Short convert(String str) { return Short.valueOf(Short.parseShort(str)); } } /** * Reads 16-bit binary short values. * * @author Vlad Orzhekhovskiy */ public static class BinaryShortReader extends BinaryReader<Short> { public BinaryShortReader() { this(null); } public BinaryShortReader(ByteOrder byteOrder) { super(Short.SIZE / 8, byteOrder); } @Override protected Short fromBuffer(ByteBuffer buffer) { return buffer.getShort(); } } /** * Reads long values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class LongReader extends AsciiReader<Long> { public LongReader(int size) { super(size); } @Override protected Long convert(String str) { return Long.valueOf(Long.parseLong(str)); } } /** * Reads 64-bit binary long values. * * @author Vlad Orzhekhovskiy */ public static class BinaryLongReader extends BinaryReader<Long> { public BinaryLongReader() { this(null); } public BinaryLongReader(ByteOrder byteOrder) { super(Long.SIZE / 8, byteOrder); } @Override protected Long fromBuffer(ByteBuffer buffer) { return buffer.getLong(); } } /** * Reads byte values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class ByteReader extends AsciiReader<Byte> { public ByteReader(int size) { super(size); } @Override protected Byte convert(String str) { return Byte.valueOf(Byte.parseByte(str)); } } /** * Reads 1-byte values. * * @author Vlad Orzhekhovskiy */ public static class BinaryByteReader extends BinaryReader<Byte> { public BinaryByteReader() { this(null); } public BinaryByteReader(ByteOrder byteOrder) { super(Byte.SIZE / 8, byteOrder); } @Override protected Byte fromBuffer(ByteBuffer buffer) { return buffer.get(); } } /** * Reads float values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class FloatReader extends AsciiReader<Float> { public FloatReader(int size) { super(size); } @Override protected Float convert(String str) { return Float.valueOf(str); } } /** * Reads 32-bit binary float values. * * @author Vlad Orzhekhovskiy */ public static class BinaryFloatReader extends BinaryReader<Float> { public BinaryFloatReader() { this(null); } public BinaryFloatReader(ByteOrder byteOrder) { super(Float.SIZE / 8, byteOrder); } @Override protected Float fromBuffer(ByteBuffer buffer) { return buffer.getFloat(); } } /** * Reads double values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class DoubleReader extends AsciiReader<Double> { public DoubleReader(int size) { super(size); } @Override protected Double convert(String str) { return Double.valueOf(str); } } /** * Reads 64-bit binary double values. * * @author Vlad Orzhekhovskiy */ public static class BinaryDoubleReader extends BinaryReader<Double> { public BinaryDoubleReader() { this(null); } public BinaryDoubleReader(ByteOrder byteOrder) { super(Double.SIZE / 8, byteOrder); } @Override protected Double fromBuffer(ByteBuffer buffer) { return buffer.getDouble(); } } /** * Reads decimal values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class DecimalReader extends AsciiReader<BigDecimal> { private final DecimalFormat fmt; public DecimalReader(int size) { super(size); this.fmt = null; } public DecimalReader(String format) { super(format.length()); this.fmt = new DecimalFormat(format); this.fmt.setParseBigDecimal(true); } @Override protected BigDecimal convert(String str) { try { return fmt != null ? (BigDecimal) fmt.parse(str) : new BigDecimal(str); } catch (Exception e) { throw new RuntimeException("Invalid decimal: " + str); } } } /** * Reads big integer values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class BigIntReader extends AsciiReader<BigInteger> { public BigIntReader(int size) { super(size); } @Override protected BigInteger convert(String str) { return new BigInteger(str); } } /** * Reads date values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class DateReader extends AsciiReader<Date> { private final DateFormat df; public DateReader(String format) { this(format.length(), new SimpleDateFormat(format)); } public DateReader(int size, DateFormat df) { super(size); this.df = df; } @Override protected Date convert(String str) { try { Date date = df.parse(str); return date.getTime() > 0 ? date : null; } catch (ParseException e) { throw new RuntimeException("Invalid date: " + str); } } } /** * Reads enumerated values in ASCII format. * * @author Vlad Orzhekhovskiy */ public static class EnumReader<T extends Enum<T>> extends AsciiReader<T> { private final Class<T> enumType; @SuppressWarnings("unchecked") public EnumReader(int size) { super(size); ParameterizedType type = (ParameterizedType) getClass() .getGenericSuperclass(); this.enumType = (Class<T>) type.getActualTypeArguments()[0]; } @Override protected T convert(String str) { return Enum.valueOf(enumType, str); } } } |
Commits for playgrnd/NIO/NIOUtils.java
Revision | Author | Commited | Message |
---|---|---|---|
6 | snark | Tue 24 Jul, 2012 01:06:32 +0000 | initial checkin |