001/*
002 * acme4j - Java ACME client
003 *
004 * Copyright (C) 2018 Richard "Shred" Körber
005 *   http://acme4j.shredzone.org
006 *
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
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.
013 */
014package org.shredzone.acme4j;
015
016import java.io.Serial;
017import java.net.URL;
018import java.time.Instant;
019import java.util.Objects;
020import java.util.Optional;
021
022import edu.umd.cs.findbugs.annotations.Nullable;
023import org.shredzone.acme4j.exception.AcmeException;
024import org.shredzone.acme4j.exception.AcmeLazyLoadingException;
025import org.shredzone.acme4j.toolbox.JSON;
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029/**
030 * An extension of {@link AcmeResource} that also contains the current state of a resource
031 * as JSON document. If the current state is not present, this class takes care of
032 * fetching it from the server if necessary.
033 */
034public abstract class AcmeJsonResource extends AcmeResource {
035    @Serial
036    private static final long serialVersionUID = -5060364275766082345L;
037    private static final Logger LOG = LoggerFactory.getLogger(AcmeJsonResource.class);
038
039    private @Nullable JSON data = null;
040    private @Nullable Instant retryAfter = null;
041
042    /**
043     * Create a new {@link AcmeJsonResource}.
044     *
045     * @param login
046     *            {@link Login} the resource is bound with
047     * @param location
048     *            Location {@link URL} of this resource
049     */
050    protected AcmeJsonResource(Login login, URL location) {
051        super(login, location);
052    }
053
054    /**
055     * Returns the JSON representation of the resource data.
056     * <p>
057     * If there is no data, {@link #fetch()} is invoked to fetch it from the server.
058     * <p>
059     * This method can be used to read proprietary data from the resources.
060     *
061     * @return Resource data, as {@link JSON}.
062     * @throws AcmeLazyLoadingException
063     *         if an {@link AcmeException} occured while fetching the current state from
064     *         the server.
065     */
066    public JSON getJSON() {
067        if (data == null) {
068            try {
069                fetch();
070            } catch (AcmeException ex) {
071                throw new AcmeLazyLoadingException(this, ex);
072            }
073        }
074        return Objects.requireNonNull(data);
075    }
076
077    /**
078     * Sets the JSON representation of the resource data.
079     *
080     * @param data
081     *            New {@link JSON} data, must not be {@code null}.
082     */
083    protected void setJSON(JSON data) {
084        invalidate();
085        this.data = Objects.requireNonNull(data, "data");
086    }
087
088    /**
089     * Checks if this resource is valid.
090     *
091     * @return {@code true} if the resource state has been loaded from the server. If
092     *         {@code false}, {@link #getJSON()} would implicitly call {@link #fetch()}
093     *         to fetch the current state from the server.
094     */
095    protected boolean isValid() {
096        return data != null;
097    }
098
099    /**
100     * Invalidates the state of this resource. Enforces a {@link #fetch()} when
101     * {@link #getJSON()} is invoked.
102     * <p>
103     * Subclasses can override this method to purge internal caches that are based on the
104     * JSON structure. Remember to invoke {@code super.invalidate()}!
105     */
106    protected void invalidate() {
107        data = null;
108        retryAfter = null;
109    }
110
111    /**
112     * Updates this resource, by fetching the current resource data from the server.
113     *
114     * @return An {@link Optional} estimation when the resource status will change. If you
115     * are polling for the resource to complete, you should wait for the given instant
116     * before trying again. Empty if the server did not return a "Retry-After" header.
117     * @throws AcmeException
118     *         if the resource could not be fetched.
119     * @since 3.2.0
120     */
121    public Optional<Instant> fetch() throws AcmeException {
122        var resourceType = getClass().getSimpleName();
123        LOG.debug("update {}", resourceType);
124        try (var conn = getSession().connect()) {
125            conn.sendSignedPostAsGetRequest(getLocation(), getLogin());
126            setJSON(conn.readJsonResponse());
127            var retryAfterOpt = conn.getRetryAfter();
128            retryAfterOpt.ifPresent(instant -> LOG.debug("Retry-After: {}", instant));
129            setRetryAfter(retryAfterOpt.orElse(null));
130            return retryAfterOpt;
131        }
132    }
133
134    /**
135     * Sets a Retry-After instant.
136     *
137     * @since 3.2.0
138     */
139    protected void setRetryAfter(@Nullable Instant retryAfter) {
140        this.retryAfter = retryAfter;
141    }
142
143    /**
144     * Gets an estimation when the resource status will change. If you are polling for
145     * the resource to complete, you should wait for the given instant before trying
146     * a status refresh.
147     * <p>
148     * This instant was sent with the Retry-After header at the last update.
149     *
150     * @return Retry-after {@link Instant}, or empty if there was no such header.
151     * @since 3.2.0
152     */
153    public Optional<Instant> getRetryAfter() {
154        return Optional.ofNullable(retryAfter);
155    }
156
157}