001package net.tnemc.plugincore.core.channel; 002/* 003 * The New Plugin Core 004 * Copyright (C) 2022 - 2024 Daniel "creatorfromhell" Vidmar 005 * 006 * This program is free software: you can redistribute it and/or modify 007 * it under the terms of the GNU Affero General Public License as published by 008 * the Free Software Foundation, either version 3 of the License, or 009 * (at your option) any later version. 010 * 011 * This program is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014 * GNU Affero General Public License for more details. 015 * 016 * You should have received a copy of the GNU Affero General Public License 017 * along with this program. If not, see <http://www.gnu.org/licenses/>. 018 */ 019 020import java.io.ByteArrayInputStream; 021import java.io.DataInputStream; 022import java.io.IOException; 023import java.math.BigDecimal; 024import java.util.Optional; 025import java.util.UUID; 026 027/** 028 * ChannelBytesWrapper represents a utility wrapper for a ByteArray stream. 029 * 030 * @author creatorfromhell 031 * @since 0.1.2.0 032 */ 033public class ChannelBytesWrapper implements AutoCloseable { 034 035 private final byte[] data; 036 private DataInputStream in; 037 038 public ChannelBytesWrapper(byte[] data) { 039 040 this.data = data; 041 open(); 042 } 043 044 public void open() { 045 046 this.in = new DataInputStream(new ByteArrayInputStream(data)); 047 } 048 049 @Override 050 public void close() { 051 052 try { 053 in.close(); 054 } catch(IOException e) { 055 e.printStackTrace(); 056 } 057 } 058 059 public short readShort() throws IOException { 060 061 return in.readShort(); 062 } 063 064 public String readUTF() throws IOException { 065 066 return in.readUTF(); 067 } 068 069 public Optional<UUID> readUUID() throws IOException { 070 071 final String str = readUTF(); 072 073 try { 074 return Optional.of(UUID.fromString(str)); 075 } catch(Exception ignore) { 076 return Optional.empty(); 077 } 078 } 079 080 public Optional<BigDecimal> readBigDecimal() throws IOException { 081 082 final String str = readUTF(); 083 084 try { 085 return Optional.of(new BigDecimal(str)); 086 } catch(Exception ignore) { 087 return Optional.empty(); 088 } 089 } 090}