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 this.data = data; 040 open(); 041 } 042 043 public void open() { 044 this.in = new DataInputStream(new ByteArrayInputStream(data)); 045 } 046 047 @Override 048 public void close() { 049 try { 050 in.close(); 051 } catch (IOException e) { 052 e.printStackTrace(); 053 } 054 } 055 056 public short readShort() throws IOException { 057 return in.readShort(); 058 } 059 060 public String readUTF() throws IOException { 061 return in.readUTF(); 062 } 063 064 public Optional<UUID> readUUID() throws IOException { 065 final String str = readUTF(); 066 067 try { 068 return Optional.of(UUID.fromString(str)); 069 } catch (Exception ignore) { 070 return Optional.empty(); 071 } 072 } 073 074 public Optional<BigDecimal> readBigDecimal() throws IOException { 075 final String str = readUTF(); 076 077 try { 078 return Optional.of(new BigDecimal(str)); 079 } catch (Exception ignore) { 080 return Optional.empty(); 081 } 082 } 083}