001/*
002 * acme4j - Java ACME client
003 *
004 * Copyright (C) 2016 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.Serializable;
017import java.net.URL;
018import java.util.Objects;
019
020import edu.umd.cs.findbugs.annotations.Nullable;
021
022/**
023 * A generic ACME resource.
024 */
025public abstract class AcmeResource implements Serializable {
026    private static final long serialVersionUID = -7930580802257379731L;
027
028    private transient @Nullable Login login;
029    private final URL location;
030
031    /**
032     * Create a new {@link AcmeResource}.
033     *
034     * @param login
035     *            {@link Login} the resource is bound with
036     * @param location
037     *            Location {@link URL} of this resource
038     */
039    protected AcmeResource(Login login, URL location) {
040        this.location = Objects.requireNonNull(location, "location");
041        rebind(login);
042    }
043
044    /**
045     * Gets the {@link Login} this resource is bound with.
046     */
047    protected Login getLogin() {
048        if (login == null) {
049            throw new IllegalStateException("Use rebind() for binding this object to a login.");
050        }
051        return login;
052    }
053
054    /**
055     * Gets the {@link Session} this resource is bound with.
056     */
057    protected Session getSession() {
058        return getLogin().getSession();
059    }
060
061    /**
062     * Rebinds this resource to a {@link Login}.
063     * <p>
064     * Logins are not serialized, because they contain volatile session data and also a
065     * private key. After de-serialization of an {@link AcmeResource}, use this method to
066     * rebind it to a {@link Login}.
067     *
068     * @param login
069     *            {@link Login} to bind this resource to
070     */
071    public void rebind(Login login) {
072        if (this.login != null) {
073            throw new IllegalStateException("Resource is already bound to a login");
074        }
075        this.login = Objects.requireNonNull(login, "login");
076    }
077
078    /**
079     * Gets the resource's location.
080     */
081    public URL getLocation() {
082        return location;
083    }
084
085}