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 */
017
018package org.apache.bcel.classfile;
019
020import java.io.DataInput;
021import java.io.DataOutputStream;
022import java.io.IOException;
023import java.util.Arrays;
024
025import org.apache.bcel.Const;
026import org.apache.bcel.util.Args;
027import org.apache.commons.lang3.ArrayUtils;
028
029/**
030 * This class is derived from <em>Attribute</em> and records the classes and interfaces that are authorized to claim
031 * membership in the nest hosted by the current class or interface. There may be at most one NestMembers attribute in a
032 * ClassFile structure.
033 *
034 * @see Attribute
035 */
036public final class NestMembers extends Attribute {
037
038    private int[] classes;
039
040    /**
041     * Constructs object from input stream.
042     *
043     * @param nameIndex Index in constant pool
044     * @param length Content length in bytes
045     * @param input Input stream
046     * @param constantPool Array of constants
047     * @throws IOException if an I/O error occurs.
048     */
049    NestMembers(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException {
050        this(nameIndex, length, (int[]) null, constantPool);
051        final int classCount = input.readUnsignedShort();
052        classes = new int[classCount];
053        for (int i = 0; i < classCount; i++) {
054            classes[i] = input.readUnsignedShort();
055        }
056    }
057
058    /**
059     * @param nameIndex Index in constant pool
060     * @param length Content length in bytes
061     * @param classes Table of indices in constant pool
062     * @param constantPool Array of constants
063     */
064    public NestMembers(final int nameIndex, final int length, final int[] classes, final ConstantPool constantPool) {
065        super(Const.ATTR_NEST_MEMBERS, nameIndex, length, constantPool);
066        this.classes = ArrayUtils.nullToEmpty(classes);
067        Args.requireU2(this.classes.length, "classes.length");
068    }
069
070    /**
071     * Initialize from another object. Note that both objects use the same references (shallow copy). Use copy() for a
072     * physical copy.
073     *
074     * @param c Source to copy.
075     */
076    public NestMembers(final NestMembers c) {
077        this(c.getNameIndex(), c.getLength(), c.getClasses(), c.getConstantPool());
078    }
079
080    /**
081     * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
082     * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.
083     *
084     * @param v Visitor object
085     */
086    @Override
087    public void accept(final Visitor v) {
088        v.visitNestMembers(this);
089    }
090
091    /**
092     * @return deep copy of this attribute
093     */
094    @Override
095    public Attribute copy(final ConstantPool constantPool) {
096        final NestMembers c = (NestMembers) clone();
097        if (classes.length > 0) {
098            c.classes = classes.clone();
099        }
100        c.setConstantPool(constantPool);
101        return c;
102    }
103
104    /**
105     * Dump NestMembers attribute to file stream in binary format.
106     *
107     * @param file Output file stream
108     * @throws IOException if an I/O error occurs.
109     */
110    @Override
111    public void dump(final DataOutputStream file) throws IOException {
112        super.dump(file);
113        file.writeShort(classes.length);
114        for (final int index : classes) {
115            file.writeShort(index);
116        }
117    }
118
119    /**
120     * @return array of indices into constant pool of class names.
121     */
122    public int[] getClasses() {
123        return classes;
124    }
125
126    /**
127     * @return string array of class names
128     */
129    public String[] getClassNames() {
130        final String[] names = new String[classes.length];
131        Arrays.setAll(names, i -> Utility.pathToPackage(super.getConstantPool().getConstantString(classes[i], Const.CONSTANT_Class)));
132        return names;
133    }
134
135    /**
136     * @return Length of classes table.
137     */
138    public int getNumberClasses() {
139        return classes.length;
140    }
141
142    /**
143     * @param classes the list of class indexes Also redefines number_of_classes according to table length.
144     */
145    public void setClasses(final int[] classes) {
146        this.classes = ArrayUtils.nullToEmpty(classes);
147    }
148
149    /**
150     * @return String representation, i.e., a list of classes.
151     */
152    @Override
153    public String toString() {
154        final StringBuilder buf = new StringBuilder();
155        buf.append("NestMembers(");
156        buf.append(classes.length);
157        buf.append("):\n");
158        for (final int index : classes) {
159            final String className = super.getConstantPool().getConstantString(index, Const.CONSTANT_Class);
160            buf.append("  ").append(Utility.compactClassName(className, false)).append("\n");
161        }
162        return buf.substring(0, buf.length() - 1); // remove the last newline
163    }
164}