001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019
020package org.apache.bcel.classfile;
021
022import java.io.DataInput;
023import java.io.DataOutputStream;
024import java.io.IOException;
025import java.util.Arrays;
026
027import org.apache.bcel.Const;
028import org.apache.bcel.util.Args;
029import org.apache.commons.lang3.ArrayUtils;
030
031/**
032 * This class is derived from <em>Attribute</em> and represents the list of packages that are exported or opened by the
033 * Module attribute. There may be at most one ModulePackages attribute in a ClassFile structure.
034 *
035 * @see Attribute
036 */
037public final class ModulePackages extends Attribute {
038
039    private int[] packageIndexTable;
040
041    /**
042     * Constructs object from input stream.
043     *
044     * @param nameIndex Index in constant pool
045     * @param length Content length in bytes
046     * @param input Input stream
047     * @param constantPool Array of constants
048     * @throws IOException if an I/O error occurs.
049     */
050    ModulePackages(final int nameIndex, final int length, final DataInput input, final ConstantPool constantPool) throws IOException {
051        this(nameIndex, length, (int[]) null, constantPool);
052        final int packageCount = input.readUnsignedShort();
053        packageIndexTable = new int[packageCount];
054        for (int i = 0; i < packageCount; i++) {
055            packageIndexTable[i] = input.readUnsignedShort();
056        }
057    }
058
059    /**
060     * @param nameIndex Index in constant pool
061     * @param length Content length in bytes
062     * @param packageIndexTable Table of indices in constant pool
063     * @param constantPool Array of constants
064     */
065    public ModulePackages(final int nameIndex, final int length, final int[] packageIndexTable, final ConstantPool constantPool) {
066        super(Const.ATTR_MODULE_PACKAGES, nameIndex, length, constantPool);
067        this.packageIndexTable = ArrayUtils.nullToEmpty(packageIndexTable);
068        Args.requireU2(this.packageIndexTable.length, "packageIndexTable.length");
069    }
070
071    /**
072     * Initialize from another object. Note that both objects use the same references (shallow copy). Use copy() for a
073     * physical copy.
074     *
075     * @param c Source to copy.
076     */
077    public ModulePackages(final ModulePackages c) {
078        this(c.getNameIndex(), c.getLength(), c.getPackageIndexTable(), c.getConstantPool());
079    }
080
081    /**
082     * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
083     * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.
084     *
085     * @param v Visitor object
086     */
087    @Override
088    public void accept(final Visitor v) {
089        v.visitModulePackages(this);
090    }
091
092    /**
093     * @return deep copy of this attribute
094     */
095    @Override
096    public Attribute copy(final ConstantPool constantPool) {
097        final ModulePackages c = (ModulePackages) clone();
098        if (packageIndexTable != null) {
099            c.packageIndexTable = packageIndexTable.clone();
100        }
101        c.setConstantPool(constantPool);
102        return c;
103    }
104
105    /**
106     * Dump ModulePackages attribute to file stream in binary format.
107     *
108     * @param file Output file stream
109     * @throws IOException if an I/O error occurs.
110     */
111    @Override
112    public void dump(final DataOutputStream file) throws IOException {
113        super.dump(file);
114        file.writeShort(packageIndexTable.length);
115        for (final int index : packageIndexTable) {
116            file.writeShort(index);
117        }
118    }
119
120    /**
121     * @return Length of package table.
122     */
123    public int getNumberOfPackages() {
124        return packageIndexTable == null ? 0 : packageIndexTable.length;
125    }
126
127    /**
128     * @return array of indices into constant pool of package names.
129     */
130    public int[] getPackageIndexTable() {
131        return packageIndexTable;
132    }
133
134    /**
135     * @return string array of package names
136     */
137    public String[] getPackageNames() {
138        final String[] names = new String[packageIndexTable.length];
139        Arrays.setAll(names, i -> Utility.pathToPackage(super.getConstantPool().getConstantString(packageIndexTable[i], Const.CONSTANT_Package)));
140        return names;
141    }
142
143    /**
144     * @param packageIndexTable the list of package indexes Also redefines number_of_packages according to table length.
145     */
146    public void setPackageIndexTable(final int[] packageIndexTable) {
147        this.packageIndexTable = ArrayUtils.nullToEmpty(packageIndexTable);
148    }
149
150    /**
151     * @return String representation, i.e., a list of packages.
152     */
153    @Override
154    public String toString() {
155        final StringBuilder buf = new StringBuilder();
156        buf.append("ModulePackages(");
157        buf.append(packageIndexTable.length);
158        buf.append("):\n");
159        for (final int index : packageIndexTable) {
160            final String packageName = super.getConstantPool().getConstantString(index, Const.CONSTANT_Package);
161            buf.append("  ").append(Utility.compactClassName(packageName, false)).append("\n");
162        }
163        return buf.substring(0, buf.length() - 1); // remove the last newline
164    }
165}