BrightSide Workbench Full Report + Source Code
RelatedMigration.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2022 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.related;
20 
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.locks.ReentrantLock;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25 import java.util.stream.Stream;
26 import org.turro.elephant.context.ElephantContext;
27 import org.turro.elephant.db.ElephantPU;
28 import org.turro.jpa.Dao;
29 import org.turro.jpa.DaoUtil;
30 
35 public class RelatedMigration implements Runnable {
36 
37  private final Dao oldRelatedDao, newRelatedDao;
38 
39  public static void migrate() {
40  RelatedMigration migration = new RelatedMigration(Dao.getDaoByPU("contactsPU"));
41  if(migration.isNecessary()) new Thread(migration, "ElephantRelated migration").start();
42  }
43 
44  private boolean isNecessary() {
45  return DaoUtil.isEmpty(newRelatedDao, "Related") && !DaoUtil.isEmpty(oldRelatedDao, "RelatedPaths");
46  }
47 
48  private void start() {
49  try(Stream<OldRelatedEntry> related = oldRelatedDao.stream(OldRelatedEntry.class, getSelect())) {
50  related.forEach((relation) -> {
51  relation.migrate(newRelatedDao);
52  });
53  }
54  }
55 
56  private String getSelect() {
57  return "select new org.turro.related.OldRelatedEntry(origin, destination, description, unbreakable, creation) from RelatedPaths";
58  }
59 
60  private RelatedMigration(Dao oldRelatedDao) {
61  this.oldRelatedDao = oldRelatedDao;
62  this.newRelatedDao = new ElephantPU();
63  }
64 
65  private static final ReentrantLock LOCK = new ReentrantLock();
66 
67  @Override
68  public void run() {
69  if(!LOCK.isLocked()) {
70  try {
71  if(LOCK.tryLock(0, TimeUnit.SECONDS)) {
72  try {
73  if(isNecessary()) {
74  start();
75  }
76  } finally {
77  LOCK.unlock();
78  }
79  }
80  } catch (InterruptedException ex) {
81  Logger.getLogger(RelatedMigration.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
82  }
83  }
84  }
85 
86 }
static boolean isEmpty(Dao dao, String table)
Definition: DaoUtil.java:35
static Dao getDaoByPU(String pu)
Definition: Dao.java:654