|
|||||||
Чистим дубли, многопоточность
Время создания: 10.12.2019 17:08
Раздел: INFO - JOB - CUBA - GroovyScripts
Запись: wwwlir/Tetra/master/base/1575968938ky5pfynrz9/text.html на raw.githubusercontent.com
|
|||||||
|
|||||||
import com.groupstp.rtneo.entity.*; import com.haulmont.cuba.core.global.*; import com.groupstp.rtneo.service.*; import com.haulmont.cuba.core.sys.SecurityContext; import com.haulmont.cuba.core.sys.AppContext; import com.haulmont.cuba.core.sys.SecurityContextAwareRunnable import java.util.concurrent.*; import com.haulmont.cuba.core.global.ViewRepository; import com.haulmont.cuba.core.global.View; import com.groupstp.rtneo.core.bean.ContragentWorker; DataManager dataManager = AppBeans.get(DataManager.NAME); final SecurityContext securityContext = AppContext.getSecurityContext(); System.out.println("================================================>>> START!!! <<<") //Создается основной поток Runnable task = new Runnable() {
public void run() { //Получается securityContext. Нужен для выполнения потока от имени пользователя AppContext.setSecurityContext(securityContext); ViewRepository vRep = AppBeans.get(ViewRepository.NAME) View viewContragent = vRep.getView(Contragent.class, "_minimal") viewContragent.addProperty("inn") viewContragent.addProperty("personalAccount") viewContragent.addProperty("type") System.out.println("MAIN THREAD " + Thread.currentThread().getName())
System.out.println("INIT POOL") //Инициализация пула с указанием количества потоков ExecutorService executorService = Executors.newFixedThreadPool(5)
def list = [] for(def i=0; i<230; i++){ list = dataManager.load(Contragent.class) .query('select c from rtneo$Contragent c where c.personalAccount is null and c.createdBy like \'%dataminer%\' order by c.inn') .firstResult(i*500) .maxResults(500) .view(viewContragent) .list(); //Старт потока в методе startExec(executorService, list) }
System.out.println("EXECUTOR SHUTDOWN") //Обязательно закрываем пулл executorService.shutdown() //Максимальное время действия потока и проверка его окончания //def done = executorService.awaitTermination(1, TimeUnit.MINUTES); // System.out.println("awaitTermination done is "+done) } } //Установка и запуск потока Thread thread = new Thread(task); thread.start(); System.out.println(">>> END!!! <<<") public void startExec(ExecutorService executorService, List<Object> list){ System.out.println("Start exec") //Добавление потока в пулл с передачей securityContext Future future = executorService.submit(new SecurityContextAwareRunnable({ try { System.out.println("=== Start thread > " + Thread.currentThread().getName()) //Для удобства бизнес логика вынесена в отдельный метод createContract(list)
} catch (Exception e) { log.error('Error creating entity', e) } System.out.println("=== End thread > " + Thread.currentThread().getName()) }))
System.out.println("End exec") } public void createContract(List<Object> list){ System.out.println("WORKING IN THREAD " + Thread.currentThread().getName()) DataManager dataManager = AppBeans.get(DataManager.NAME) ViewRepository vRep = AppBeans.get(ViewRepository.NAME) View viewCre = vRep.getView(ContragentRealEstate.class, "_minimal") viewCre.addProperty("realEstate", vRep.getView(RealEstate.class, "_minimal").addProperty("cadastralNumber")) viewCre.addProperty("contragent", vRep.getView(Contragent.class, "_minimal")) viewCre.addProperty("calculationAmount") viewCre.addProperty("livingArea") View viewContragent = vRep.getView(Contragent.class, "_minimal") viewContragent.addProperty("inn") viewContragent.addProperty("personalAccount") viewContragent.addProperty("type") def createPA = 0 def changeContragent = 0 def deleteContragent = 0 def previousINN = null def previousName = null for(Contragent contragent : list){ System.out.println("\n*****************************************************************") System.out.println("contragent - ${contragent} is inn - ${contragent.getInn()}") //System.out.println(dataManager.loadValue('select count(c) from rtneo$Contragent c where c.inn = :inn', Integer.class).parameter("inn", contragent.getInn()).optional().orElse(0)) if(contragent.getInn() == null){ System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...${contragent.getType()}") if(contragent.getType() == ContragentType.PERSONAL){ System.out.println("++++++++++++++++++++++++=${contragent.getType()}") System.out.println("Нужно сгенерировать ЛС -- (${contragent.getName()})") contragent.setPersonalAccount(generatePersonalNumber(contragent)) System.out.println("ЛС -- (${contragent.getPersonalAccount()})") createPA++ dataManager.commit(contragent) continue }else{ continue } } System.out.println(">>SEARCH CONTRAGENT!<<") def paContragent = dataManager.load(Contragent.class) .query('select c from rtneo$Contragent c where c.inn = :inn and not c.personalAccount is null') .parameter("inn", contragent.getInn()) .view(viewContragent) .optional() .orElse(null) System.out.println("paContragent - ${paContragent}")
if(paContragent == null){ System.out.println("Нужно сгенерировать ЛС -- (${contragent.getName()})") contragent.setPersonalAccount(generatePersonalNumber(contragent)) createPA++ dataManager.commit(contragent) continue }else{ System.out.println("===================paContragent found ===================") }
// def paCres = paContragent.getRealEstates() def paCres = dataManager.load(ContragentRealEstate.class) .query('select c from rtneo$ContragentRealEstate c where c.contragent.id = :id') .parameter("id", paContragent.getId()) .view(viewCre) .list() System.out.println("paCres.size() - ${paCres.size()}")
// def cres = contragent.getRealEstates() def cres = dataManager.load(ContragentRealEstate.class) .query('select c from rtneo$ContragentRealEstate c where c.contragent.id = :id') .parameter("id", contragent.getId()) .view(viewCre) .list() System.out.println("cres.size() - ${cres.size()}")
System.out.println(">>SEARCH CRE<<") for(ContragentRealEstate cre : cres){
def found = false for(ContragentRealEstate paCre : paCres){
System.out.println("${paCre.getRealEstate().getCadastralNumber()}")
if(paCre.getRealEstate().getCadastralNumber() == cre.getRealEstate().getCadastralNumber()){ if(paCre.getCalculationAmount() == cre.getLivingArea() || paCre.getLivingArea() == cre.getLivingArea()){ found = true break } }
}
if(found){ System.out.println("found cad - ${cre.getRealEstate().getCadastralNumber()}") }else{ System.out.println("no found cad - ${cre.getRealEstate().getCadastralNumber()} need to create!!!") if(cre.getCalculationAmount() == 0 || cre.getCalculationAmount() == null) cre.setCalculationAmount(cre.getLivingArea()) cre.setContragent(paContragent) dataManager.commit(cre) changeContragent++ }
}
System.out.println("DELETE ${contragent.getId()}") dataManager.remove(contragent) deleteContragent++ } System.out.println("Create PA = ${createPA}, changeCREContragent = ${changeContragent}, deleteContragent = ${deleteContragent}") } def generatePersonalNumber(Contragent contragent){ ContragentWorker сontragentWorker = AppBeans.get(ContragentWorker.NAME) return сontragentWorker.createAccountNumber(contragent) } |
|||||||
Так же в этом разделе:
|
|||||||
|
|||||||
|