001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.imaging.formats.jpeg.segments; 018 019import static org.apache.commons.imaging.common.BinaryFunctions.readBytes; 020 021import java.io.IOException; 022import java.io.InputStream; 023import java.io.PrintWriter; 024import java.nio.charset.Charset; 025 026public abstract class AbstractGenericSegment extends AbstractSegment { 027 private final byte[] segmentData; 028 029 public AbstractGenericSegment(final int marker, final byte[] bytes) { 030 super(marker, bytes.length); 031 032 this.segmentData = bytes.clone(); 033 } 034 035 public AbstractGenericSegment(final int marker, final int markerLength, final InputStream is) throws IOException { 036 super(marker, markerLength); 037 038 segmentData = readBytes("Segment Data", is, markerLength, "Invalid Segment: insufficient data"); 039 } 040 041 @Override 042 public void dump(final PrintWriter pw) { 043 dump(pw, 0); 044 } 045 046 public void dump(final PrintWriter pw, final int start) { 047 for (int i = 0; i < 50 && i + start < segmentData.length; i++) { 048 debugNumber(pw, "\t" + (i + start), segmentData[i + start], 1); 049 } 050 } 051 052 /** 053 * Returns a copy of the segment's contents, excluding the marker and length bytes at the beginning. 054 * 055 * @return the segment's contents 056 */ 057 public byte[] getSegmentData() { 058 return segmentData.clone(); 059 } 060 061 /** 062 * Returns a specific byte of the segment's contents, excluding the marker and length bytes at the beginning. 063 * 064 * @param offset segment offset 065 * @see AbstractGenericSegment#getSegmentData() 066 * @return the bye in the segment's contents 067 */ 068 protected byte getSegmentData(final int offset) { 069 return segmentData[offset]; 070 } 071 072 /** 073 * Convert the bytes to a String 074 * 075 * @param encoding segment encoding 076 * @return the encoded bytes 077 */ 078 public String getSegmentDataAsString(final Charset encoding) { 079 return new String(segmentData, encoding); 080 } 081 082}