BrightSide Workbench Full Report + Source Code
RelationMigration.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2020 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.contacts.relation;
20 
21 import java.util.stream.Stream;
22 import org.turro.string.Strings;
23 import org.turro.contacts.BusinessRelation;
24 import org.turro.contacts.Contact;
25 import org.turro.contacts.ContactType;
26 import org.turro.contacts.Relation;
27 import org.turro.contacts.db.ContactsPU;
28 import org.turro.jpa.Dao;
29 import org.turro.jpa.DaoUtil;
30 
35 public class RelationMigration {
36 
37  public static void migrate() {
38  RelationMigration migration = new RelationMigration();
39  if(migration.isNecessary()) {
40  migration.start();
41  }
42  qualifyCompanies();
43  }
44 
45  private boolean isNecessary() {
46  Dao dao = new ContactsPU();
47  return DaoUtil.isEmpty(dao, "BusinessRelation") && !DaoUtil.isEmpty(dao, "Relation");
48  }
49 
50  private void start() {
51  Dao dao = new ContactsPU();
52  try(Stream<Relation> relations = new ContactsPU().stream(Relation.class, "select r from Relation r")) {
53  relations.forEach((relation) -> {
54  if(Strings.isBlank(relation.getRelationType()) || !relation.getRelationType().startsWith("$INT_")) {
55  BusinessRelation br = new BusinessRelation();
56  br.setId(relation.getId());
57  br.setContact(relation.getContact1());
58  br.setBusiness(relation.getContact2());
59  br.setRelationType(relation.getRelationType());
60  br.setDescription(relation.getDescription());
61  br.setPreferential(relation.isPreferential());
62  br.setValidated(true);
63  dao.saveObject(br);
64  }
65  });
66  }
67  }
68 
69  private static void qualifyCompanies() {
70  Dao dao = new ContactsPU();
71  try(Stream<BusinessRelation> relations = new ContactsPU().stream(BusinessRelation.class,
72  "select r from BusinessRelation r")) {
73  relations.forEach((relation) -> {
74  Contact business = relation.getBusiness();
75  if(ContactType.CONTACT_USER.equals(business.getType())) {
76  business.setType(ContactType.CONTACT_COMPANY);
77  dao.saveObject(business);
78  }
79  });
80  }
81  }
82 
83 }
static boolean isEmpty(Dao dao, String table)
Definition: DaoUtil.java:35