summaryrefslogtreecommitdiff
path: root/opendc-web/opendc-web-server/src/main/java/org/opendc/web/server/model/Project.java
blob: f4e5305d2236dde7bd64263326fc433d5ad46e09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
 * Copyright (c) 2022 AtLarge Research
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package org.opendc.web.server.model;

import io.quarkus.hibernate.orm.panache.Panache;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import io.quarkus.panache.common.Parameters;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Table;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;

/**
 * A project in OpenDC encapsulates all the datacenter designs and simulation runs for a set of users.
 */
@Entity
@Table
@NamedQueries({
    @NamedQuery(
            name = "Project.findByUser",
            query =
                    """
            SELECT a
            FROM ProjectAuthorization a
            WHERE a.key.userName = :userName
        """),
    @NamedQuery(
            name = "Project.allocatePortfolio",
            query =
                    """
            UPDATE Project p
            SET p.portfoliosCreated = :oldState + 1, p.updatedAt = :now
            WHERE p.id = :id AND p.portfoliosCreated = :oldState
        """),
    @NamedQuery(
            name = "Project.allocateTopology",
            query =
                    """
            UPDATE Project p
            SET p.topologiesCreated = :oldState + 1, p.updatedAt = :now
            WHERE p.id = :id AND p.topologiesCreated = :oldState
        """),
    @NamedQuery(
            name = "Project.allocateScenario",
            query =
                    """
            UPDATE Project p
            SET p.scenariosCreated = :oldState + 1, p.updatedAt = :now
            WHERE p.id = :id AND p.scenariosCreated = :oldState
        """)
})
public class Project extends PanacheEntityBase {

    /**
     * The main ID of a project.
     * The value starts at 6 to account for the other 5 projects already made by the loading script.
     */
    @Id
    @SequenceGenerator(name = "projectSeq", sequenceName = "project_id_seq", allocationSize = 1, initialValue = 7)
    @GeneratedValue(generator = "projectSeq")
    public Long id;

    /**
     * The name of the project.
     */
    @Column(nullable = false)
    public String name;

    /**
     * The instant at which the project was created.
     */
    @Column(name = "created_at", nullable = false, updatable = false)
    public Instant createdAt;

    /**
     * The instant at which the project was updated.
     */
    @Column(name = "updated_at", nullable = false)
    public Instant updatedAt;

    /**
     * The portfolios belonging to this project.
     */
    @OneToMany(
            cascade = {CascadeType.ALL},
            mappedBy = "project",
            orphanRemoval = true)
    @OrderBy("id ASC")
    public Set<Portfolio> portfolios = new HashSet<>();

    /**
     * The number of portfolios created for this project (including deleted portfolios).
     */
    @Column(name = "portfolios_created", nullable = false)
    public int portfoliosCreated = 0;

    /**
     * The topologies belonging to this project.
     */
    @OneToMany(
            cascade = {CascadeType.ALL},
            mappedBy = "project",
            orphanRemoval = true)
    @OrderBy("id ASC")
    public Set<Topology> topologies = new HashSet<>();

    /**
     * The number of topologies created for this project (including deleted topologies).
     */
    @Column(name = "topologies_created", nullable = false)
    public int topologiesCreated = 0;

    /**
     * The scenarios belonging to this project.
     */
    @OneToMany(mappedBy = "project", orphanRemoval = true)
    public Set<Scenario> scenarios = new HashSet<>();

    /**
     * The number of scenarios created for this project (including deleted scenarios).
     */
    @Column(name = "scenarios_created", nullable = false)
    public int scenariosCreated = 0;

    /**
     * The users authorized to access the project.
     */
    @OneToMany(
            cascade = {CascadeType.ALL},
            mappedBy = "project",
            orphanRemoval = true)
    public Set<ProjectAuthorization> authorizations = new HashSet<>();

    /**
     * Construct a {@link Project} object.
     */
    public Project(String name, Instant createdAt) {
        this.name = name;
        this.createdAt = createdAt;
        this.updatedAt = createdAt;
    }

    /**
     * JPA constructor
     */
    protected Project() {}

    /**
     * Allocate the next portfolio number for the specified [project].
     *
     * @param time The time at which the new portfolio is created.
     */
    public int allocatePortfolio(Instant time) {
        for (int i = 0; i < 4; i++) {
            long count = update(
                    "#Project.allocatePortfolio",
                    Parameters.with("id", id).and("oldState", portfoliosCreated).and("now", time));
            if (count > 0) {
                return portfoliosCreated + 1;
            } else {
                Panache.getEntityManager().refresh(this);
            }
        }

        throw new IllegalStateException("Failed to allocate next portfolio");
    }

    /**
     * Allocate the next topology number for the specified [project].
     *
     * @param time The time at which the new topology is created.
     */
    public int allocateTopology(Instant time) {
        for (int i = 0; i < 4; i++) {
            long count = update(
                    "#Project.allocateTopology",
                    Parameters.with("id", id).and("oldState", topologiesCreated).and("now", time));
            if (count > 0) {
                return topologiesCreated + 1;
            } else {
                Panache.getEntityManager().refresh(this);
            }
        }

        throw new IllegalStateException("Failed to allocate next topology");
    }

    /**
     * Allocate the next scenario number for the specified [project].
     *
     * @param time The time at which the new scenario is created.
     */
    public int allocateScenario(Instant time) {
        for (int i = 0; i < 4; i++) {
            long count = update(
                    "#Project.allocateScenario",
                    Parameters.with("id", id).and("oldState", scenariosCreated).and("now", time));
            if (count > 0) {
                return scenariosCreated + 1;
            } else {
                Panache.getEntityManager().refresh(this);
            }
        }

        throw new IllegalStateException("Failed to allocate next scenario");
    }
}