001/*
002 * JDrupes Builder
003 * Copyright (C) 2025 Michael N. Lipp
004 * 
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
017 */
018
019package org.jdrupes.builder.java;
020
021import java.io.IOException;
022import java.io.InputStream;
023import java.io.OutputStream;
024import java.time.Instant;
025import java.util.Objects;
026import java.util.jar.JarEntry;
027import java.util.jar.JarFile;
028import org.jdrupes.builder.api.IOResource;
029import org.jdrupes.builder.core.ResourceObject;
030
031/// Represents an entry in a jar file.
032///
033public class JarFileEntry extends ResourceObject implements IOResource {
034
035    private final JarFile jarFile;
036    private final JarEntry entry;
037
038    /// Initializes a new jar file entry.
039    ///
040    /// @param jarFile the jar file
041    /// @param entry the entry
042    ///
043    public JarFileEntry(JarFile jarFile, JarEntry entry) {
044        super();
045        this.jarFile = jarFile;
046        this.entry = entry;
047    }
048
049    @Override
050    public Instant asOf() {
051        return entry.getLastModifiedTime().toInstant();
052    }
053
054    @Override
055    public InputStream inputStream() throws IOException {
056        return jarFile.getInputStream(entry);
057    }
058
059    @Override
060    public OutputStream outputStream() throws IOException {
061        throw new UnsupportedOperationException();
062    }
063
064    @Override
065    public int hashCode() {
066        final int prime = 31;
067        int result = super.hashCode();
068        result
069            = prime * result + Objects.hash(entry.getName(), jarFile.getName());
070        return result;
071    }
072
073    @Override
074    public boolean equals(Object obj) {
075        if (this == obj) {
076            return true;
077        }
078        if (!super.equals(obj)) {
079            return false;
080        }
081        return (obj instanceof JarFileEntry other)
082            && Objects.equals(entry.getName(), other.entry.getName())
083            && Objects.equals(jarFile.getName(), other.jarFile.getName());
084    }
085
086    @Override
087    public String toString() {
088        return jarFile.getName() + "!" + entry.getName() + " ("
089            + asOfLocalized() + ")";
090    }
091
092}