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