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.core; 020 021import java.io.IOException; 022import java.nio.file.Files; 023import java.nio.file.Path; 024import org.jdrupes.builder.api.Cleanliness; 025import org.jdrupes.builder.api.Generator; 026import org.jdrupes.builder.api.Project; 027import org.jdrupes.builder.api.ResourceRequest; 028import static org.jdrupes.builder.api.ResourceType.CleanlinessType; 029 030// TODO: Auto-generated Javadoc 031/// A base implementation of a [Generator]. 032/// 033public abstract class AbstractGenerator extends AbstractProvider 034 implements Generator { 035 036 private final Project project; 037 private String name; 038 039 /// Instantiates a new abstract generator. 040 /// 041 /// @param project the project 042 /// 043 public AbstractGenerator(Project project) { 044 this.project = project; 045 name = getClass().getSimpleName(); 046 if (name.isBlank()) { 047 name = "Adapted " + getClass().getSuperclass().getSimpleName(); 048 } 049 } 050 051 /// Sets the name of the generator. 052 /// 053 /// @param name the name 054 /// @return the generator 055 /// 056 public AbstractGenerator name(String name) { 057 this.name = name; 058 return this; 059 } 060 061 /// Name. 062 /// 063 /// @return the string 064 /// 065 @Override 066 public String name() { 067 return name; 068 } 069 070 /// Project. 071 /// 072 /// @return the project 073 /// 074 @Override 075 public final Project project() { 076 return project; 077 } 078 079 /// If the request includes [Cleanliness] deletes the given files 080 /// and returns `true`. 081 /// 082 /// @param requested the requested resource 083 /// @param files the files 084 /// @return true, if successful 085 /// 086 protected boolean cleanup(ResourceRequest<?> requested, Path... files) { 087 if (!requested.includes(CleanlinessType)) { 088 return false; 089 } 090 for (Path file : files) { 091 try { 092 Files.deleteIfExists(file); 093 } catch (IOException e) { 094 log.warning(() -> file + " cannot be deleted."); 095 } 096 } 097 return true; 098 } 099 100 /// To string. 101 /// 102 /// @return the string 103 /// 104 @Override 105 public String toString() { 106 return name + " in project " + project().name(); 107 } 108 109}