Example usage for org.hibernate Session merge

List of usage examples for org.hibernate Session merge

Introduction

In this page you can find the example usage for org.hibernate Session merge.

Prototype

Object merge(Object object);

Source Link

Document

Copy the state of the given object onto the persistent object with the same identifier.

Usage

From source file:de.fhdo.terminologie.ws.authoring.MaintainConcept.java

License:Apache License

public MaintainConceptResponseType MaintainConcept(MaintainConceptRequestType parameter, String ipAddress) {
    ////////// Logger //////////////////////////////////////////////////////////////
    if (logger.isInfoEnabled())
        logger.info("====== MaintainConcept gestartet ======");

    ////////// Return-Informationen anlegen ////////////////////////////////////////
    MaintainConceptResponseType response = new MaintainConceptResponseType();
    response.setReturnInfos(new ReturnType());

    ////////// Parameter prfen ////////////////////////////////////////////////////
    if (validateParameter(parameter, response) == false)
        return response;

    // Login-Informationen auswerten (gilt fr jeden Webservice)    
    boolean loggedIn = false;
    if (parameter != null && parameter.getLoginToken() != null) {
        AuthenticateInfos loginInfoType = Authorization.authenticate(ipAddress, parameter.getLoginToken());
        loggedIn = loginInfoType != null;
    }/*from  ww w .j  ava  2s .  c o m*/

    if (loggedIn == false) {
        response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO);
        response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
        response.getReturnInfos().setMessage("You have to be logged in to use this service.");
        return response;
    }

    ////////// Der eigentliche Teil  /////////////////////////////////////////////// 
    try {
        // Fr die Statusmeldung ob eine neue VSV angelegt oder die alte verndert wurde
        String sCreateNewVersionMessage = "";
        boolean bNewVersion = parameter.getVersioning().getCreateNewVersion();

        // Hibernate-Block, Session ffnen
        org.hibernate.Session hb_session = HibernateUtil.getSessionFactory().openSession();
        hb_session.getTransaction().begin();

        CodeSystemEntity cse_Request = parameter.getCodeSystemEntity();
        Long csvId = parameter.getCodeSystemVersionId();
        CodeSystemEntity cse_db = null;
        CodeSystemEntityVersion csev_Request = (CodeSystemEntityVersion) cse_Request
                .getCodeSystemEntityVersions().toArray()[0];
        CodeSystemEntityVersion csev_New = null;

        CodeSystemConcept csc_Request = null;
        CodeSystemConcept csc_New = null;
        CodeSystemConceptTranslation csct_Request = null;
        CodeSystemConceptTranslation csct_New = null;

        Iterator<CodeSystemConcept> itCsc_Request = null;
        Iterator<CodeSystemConceptTranslation> itCsct_Request = null;

        try { // 2. try-catch-Block zum Abfangen von Hibernate-Fehlern      
              // neue Version anlegen oder alte bearbeiten?
            if (bNewVersion) {
                // original CSE aus DB laden
                cse_db = (CodeSystemEntity) hb_session.load(CodeSystemEntity.class, cse_Request.getId());

                // neues CodeSystemEntityVersion-Objekt erzeugen
                csev_New = new CodeSystemEntityVersion();

                // Not NULL werte setzen
                csev_New.setCodeSystemEntity(cse_db);
                csev_New.setStatusVisibility(Definitions.STATUS_CODES.ACTIVE.getCode());
                csev_New.setStatusVisibilityDate(new java.util.Date());
                csev_New.setStatusDeactivated(0);
                csev_New.setStatusDeactivatedDate(new java.util.Date());
                csev_New.setStatusWorkflow(0);
                csev_New.setStatusWorkflowDate(new java.util.Date());
                csev_New.setInsertTimestamp(new java.util.Date());

                csev_New.setPreviousVersionId(cse_db.getCurrentVersionId());

                // speichern damit eine Id erzeugt wird
                hb_session.save(csev_New);

                // Revision setzen, falls angegeben
                if (csev_Request.getMajorRevision() != null)
                    csev_New.setMajorRevision(csev_Request.getMajorRevision());
                if (csev_Request.getMinorRevision() != null)
                    csev_New.setMinorRevision(csev_Request.getMinorRevision());

                // CodeSystemConcept neu anlegen, falls angegeben
                if (csev_Request.getCodeSystemConcepts() != null) {
                    csc_Request = (CodeSystemConcept) csev_Request.getCodeSystemConcepts().toArray()[0];

                    csc_New = new CodeSystemConcept();
                    csc_New.setCodeSystemEntityVersionId(csev_New.getVersionId());

                    csc_New.setCode(csc_Request.getCode());
                    csc_New.setTerm(csc_Request.getTerm());
                    csc_New.setIsPreferred(csc_Request.getIsPreferred());
                    if (csc_Request.getMeaning() != null)
                        csc_New.setMeaning(csc_Request.getMeaning());
                    if (csc_Request.getHints() != null)
                        csc_New.setHints(csc_Request.getHints());
                    if (csc_Request.getDescription() != null)
                        csc_New.setDescription(csc_Request.getDescription());
                    if (csc_Request.getTermAbbrevation() != null
                            && csc_Request.getTermAbbrevation().length() > 0)
                        csc_New.setTermAbbrevation(csc_Request.getTermAbbrevation());

                    // CSConcept in SB speichern
                    hb_session.save(csc_New);

                    // CodeSystemConceptTranslation(s) anlegen, falls vorhanden
                    if (csc_Request.getCodeSystemConceptTranslations() != null) {
                        itCsct_Request = csc_Request.getCodeSystemConceptTranslations().iterator();
                        while (itCsct_Request.hasNext()) {
                            csct_Request = itCsct_Request.next();

                            csct_New = new CodeSystemConceptTranslation();

                            csct_New.setCodeSystemConcept(csc_New);
                            csct_New.setLanguageCd(csct_Request.getLanguageCd());
                            csct_New.setTerm(csct_Request.getTerm());
                            if (csct_Request.getTermAbbrevation() != null
                                    && csct_Request.getTermAbbrevation().length() > 0)
                                csct_New.setTermAbbrevation(csct_Request.getTermAbbrevation());

                            // in DB speichern
                            hb_session.save(csct_New);
                        }
                    }
                }

                if (csev_Request.getCodeSystemMetadataValues() != null) {
                    logger.debug("check for metadata changes...");

                    for (CodeSystemMetadataValue mv : csev_Request.getCodeSystemMetadataValues()) {
                        CodeSystemEntityVersion csev_db = csev_New;

                        if (mv.getParameterValue() != null && mv.getParameterValue().length() > 0) {
                            // add new md value
                            CodeSystemMetadataValue mv_db = new CodeSystemMetadataValue(mv.getParameterValue());
                            mv_db.setMetadataParameter(new MetadataParameter());
                            mv_db.getMetadataParameter().setId(mv.getMetadataParameter().getId());
                            mv_db.setCodeSystemEntityVersion(csev_db);
                            hb_session.save(mv_db);

                            logger.debug(
                                    "save metadata-value with mp-id: " + mv_db.getMetadataParameter().getId()
                                            + ", value: " + mv_db.getParameterValue());
                        }
                    }
                }

                cse_db.setCurrentVersionId(csev_New.getVersionId());
                hb_session.save(cse_db);
            }

            ////////////////// bestehende Version updaten:  der einfachheitshalber wird hier das csev.Objekt, dass gendet werden sollen ebenfalls als csev_New bezeichnet
            else {
                // original CSE aus DB laden                                  
                cse_db = (CodeSystemEntity) hb_session.load(CodeSystemEntity.class, cse_Request.getId());

                // Request CSEV, bentigt man fr die versionId
                csev_Request = (CodeSystemEntityVersion) cse_Request.getCodeSystemEntityVersions().toArray()[0];

                // "neues" CodeSystemEntityVersion-Objekt wird aus der DB geladen. Jetzt knnen die nderungen vorgenommen werden
                csev_New = (CodeSystemEntityVersion) hb_session.load(CodeSystemEntityVersion.class,
                        csev_Request.getVersionId());

                // Revision setzen, falls angegeben
                if (csev_Request.getMajorRevision() != null)
                    csev_New.setMajorRevision(csev_Request.getMajorRevision());
                if (csev_Request.getMinorRevision() != null)
                    csev_New.setMinorRevision(csev_Request.getMinorRevision());
                if (csev_Request.getIsLeaf() != null)
                    csev_New.setIsLeaf((csev_Request.getIsLeaf()));

                // CodeSystemConcept aus DB laden und anpassen
                if (csev_Request.getCodeSystemConcepts() != null) {
                    csc_Request = (CodeSystemConcept) csev_Request.getCodeSystemConcepts().toArray()[0];

                    // Aus DB laden
                    csc_New = (CodeSystemConcept) hb_session.load(CodeSystemConcept.class,
                            csc_Request.getCodeSystemEntityVersionId());

                    // nderungen speichern
                    if (csc_Request.getCode() != null && csc_Request.getCode().length() > 0)
                        csc_New.setCode(csc_Request.getCode());
                    if (csc_Request.getTerm() != null && csc_Request.getTerm().length() > 0)
                        csc_New.setTerm(csc_Request.getTerm());
                    if (csc_Request.getIsPreferred() != null)
                        csc_New.setIsPreferred(csc_Request.getIsPreferred());
                    if (csc_Request.getTermAbbrevation() != null)
                        csc_New.setTermAbbrevation(csc_Request.getTermAbbrevation());
                    if (csc_Request.getMeaning() != null)
                        csc_New.setMeaning(csc_Request.getMeaning());
                    if (csc_Request.getHints() != null)
                        csc_New.setHints(csc_Request.getHints());
                    if (csc_Request.getDescription() != null)
                        csc_New.setDescription(csc_Request.getDescription());

                    // CodeSystemConceptTranslation(s) anlegen, falls vorhanden
                    if (csc_Request.getCodeSystemConceptTranslations() != null) {
                        itCsct_Request = csc_Request.getCodeSystemConceptTranslations().iterator();
                        while (itCsct_Request.hasNext()) {
                            csct_Request = itCsct_Request.next();

                            //Delete
                            if (csct_Request.getId() != null && csct_Request.getLanguageCd() == null
                                    && csct_Request.getTerm() == null
                                    && csct_Request.getTermAbbrevation() == null
                                    && csct_Request.getDescription() == null) {

                                CodeSystemConceptTranslation csct_puffer = (CodeSystemConceptTranslation) hb_session
                                        .get(CodeSystemConceptTranslation.class, csct_Request.getId());
                                hb_session.delete(csct_puffer);
                            } else {

                                //Update
                                if (csct_Request.getId() != null) {

                                    csct_New = (CodeSystemConceptTranslation) hb_session
                                            .get(CodeSystemConceptTranslation.class, csct_Request.getId());
                                } else {
                                    //Wenn zustzlich neues csct => neu anlegen...
                                    csct_New = new CodeSystemConceptTranslation();
                                    csct_New.setCodeSystemConcept(csc_Request);
                                    csct_New.setTerm("");
                                    csct_New.setLanguageCd(null);
                                    hb_session.save(csct_New);
                                }

                                if (csct_Request.getLanguageCd() != null
                                        && csct_Request.getLanguageCd().length() > 0)
                                    csct_New.setLanguageCd(csct_Request.getLanguageCd());
                                if (csct_Request.getTerm() != null && csct_Request.getTerm().isEmpty() == false)
                                    csct_New.setTerm(csct_Request.getTerm());
                                if (csct_Request.getTermAbbrevation() != null)
                                    csct_New.setTermAbbrevation(csct_Request.getTermAbbrevation());

                                hb_session.merge(csct_New);
                            }
                        }
                    }
                }

                // metadata
                if (csev_Request.getCodeSystemMetadataValues() != null) {
                    logger.debug("check for metadata changes...");

                    for (CodeSystemMetadataValue mv : csev_Request.getCodeSystemMetadataValues()) {
                        CodeSystemEntityVersion csev_db = csev_New;
                        CodeSystemMetadataValue mv_db = null;

                        // check if exists
                        boolean mv_exists = false;
                        for (CodeSystemMetadataValue mv_db_loop : csev_db.getCodeSystemMetadataValues()) {
                            if (mv_db_loop.getMetadataParameter().getId().longValue() == mv
                                    .getMetadataParameter().getId()) {
                                mv_exists = true;
                                mv_db = mv_db_loop;
                                break;
                            }
                        }

                        if (mv_exists) {
                            if (mv.getParameterValue() == null || mv.getParameterValue().length() == 0) {
                                // delete existing md value
                                hb_session.delete(mv_db);
                                csev_db.getCodeSystemMetadataValues().remove(mv_db);
                                logger.debug("remove metadata-value with mp-id: "
                                        + mv_db.getMetadataParameter().getId() + ", value: "
                                        + mv_db.getParameterValue());
                            } else {
                                if (mv.getParameterValue() != null
                                        && mv.getParameterValue().equals(mv_db.getParameterValue()) == false) {
                                    // replace existing md value
                                    mv_db.setParameterValue(mv.getParameterValue());
                                    hb_session.update(mv_db);
                                    logger.debug("edit metadata-value with mp-id: "
                                            + mv_db.getMetadataParameter().getId() + ", value: "
                                            + mv_db.getParameterValue());
                                } else
                                    logger.debug("no need to change metadata-value with mp-id: "
                                            + mv_db.getMetadataParameter().getId() + ", value: "
                                            + mv_db.getParameterValue());
                            }
                        } else {
                            if (mv.getParameterValue() != null && mv.getParameterValue().length() > 0) {
                                // add new md value
                                mv_db = new CodeSystemMetadataValue(mv.getParameterValue());
                                mv_db.setMetadataParameter(new MetadataParameter());
                                mv_db.getMetadataParameter().setId(mv.getMetadataParameter().getId());
                                mv_db.setCodeSystemEntityVersion(csev_db);
                                hb_session.save(mv_db);

                                logger.debug("save metadata-value with mp-id: "
                                        + mv_db.getMetadataParameter().getId() + ", value: "
                                        + mv_db.getParameterValue());
                            }
                        }
                    }
                }

                // Nachdem die neuen Objekte angelegt oder die alten aktualisiert wurden, speichere CSE in DB
                cse_db.setCurrentVersionId(csev_New.getVersionId());
                hb_session.save(cse_db);
            }
            LastChangeHelper.updateLastChangeDate(true, csvId, hb_session);
        } catch (Exception e) {
            // Fehlermeldung an den Aufrufer weiterleiten
            response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR);
            response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
            response.getReturnInfos()
                    .setMessage("Fehler bei 'MaintainConcept', Hibernate: " + e.getLocalizedMessage());
            logger.error(response.getReturnInfos().getMessage());
        } finally {
            // Transaktion abschlieen
            if (csev_New.getVersionId() > 0 /*&& pv_New.getVersionId() > 0 && p_New.getId() > 0*/)
                hb_session.getTransaction().commit();
            else {
                logger.warn("[MaintainConcept.java] nderungen nicht erfolgreich");
                hb_session.getTransaction().rollback();
            }
            hb_session.close();
        }
        if (csev_New.getVersionId() > 0 /*&& pv_New.getVersionId() > 0 && p_New.getId() > 0*/) {
            // Status an den Aufrufer weitergeben
            response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO);
            response.getReturnInfos().setStatus(ReturnType.Status.OK);
            response.getReturnInfos().setMessage("Concept erfolgreich gendert. " + sCreateNewVersionMessage);
        }

    } catch (Exception e) {
        // Fehlermeldung an den Aufrufer weiterleiten
        response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR);
        response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
        response.getReturnInfos().setMessage("Fehler bei 'MaintainConcept': " + e.getLocalizedMessage());
        logger.error(response.getReturnInfos().getMessage());
    }
    return response;
}

From source file:de.fhdo.terminologie.ws.conceptAssociation.MaintainConceptAssociation.java

License:Apache License

/**
 * Verndert eine Beziehung zwischen 2 Konzepten.
 *
 * @param parameter/* ww  w.  j  a  va  2 s  . c om*/
 * @return
 */
public MaintainConceptAssociationResponseType MaintainConceptAssociation(
        MaintainConceptAssociationRequestType parameter, String ipAddress) {
    if (logger.isInfoEnabled())
        logger.info("====== MaintainConceptAssociation gestartet ======");

    // Return-Informationen anlegen
    MaintainConceptAssociationResponseType response = new MaintainConceptAssociationResponseType();
    response.setReturnInfos(new ReturnType());

    // Parameter prfen
    if (validateParameter(parameter, response) == false) {
        return response; // Fehler bei den Parametern
    }

    // Login-Informationen auswerten
    boolean loggedIn = false;
    AuthenticateInfos loginInfoType = null;
    if (parameter != null && parameter.getLoginToken() != null) {
        loginInfoType = Authorization.authenticate(ipAddress, parameter.getLoginToken());
        loggedIn = loginInfoType != null;
    }

    if (logger.isDebugEnabled())
        logger.debug("Benutzer ist eingeloggt: " + loggedIn);

    if (loggedIn == false) {
        // Benutzer muss fr diesen Webservice eingeloggt sein
        response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.WARN);
        response.getReturnInfos().setStatus(ReturnType.Status.OK);
        response.getReturnInfos().setMessage(
                "Sie mssen am Terminologieserver angemeldet sein, um diesen Service nutzen zu knnen.");
        return response;
    }

    try {
        long associationId = 0;

        // Hibernate-Block, Session ffnen
        org.hibernate.Session hb_session = HibernateUtil.getSessionFactory().openSession();
        hb_session.getTransaction().begin();

        // Neue CodeSystemEntityVersionAssociation
        CodeSystemEntityVersionAssociation cseva_New = parameter.getCodeSystemEntityVersionAssociation().get(0);
        CodeSystemEntityVersionAssociation cseva_db = new CodeSystemEntityVersionAssociation();

        try { // 2. Try-Catch-Block zum Abfangen von Hibernate-Fehlern 

            //Origianl CSEVA aus DB laden
            //TODO Prfen, ob Id vorhanden ist (Catch funktioniert nicht richtig, Fehler wird zu spt gefangen)
            try {
                cseva_db = (CodeSystemEntityVersionAssociation) hb_session
                        .load(CodeSystemEntityVersionAssociation.class, cseva_New.getId());
            } catch (ObjectNotFoundException e) {
                // Fehlermeldung an den Aufrufer weiterleiten
                response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.WARN);
                response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
                response.getReturnInfos()
                        .setMessage("Keine CodeSystemEntityVersionAssociation mit der angegeben ID vorhanden.");
                logger.error(response.getReturnInfos().getMessage());
            }

            // Beziehungen ndern                
            // codeSystemEntityVersionByCodeSystemEntityVersionIdX neu erstellen
            //cseva_db.setCodeSystemEntityVersionByCodeSystemEntityVersionId1(null); -> nicht mehr mglich!
            //cseva_db.setCodeSystemEntityVersionByCodeSystemEntityVersionId2(null); -> nicht mehr mglich!
            // codeSystemEntityVersionByCodeSystemEntityVersionIdX zuweisen -> nicht mehr mglich!
            //cseva_db.setCodeSystemEntityVersionByCodeSystemEntityVersionId1(new CodeSystemEntityVersion());
            //cseva_db.getCodeSystemEntityVersionByCodeSystemEntityVersionId1().setVersionId(cseva_New.getCodeSystemEntityVersionByCodeSystemEntityVersionId1().getVersionId());
            //cseva_db.setCodeSystemEntityVersionByCodeSystemEntityVersionId2(new CodeSystemEntityVersion());
            //cseva_db.getCodeSystemEntityVersionByCodeSystemEntityVersionId2().setVersionId(cseva_New.getCodeSystemEntityVersionByCodeSystemEntityVersionId2().getVersionId());
            // Attribute ndern
            // cseva_db.setLeftId(cseva_New.getLeftId()); -> nicht mehr mglich!
            //cseva_db.setAssociationKind(cseva_New.getAssociationKind()); -> nicht mehr mglich!
            // AssociationType ndern, falls angegeben
            if (cseva_New.getAssociationType() != null) {
                //cseva_db.getAssociationType().setCodeSystemEntityVersionId(cseva_New.getAssociationType().getCodeSystemEntityVersionId());
                cseva_db.setAssociationType(new AssociationType());
                cseva_db.getAssociationType().setCodeSystemEntityVersionId(
                        cseva_New.getAssociationType().getCodeSystemEntityVersionId());
            }

            if (cseva_New.getLeftId() != null && cseva_New.getLeftId() > 0) {
                if (cseva_New.getLeftId().longValue() == cseva_db
                        .getCodeSystemEntityVersionByCodeSystemEntityVersionId1().getVersionId().longValue()
                        || cseva_New.getLeftId().longValue() == cseva_db
                                .getCodeSystemEntityVersionByCodeSystemEntityVersionId2().getVersionId()
                                .longValue()) {
                    cseva_db.setLeftId(cseva_New.getLeftId());
                }
            }

            if (cseva_New.getAssociationKind() != null && cseva_New.getAssociationKind() > 0) {
                cseva_db.setAssociationKind(cseva_New.getAssociationKind());
            }

            cseva_db.setStatusDate(new Date());

            // prfen, ob AssociationTypeId auch eine Association ist
            if (hb_session.get(AssociationType.class,
                    cseva_db.getAssociationType().getCodeSystemEntityVersionId()) == null) {
                response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.WARN);
                response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
                response.getReturnInfos().setMessage(
                        "Sie mssen eine gltige ID fr ein AssociationType angeben. Das Konzept mit der ID '"
                                + cseva_db.getAssociationType().getCodeSystemEntityVersionId()
                                + "' ist kein AssociationType!");

                logger.info("ungltige ID fr AssociationType");
            } else {
                // Beziehung abspeichern
                hb_session.merge(cseva_db);
                associationId = cseva_db.getId();

                response.getReturnInfos().setCount(1);
            }
        } catch (Exception e) {
            // Fehlermeldung an den Aufrufer weiterleiten
            response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR);
            response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
            response.getReturnInfos().setMessage(
                    "Fehler bei 'MaintainConceptAssociation', Hibernate: " + e.getLocalizedMessage());
            logger.error(response.getReturnInfos().getMessage());
            LoggingOutput.outputException(e, this);
            e.printStackTrace();
        } finally {
            // Transaktion abschlieen
            if (associationId > 0) {
                hb_session.getTransaction().commit();
            } else {
                // nderungen nicht erfolgreich
                logger.warn("[MaintainConceptAssociation.java] nderungen nicht erfolgreich");
                hb_session.getTransaction().rollback();
            }
            hb_session.close();
        }
        if (associationId > 0) {
            // Status an den Aufrufer weitergeben
            response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO);
            response.getReturnInfos().setStatus(ReturnType.Status.OK);
            response.getReturnInfos().setMessage("CodeSystemEntityVersionAssociation erfolgreich gendert. ");
            logger.info(response.getReturnInfos().getMessage());
        }
    } catch (Exception e) {
        // Fehlermeldung an den Aufrufer weiterleiten
        response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR);
        response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
        response.getReturnInfos()
                .setMessage("Fehler bei 'MaintainConceptAssociation': " + e.getLocalizedMessage());
        logger.error(response.getReturnInfos().getMessage());
    }
    return response;
}

From source file:de.fhdo.terminologie.ws.conceptAssociation.UpdateConceptAssociationStatus.java

License:Apache License

public UpdateConceptAssociationStatusResponseType UpdateConceptAssociationStatus(
        UpdateConceptAssociationStatusRequestType parameter, org.hibernate.Session session, String ipAddress) {
    if (logger.isInfoEnabled())
        logger.info("====== UpdateConceptAssociationStatus gestartet ======");

    boolean createHibernateSession = (session == null);
    logger.debug("createHibernateSession: " + createHibernateSession);

    // Return-Informationen anlegen
    UpdateConceptAssociationStatusResponseType response = new UpdateConceptAssociationStatusResponseType();
    response.setReturnInfos(new ReturnType());

    // Parameter prfen
    if (validateParameter(parameter, response) == false) {
        return response; // Fehler bei den Parametern
    }/*from w ww  .  j a  v  a  2 s  .c  om*/

    // Login-Informationen auswerten (gilt fr jeden Webservice)
    boolean loggedIn = false;
    AuthenticateInfos loginInfoType = null;
    if (parameter != null && parameter.getLoginToken() != null) {
        loginInfoType = Authorization.authenticate(ipAddress, parameter.getLoginToken());
        loggedIn = loginInfoType != null;
    }

    // TODO Lizenzen prfen (?)

    if (logger.isDebugEnabled())
        logger.debug("Benutzer ist eingeloggt: " + loggedIn);

    if (loggedIn == false) {
        // Benutzer muss fr diesen Webservice eingeloggt sein
        response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.WARN);
        response.getReturnInfos().setStatus(ReturnType.Status.OK);
        response.getReturnInfos().setMessage(
                "Sie mssen am Terminologieserver angemeldet sein, um diesen Service nutzen zu knnen.");
        return response;
    }

    try {
        long associationId = 0;

        // Hibernate-Block, Session ffnen
        org.hibernate.Session hb_session = null;
        org.hibernate.Transaction tx = null;

        if (createHibernateSession) {
            hb_session = HibernateUtil.getSessionFactory().openSession();
            tx = hb_session.beginTransaction();
        } else {
            hb_session = session;
            //hb_session.getTransaction().begin();
        }

        try // 2. try-catch-Block zum Abfangen von Hibernate-Fehlern
        {
            CodeSystemEntityVersionAssociation association_param = parameter
                    .getCodeSystemEntityVersionAssociation();
            //long id = association_param.getId();

            logger.debug(
                    "change status for codeSystemEntityVersionAssociation id " + association_param.getId());

            CodeSystemEntityVersionAssociation association_db = (CodeSystemEntityVersionAssociation) hb_session
                    .get(CodeSystemEntityVersionAssociation.class, association_param.getId());
            association_db.setStatus(parameter.getCodeSystemEntityVersionAssociation().getStatus());
            association_db.setStatusDate(new Date());

            logger.debug("ID: " + association_db.getId() + ", left-id: " + association_db.getLeftId());

            hb_session.merge(association_db);

            if (tx != null)
                tx.commit();

            // Status an den Aufrufer weitergeben
            response.getReturnInfos().setCount(1);
            response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO);
            response.getReturnInfos().setStatus(ReturnType.Status.OK);
            response.getReturnInfos().setMessage("Relation status changed successfully.");
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();

            // Fehlermeldung an den Aufrufer weiterleiten
            response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR);
            response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
            response.getReturnInfos().setMessage(
                    "Error at 'UpdateConceptAssociationStatus', Hibernate: " + e.getLocalizedMessage());

            logger.error("Fehler bei 'UpdateConceptAssociationStatus', Hibernate: " + e.getLocalizedMessage());
            e.printStackTrace();
        } finally {
            if (createHibernateSession)
                hb_session.close();
        }

    } catch (Exception e) {
        // Fehlermeldung an den Aufrufer weiterleiten
        response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR);
        response.getReturnInfos().setStatus(ReturnType.Status.FAILURE);
        response.getReturnInfos()
                .setMessage("Error at 'UpdateConceptAssociationStatus': " + e.getLocalizedMessage());

        logger.error("Error at 'UpdateConceptAssociationStatus': " + e.getLocalizedMessage());
    }

    return response;
}

From source file:de.uniwue.info6.database.map.daos.DaoTools.java

License:Apache License

public T merge(T detachedInstance, Session session) {
    log.debug("merging T instance");
    try {//from   ww  w .  j a va 2  s .  com
        @SuppressWarnings("unchecked")
        T result = (T) session.merge(detachedInstance);
        log.debug("merge successful");
        return result;
    } catch (RuntimeException re) {
        log.error("merge failed", re);
        throw re;
    }
}

From source file:de.uzk.hki.da.action.QueueConnector.java

License:Open Source License

/**
 * XXX locking synchronized, against itself and against get object need audit
 * /*from  w  w  w . j a  v a  2  s .c  o  m*/
 * IMPORTANT NOTE: Fetch objects from queue opens a new session.
 *
 * @param status the status
 * @param workingStatus typically a numerical value with three digits, stored as string.
 * working status third digit typically is 2 by convention.
 * @param node the node
 * @return the job
 * @author Daniel M. de Oliveira
 */
@SuppressWarnings({ "unchecked", "unused" })
public Job fetchJobFromQueue(String status, String workingStatus, Node node, PreservationSystem pSystem) {
    Session session = HibernateUtil.openSession();
    session.beginTransaction();
    logger.trace("Fetch job for node name " + node.getName());
    List<Job> joblist = null;
    try {
        session.refresh(node);
        session.refresh(pSystem);

        joblist = session.createQuery("SELECT j FROM Job j LEFT JOIN j.obj as o where j.status=?1 and "
                + "j.responsibleNodeName=?2 and o.object_state IN (100, 50, 40) and o.orig_name!=?3 order by j.date_modified asc ")
                .setParameter("1", status).setParameter("2", node.getName())
                .setParameter("3", "integrationTest").setCacheable(false).setMaxResults(1).list();

        if ((joblist == null) || (joblist.isEmpty())) {
            logger.trace("no job found for status {}.", status);
            session.close();
            return null;
        }

        Job job = joblist.get(0);

        // To circumvent lazy initialization issues
        for (ConversionInstruction ci : job.getConversion_instructions()) {
        }
        for (Job j : job.getChildren()) {
        }
        for (Package p : job.getObject().getPackages()) {
            for (DAFile f : p.getFiles()) {
            }
            for (Event e : p.getEvents()) {
            }
        }
        // -
        logger.debug("fetched job with id {} and status {}", job.getId(), job.getStatus());

        job.setStatus(workingStatus);
        job.setDate_modified(String.valueOf(new Date().getTime() / 1000L));
        session.merge(job);
        session.getTransaction().commit();
        session.close();

        logger.debug("fetched job with id {} and set status to {}", job.getId(), job.getStatus());

    } catch (Exception e) {
        session.close();
        logger.error("Caught error in fetchJobFromQueue");

        throw new RuntimeException(e.getMessage(), e);
    }
    return joblist.get(0);
}

From source file:de.uzk.hki.da.model.JobNamedQueryDAO.java

License:Open Source License

/**
 * XXX locking synchronized, against itself and against get object need audit
 * /*from  w  ww . j av  a 2 s.c  o m*/
 * IMPORTANT NOTE: Fetch objects from queue opens a new session.
 *
 * @param status the status
 * @param workingStatus typically a numerical value with three digits, stored as string.
 * working status third digit typically is 2 by convention.
 * @param node the node
 * @return the job
 * @author Daniel M. de Oliveira
 */
@SuppressWarnings({ "unchecked", "unused" })
public Job fetchJobFromQueue(String status, String workingStatus, Node node) {
    Session session = HibernateUtil.openSession();
    session.beginTransaction();
    logger.trace("Fetch job for node name " + node.getName());
    List<Job> joblist = null;
    try {

        joblist = session.createQuery("SELECT j FROM Job j LEFT JOIN j.obj as o where j.status=?1 and "
                + "j.responsibleNodeName=?2 and o.object_state IN (100, 50, 40) and o.orig_name!=?3 order by j.date_modified asc ")
                .setParameter("1", status).setParameter("2", node.getName())
                .setParameter("3", "integrationTest").setCacheable(false).setMaxResults(1).list();

        if ((joblist == null) || (joblist.isEmpty())) {
            logger.trace("no job found for status {}.", status);
            session.close();
            return null;
        }

        Job job = joblist.get(0);

        // To circumvent lazy initialization issues
        for (ConversionInstruction ci : job.getConversion_instructions()) {
        }
        for (Job j : job.getChildren()) {
        }
        for (Package p : job.getObject().getPackages()) {
            for (DAFile f : p.getFiles()) {
            }
            for (Event e : p.getEvents()) {
            }
            for (Copy copy : p.getCopies()) {
            }
        }
        //-

        job.setStatus(workingStatus);
        job.setDate_modified(String.valueOf(new Date().getTime() / 1000L));
        session.merge(job);
        session.getTransaction().commit();
        session.close();

        logger.debug("Fetched job of object " + job.getObject().getIdentifier() + " +. Set job status to "
                + job.getStatus() + ".");

    } catch (Exception e) {
        session.close();
        logger.error("Caught error in fetchJobFromQueue");

        throw new RuntimeException(e.getMessage(), e);
    }
    return joblist.get(0);
}

From source file:DomainControllers.CtrlCasDusComprarEntrada.java

public void pagament(String dni, Integer codiB, String numCompte)
        throws pagamentNoAutoritzat, serveiNoDisponible {
    Showscom showscom = Showscom.getInstance();
    Integer cb = showscom.getCodiBanc();
    String nc = showscom.getNumeroCompte();
    FactoriaAdaptadores FA = FactoriaAdaptadores.getInstance();
    IBankServiceAdapter BS = FA.getBankServiceAdapter();

    Calendar cal = Calendar.getInstance();
    Date dAvui = cal.getTime();//  w  w  w .  j av a  2s. com
    boolean b = BS.pagament(dni, codiB, numCompte, preuE, cb, nc, dAvui);
    if (!b)
        throw new pagamentNoAutoritzat("El pagament no est autoritzat");

    FactoriaCtrl FC = FactoriaCtrl.getInstance();
    CtrlRepresentacio CR = FC.getCtrlRepresentacio();
    Representacio r = CR.getRepresentacio(nomLocalE, sessioE);

    if (b) {

        Configuration config = new Configuration();
        config.configure("hibernate.cfg.xml");
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(config.getProperties()).build();
        SessionFactory factory = config.buildSessionFactory(serviceRegistry);
        Session session = factory.openSession();

        session.beginTransaction();
        List<Entrada> l = session.createQuery("from Entrada").list();
        Integer size = l.size();
        String idEntrada = String.valueOf(size);
        Entrada e = new Entrada(idEntrada, dni, nombEspectadorsE, dataE, preuE, r, seientsE);
        session.saveOrUpdate(e);
        session.merge(r);
        ArrayList<SeientEnRepresentacio> SeientRes = new ArrayList<>(r.getSER());
        for (int i = 0; i < SeientRes.size(); ++i) {
            session.merge(SeientRes.get(i));
        }
        session.getTransaction().commit();
    }
}

From source file:edu.ku.brc.specify.conversion.SpecifyDBConverter.java

License:Open Source License

/**
 * Convert old Database to New //  w ww.j av a2  s. com
 * @param databaseNameSource name of an old database
 * @param databaseNameDest name of new DB
 * @throws Exception xx
 */
@SuppressWarnings("unchecked")
protected void convertDB(final String dbNameSource, final String dbNameDest) throws Exception {
    //System.setProperty(DBMSUserMgr.factoryName, "edu.ku.brc.dbsupport.MySQLDMBSUserMgr");

    AppContextMgr.getInstance().clear();

    boolean startfromScratch = true;
    boolean deleteMappingTables = false;

    System.out.println("************************************************************");
    System.out.println("From " + dbNameSource + " to " + dbNameDest);
    System.out.println("************************************************************");

    HibernateUtil.shutdown();

    DatabaseDriverInfo driverInfo = DatabaseDriverInfo.getDriver("MySQL");

    String oldConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
            dbNameSource, itUsrPwd.first, itUsrPwd.second, driverInfo.getName());

    String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
            dbNameDest, itUsrPwd.first, itUsrPwd.second, driverInfo.getName());

    MySQLDMBSUserMgr mysqlMgr = new MySQLDMBSUserMgr();
    if (mysqlMgr.connectToDBMS(itUsrPwd.first, itUsrPwd.second, hostName)) {
        if (!mysqlMgr.doesDBExists(dbNameDest)) {
            mysqlMgr.createDatabase(dbNameDest);
        }
    }
    mysqlMgr.close();

    // This will log us in and return true/false
    // This will connect without specifying a DB, which allows us to create the DB
    if (!UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbNameDest,
            newConnStr, itUsrPwd.first, itUsrPwd.second)) {
        log.error("Failed connection string: "
                + driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, dbNameDest,
                        itUsrPwd.first, itUsrPwd.second, driverInfo.getName()));
        throw new RuntimeException(
                "Couldn't login into [" + dbNameDest + "] " + DBConnection.getInstance().getErrorMsg());
    }

    log.debug("Preparing new database");
    frame.setDesc("Gather statistics from " + dbNameDest);
    frame.turnOffOverAll();
    frame.getProcessProgress().setIndeterminate(true);

    UIHelper.centerAndShow(frame);

    DBConnection oldDB = DBConnection.createInstance(driverInfo.getDriverClassName(),
            driverInfo.getDialectClassName(), dbNameDest, oldConnStr, itUsrPwd.first, itUsrPwd.second);

    Connection oldDBConn = oldDB.createConnection();
    Connection newDBConn = DBConnection.getInstance().createConnection();

    if (!isOldDBOK(oldDBConn)) {
        return;
    }

    boolean doUserAgents = false;
    if (doUserAgents) {
        fixupUserAgents(newDBConn);
        return;
    }

    boolean doObs = false;
    if (doObs) {
        ConvertMiscData.convertObservations(oldDBConn, newDBConn, 3);
        return;
    }

    boolean doFixLoanPreps = false;
    if (doFixLoanPreps) {
        // These really aren't working correctly
        fixLoanPreps(oldDBConn, newDBConn);
        fixGiftPreps(oldDBConn, newDBConn);
        return;
    }

    boolean doGetLastEditedByNamesHashSet = false;
    if (doGetLastEditedByNamesHashSet) {
        getOldEditedByStrings(oldDBConn);
        //return;
    }

    boolean doFix = false;
    if (doFix) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        DuplicateCollectingEvents dce = new DuplicateCollectingEvents(oldDBConn, newDBConn);
        //dce.performMaint(true);
        dce.fixCollectorsForCollectingEvents2();
        //dce.removeUnneededCEs();
        return;
    }

    boolean doCEAttrFIx = false;
    if (doCEAttrFIx) {
        frame.setDesc("Fixing Scope....");
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        convLogger.initialize(convOutputPath, dbNameDest);
        TableWriter tblWriter = convLogger.getWriter("ScopeUpdater.html", "Updating Scope Summary");
        ConvScopeFixer convScopeFixer = new ConvScopeFixer(oldDBConn, newDBConn, dbNameDest, tblWriter);
        convScopeFixer.doFixTables();
        oldDBConn.close();
        newDBConn.close();
        System.exit(0);
    }

    boolean doImagesToWebLinks = false;
    if (doImagesToWebLinks) {
        frame.setDesc("Fixing Scope....");
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        ConvertMiscData.convertImagesToWebLinks(oldDBConn, newDBConn);
        oldDBConn.close();
        newDBConn.close();
        System.exit(0);
    }

    if (!System.getProperty("user.name").equals("rods")) {
        OldDBStatsDlg dlg = new OldDBStatsDlg(oldDBConn);
        frame.setVisible(false);

        dlg.setVisible(true);
        if (dlg.isCancelled()) {
            oldDBConn.close();
            newDBConn.close();
            System.exit(0);
        }
        doFixCollectors = dlg.doFixAgents();
    }

    startTime = System.currentTimeMillis();

    convLogger.initialize(convOutputPath, dbNameDest);
    convLogger.setIndexTitle(dbNameDest + " Conversion "
            + (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(Calendar.getInstance().getTime()));

    /*if (true)
    {
    TableWriter tDSTblWriter = convLogger.getWriter("TableDataSummary.html", "Table Data Summary", true);
    TableDataChecker tblDataChecker = new TableDataChecker(oldDBConn);
    tblDataChecker.createHTMLReport(tDSTblWriter);
    tDSTblWriter.close();
    return;
    }*/

    boolean doCheckLastEditedByNamesHashSet = false;
    if (doCheckLastEditedByNamesHashSet) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        IdMapperMgr.getInstance().addTableMapper("agent", "AgentID", false);

        convLogger.initialize(convOutputPath, dbNameDest);
        convLogger.setIndexTitle(dbNameDest + " Conversion "
                + (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(Calendar.getInstance().getTime()));
        conversion = new GenericDBConversion(oldDBConn, newDBConn, dbNameSource, convLogger);
        conversion.checkCreatedModifiedByAgents();
        //conversion.fixCreatedModifiedByAgents(itUsrPwd.first, itUsrPwd.second, dbNameSource);
        return;
    }

    boolean doKUINVP = StringUtils.contains(dbNameDest, "kuinvp4_dbo");
    boolean doCUPaleo = StringUtils.contains(dbNameDest, "cupaleo");
    boolean ndgs = StringUtils.contains(dbNameDest, "ndgs");

    if (doCUPaleo) {
        ConvertMiscData.moveHabitatToStratSp5(oldDBConn);
    }

    boolean doFix2 = false;
    if (doFix2) {
        ConvertMiscData.convertMethodFromStratGTP(oldDBConn, newDBConn);
        return;
    }

    frame.setSize(500, frame.getPreferredSize().height);

    frame.setDesc("Fixing NULL Timestamps for conversion.");
    UIHelper.centerAndShow(frame);

    fixOldTablesTimestamps(oldDBConn);

    frame.turnOnOverAll();

    conversion = new GenericDBConversion(oldDBConn, newDBConn, dbNameSource, convLogger);
    GenericDBConversion.CollectionResultType collInitStatus = conversion.initialize();
    if (collInitStatus == GenericDBConversion.CollectionResultType.eError) {
        oldDBConn.close();
        newDBConn.close();
        throw new RuntimeException("There are no collections!");

    } else if (collInitStatus == GenericDBConversion.CollectionResultType.eCancel) {
        oldDBConn.close();
        newDBConn.close();
        System.exit(0);
    }

    boolean doFixDisciplineIntoCEs = false;
    if (doFixDisciplineIntoCEs) {
        doSetDisciplineIntoCEs(oldDBConn, newDBConn);
        return;
    }

    boolean doFixDisciplineIntoLocalities = false;
    if (doFixDisciplineIntoLocalities) {
        doSetDisciplineIntoLocalities(oldDBConn, newDBConn);
        return;
    }

    boolean doFix3 = false;
    if (doFix3) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        AgentConverter agentConverter = new AgentConverter(conversion, IdMapperMgr.getInstance(), false);
        agentConverter.fixMissingAddrsFromConv();
        oldDBConn.close();
        newDBConn.close();
        return;
    }

    boolean doFix4 = false;
    if (doFix4) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        ConvertMiscData.moveStratFieldsToCEA(oldDBConn, newDBConn);
        oldDBConn.close();
        newDBConn.close();
        return;
    }

    boolean doFix5 = false;
    if (doFix5) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        ConvertMiscData.moveGTPNameToCEText1(oldDBConn, newDBConn);
        oldDBConn.close();
        newDBConn.close();
        return;
    }

    // For KU Vert Paleo
    boolean doFix6 = false;
    if (doFix6) {
        ConvertTaxonHelper.fixTaxonomicUnitType(oldDBConn);

        oldDBConn.close();
        newDBConn.close();
        return;
    }

    boolean doFix7 = false;
    if (doFix7) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        ConvertMiscData.moveGTPNameToLocalityVer(oldDBConn, newDBConn);
        oldDBConn.close();
        newDBConn.close();
        return;
    }

    String sql = "SELECT count(*) FROM (SELECT ce.CollectingEventID, Count(ce.CollectingEventID) as cnt FROM collectingevent AS ce "
            + "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID "
            + "Inner Join collectionobjectcatalog AS cc ON co.CollectionObjectID = cc.CollectionObjectCatalogID "
            + "WHERE ce.BiologicalObjectTypeCollectedID <  21 "
            + "GROUP BY ce.CollectingEventID) T1 WHERE cnt > 1";

    /*if (true)
    {
    IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
            
    //convLogger.initialize(dbNameDest);
    //convLogger.setIndexTitle(dbNameDest + " Conversion "+(new SimpleDateFormat("yyy-MM-dd hh:mm:ss")).format(Calendar.getInstance().getTime()));
            
    TableWriter tblWriter = convLogger.getWriter("ScopeUpdater.html", "Updating Scope Summary");
    ConvScopeFixer convScopeFixer = new ConvScopeFixer(oldDBConn, newDBConn, dbNameDest, tblWriter);
    convScopeFixer.doFixTables();
    convScopeFixer.checkTables();
    return;
    }*/

    int numCESharing = BasicSQLUtils.getCountAsInt(oldDBConn, sql);

    String msg = String.format(
            "Will this Collection share Collecting Events?\nThere are %d Collecting Events that are sharing now.\n(Sp5 was %ssharing them.)",
            numCESharing, isUsingEmbeddedCEsInSp5() ? "NOT " : "");
    boolean isSharingCollectingEvents = UIHelper.promptForAction("Share", "Adjust CEs",
            "Duplicate Collecting Events", msg);
    boolean doingOneToOneForColObjToCE = !isSharingCollectingEvents;

    conversion.setSharingCollectingEvents(isSharingCollectingEvents);

    /*if (false) 
    {
    createTableSummaryPage();
    return;
    }*/

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            conversion.setFrame(frame);
            frame.setDesc("Building Database Schema...");
            frame.adjustProgressFrame();
            frame.getProcessProgress().setIndeterminate(true);
            frame.getProcessProgress().setString("");
            UIHelper.centerAndShow(frame);

        }
    });

    if (startfromScratch) {
        boolean doBuild = true;
        File file = new File("blank.sql");
        System.err.println(file.getAbsolutePath());
        if (file.exists()) {
            DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
            if (dbMgr.connect(itUsrPwd.first, itUsrPwd.second, "localhost", dbNameDest)) {
                if (dbMgr.doesDBExists(dbNameDest)) {
                    dbMgr.dropDatabase(dbNameDest);
                }

                if (dbMgr.createDatabase(dbNameDest)) {
                    doBuild = false;
                }

                dbMgr.close();
            }

            MySQLBackupService bkService = new MySQLBackupService();

            doBuild = !bkService.doRestore(file.getAbsolutePath(), "/usr/local/mysql/bin/mysql", dbNameDest,
                    itUsrPwd.first, itUsrPwd.second);
        }

        if (doBuild) {
            DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
            if (dbMgr.connect(itUsrPwd.first, itUsrPwd.second, "localhost", dbNameDest)) {
                if (dbMgr.doesDBExists(dbNameDest)) {
                    dbMgr.dropDatabase(dbNameDest);
                }

                if (dbMgr.createDatabase(dbNameDest)) {
                    doBuild = false;
                }

                dbMgr.close();
            }

            log.debug("Starting from scratch and generating the schema");
            SpecifySchemaGenerator.generateSchema(driverInfo, hostName, dbNameDest, itUsrPwd.first,
                    itUsrPwd.second);
        }
    }

    log.debug("Preparing new database: completed");

    setSession(HibernateUtil.getNewSession());
    IdMapperMgr idMapperMgr = null;
    SpecifyUser specifyUser = null;

    try {
        GenericDBConversion.setShouldCreateMapTables(startfromScratch);
        GenericDBConversion.setShouldDeleteMapTables(deleteMappingTables);

        frame.setOverall(0, OVERALL_STEPS);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                UIHelper.centerAndShow(frame);
            }
        });

        boolean doConvert = true;
        if (doConvert) {
            BuildSampleDatabase.createSpecifySAUser(hostName, itUsrPwd.first, itUsrPwd.second,
                    masterUsrPwd.first, masterUsrPwd.second, dbNameDest);

            idMapperMgr = IdMapperMgr.getInstance();
            Connection oldConn = conversion.getOldDBConnection();
            Connection newConn = conversion.getNewDBConnection();
            if (oldConn == null || newConn == null) {
                log.error(
                        "One of the DB connections is null.  Cannot proceed.  Check your DB install to make sure both DBs exist.");
                System.exit(-1);
            }

            idMapperMgr.setDBs(oldConn, newConn);

            // NOTE: Within BasicSQLUtils the connection is for removing tables and records
            BasicSQLUtils.setDBConnection(conversion.getNewDBConnection());

            /*if (false)
            {
            addStorageTreeFomrXML(true);
            return;
            }*/

            //---------------------------------------------------------------------------------------
            //-- Create basic set of information.
            //---------------------------------------------------------------------------------------
            conversion.doInitialize();

            boolean doAll = true;

            if (startfromScratch) {
                BasicSQLUtils.deleteAllRecordsFromTable(conversion.getNewDBConnection(), "agent",
                        BasicSQLUtils.myDestinationServerType);
                BasicSQLUtils.deleteAllRecordsFromTable(conversion.getNewDBConnection(), "address",
                        BasicSQLUtils.myDestinationServerType);
            }
            conversion.initializeAgentInfo(startfromScratch);

            frame.setDesc("Mapping Tables.");
            log.info("Mapping Tables.");
            boolean mapTables = true;
            if (mapTables) {
                // Ignore these field names from new table schema when mapping OR
                // when mapping IDs
                BasicSQLUtils.setFieldsToIgnoreWhenMappingIDs(
                        new String[] { "MethodID", "RoleID", "CollectionID", "ConfidenceID", "TypeStatusNameID",
                                "ObservationMethodID", "StatusID", "TypeID", "ShipmentMethodID", "RankID",
                                "DirectParentRankID", "RequiredParentRankID", "MediumID" });
                conversion.mapIds();
                BasicSQLUtils.setFieldsToIgnoreWhenMappingIDs(null);
            }
            //GenericDBConversion.setShouldCreateMapTables(startfromScratch);

            frame.incOverall();

            Integer institutionId = conversion.createInstitution("Natural History Museum");
            if (institutionId == null) {
                UIRegistry.showError("Problem with creating institution, the Id came back null");
                System.exit(0);
            }

            conversion.convertDivision(institutionId);
            frame.incOverall();

            Agent userAgent = null;
            if (startfromScratch) {
                String username = "testuser";
                String title = "Mr.";
                String firstName = "Test";
                String lastName = "User";
                String midInit = "C";
                String abbrev = "tcu";
                String email = "testuser@ku.edu";
                String userType = SpecifyUserTypes.UserType.Manager.toString();
                String password = "testuser";

                Transaction trans = getSession().beginTransaction();

                //BasicSQLUtils.deleteAllRecordsFromTable(newConn, "usergroup", BasicSQLUtils.myDestinationServerType);
                BasicSQLUtils.deleteAllRecordsFromTable(newConn, "specifyuser",
                        BasicSQLUtils.myDestinationServerType);
                //SpPrincipal userGroup = createUserGroup("admin2");

                Criteria criteria = getSession().createCriteria(Agent.class);
                criteria.add(Restrictions.eq("lastName", lastName));
                criteria.add(Restrictions.eq("firstName", firstName));

                List<?> list = criteria.list();
                if (list != null && list.size() == 1) {
                    userAgent = (Agent) list.get(0);
                } else {
                    userAgent = createAgent(title, firstName, midInit, lastName, abbrev, email);
                }

                Institution institution = (Institution) getSession().createQuery("FROM Institution").list()
                        .get(0);

                String encrypted = Encryption.encrypt(password, password);
                specifyUser = createAdminGroupAndUser(getSession(), institution, null, username, email,
                        encrypted, userType);
                specifyUser.addReference(userAgent, "agents");

                getSession().saveOrUpdate(institution);

                userAgent.setDivision(AppContextMgr.getInstance().getClassObject(Division.class));
                getSession().saveOrUpdate(userAgent);

                trans.commit();
                getSession().flush();

            } else {
                specifyUser = (SpecifyUser) getSession().createCriteria(SpecifyUser.class).list().get(0);
                userAgent = specifyUser.getAgents().iterator().next();

                AppContextMgr.getInstance().setClassObject(SpecifyUser.class, specifyUser);
                // XXX Works for a Single Convert
                Collection collection = (Collection) getSession().createCriteria(Collection.class).list()
                        .get(0);
                AppContextMgr.getInstance().setClassObject(Collection.class, collection);
            }

            /////////////////////////////////////////////////////////////
            // Really need to create or get a proper Discipline Record
            /////////////////////////////////////////////////////////////
            TableWriter taxonTblWriter = convLogger.getWriter("FullTaxon.html", "Taxon Conversion");
            ConvertTaxonHelper taxonHelper = new ConvertTaxonHelper(oldDBConn, newDBConn, dbNameDest, frame,
                    taxonTblWriter, conversion, conversion);
            taxonHelper.createTaxonIdMappings();
            taxonHelper.doForeignKeyMappings();

            frame.setDesc("Converting CollectionObjectDefs.");
            log.info("Converting CollectionObjectDefs.");
            boolean convertDiscipline = doAll;
            if (convertDiscipline) {
                if (!conversion.convertCollectionObjectTypes(specifyUser.getSpecifyUserId())) {
                    return;
                }
            } else {
                idMapperMgr.addTableMapper("CatalogSeriesDefinition", "CatalogSeriesDefinitionID");
                idMapperMgr.addTableMapper("CollectionObjectType", "CollectionObjectTypeID");
            }
            frame.incOverall();

            frame.setDesc("Converting Agents.");
            log.info("Converting Agents.");

            AgentConverter agentConverter = new AgentConverter(conversion, idMapperMgr, startfromScratch);

            // This MUST be done before any of the table copies because it
            // creates the IdMappers for Agent, Address and more importantly AgentAddress
            // NOTE: AgentAddress is actually mapping from the old AgentAddress table to the new Agent table
            boolean copyAgentAddressTables = doAll;
            if (copyAgentAddressTables) {
                log.info("Calling - convertAgents");

                agentConverter.convertAgents(doFixCollectors);

            } else {
                idMapperMgr.addTableMapper("agent", "AgentID");
                idMapperMgr.addTableMapper("agentaddress", "AgentAddressID");
            }
            frame.incOverall();

            frame.setDesc("Mapping Agent Tables.");
            log.info("MappingAgent Tables.");
            if (mapTables) {
                // Ignore these field names from new table schema when mapping OR when mapping IDs
                BasicSQLUtils.setFieldsToIgnoreWhenMappingIDs(
                        new String[] { "MethodID", "RoleID", "CollectionID", "ConfidenceID", "TypeStatusNameID",
                                "ObservationMethodID", "StatusID", "TypeID", "ShipmentMethodID", "RankID",
                                "DirectParentRankID", "RequiredParentRankID", "MediumID" });
                conversion.mapAgentRelatedIds();
                BasicSQLUtils.setFieldsToIgnoreWhenMappingIDs(null);
            }
            frame.incOverall();

            TableWriter gtpTblWriter = convLogger.getWriter("GTP.html", "Geologic Time Period");
            StratToGTP stratToGTP = doCUPaleo || doKUINVP || ndgs
                    ? new StratToGTP(oldDBConn, newDBConn, dbNameDest, gtpTblWriter, conversion)
                    : null;

            frame.setDesc("Converting Geography");
            log.info("Converting Geography");
            boolean doGeography = doAll;
            if (!dbNameDest.startsWith("accessions") && doGeography) {
                GeographyTreeDef treeDef = conversion.createStandardGeographyDefinitionAndItems(true);
                conversion.convertGeography(treeDef, null, true);
            }
            frame.incOverall();

            frame.setDesc("Converting Geologic Time Period.");
            log.info("Converting Geologic Time Period.");
            // GTP needs to be converted here so the stratigraphy conversion can use the IDs
            boolean doGTP = doAll;
            if (doGTP) {
                if (stratToGTP != null) {
                    if (doCUPaleo) {
                        stratToGTP.createGTPTreeDef();
                    } else if (doKUINVP) {
                        stratToGTP.createGTPTreeDefKUINVP();
                    } else if (ndgs) {
                        stratToGTP.createGTPTreeDefNDGS();
                    }
                } else {
                    GeologicTimePeriodTreeDef treeDef = conversion.convertGTPDefAndItems(conversion.isPaleo());
                    conversion.convertGTP(gtpTblWriter, treeDef, conversion.isPaleo());
                }
            } else {
                idMapperMgr.addTableMapper("geologictimeperiod", "GeologicTimePeriodID");
                idMapperMgr.mapForeignKey("Stratigraphy", "GeologicTimePeriodID", "GeologicTimePeriod",
                        "GeologicTimePeriodID");
            }
            frame.incOverall();

            frame.setDesc("Converting Taxonomy");
            log.info("Converting Taxonomy");
            boolean doTaxonomy = doAll;
            if (doTaxonomy) {
                BasicSQLUtils.setTblWriter(taxonTblWriter);
                taxonHelper.doConvert();
                //taxonHelper.convertTaxonCitationToTaxonImage();
                BasicSQLUtils.setTblWriter(null);
            }
            frame.incOverall();

            //-------------------------------------------------------------------------------
            // Get the Discipline Objects and put them into the CollectionInfo Objects
            //-------------------------------------------------------------------------------
            //conversion.loadDisciplineObjects();

            conversion.convertHabitat();

            frame.setDesc("Converting Determinations Records");
            log.info("Converting Determinations Records");
            boolean doDeterminations = doAll;
            if (doDeterminations) {
                frame.incOverall();
                conversion.convertDeterminationRecords();// ZZZ 
            } else {
                frame.incOverall();
            }
            frame.incOverall();

            frame.setDesc("Copying Tables");
            log.info("Copying Tables");
            boolean copyTables = doAll;
            if (copyTables) {
                boolean doBrief = false;
                conversion.copyTables(doBrief);
            }

            frame.incOverall();

            conversion.updateHabitatIds();

            frame.setDesc("Converting Locality");
            log.info("Converting Locality");

            boolean doLocality = doAll;
            if (!dbNameDest.startsWith("accessions") && (doGeography || doLocality)) {
                conversion.convertLocality();
                frame.incOverall();

            } else {
                frame.incOverall();
                frame.incOverall();
            }

            frame.setDesc("Converting DeaccessionCollectionObject");
            log.info("Converting DeaccessionCollectionObject");
            boolean doDeaccessionCollectionObject = doAll;
            if (doDeaccessionCollectionObject) {
                conversion.convertDeaccessionCollectionObject();
            }
            frame.incOverall();

            frame.setDesc("Converting Preparations");
            log.info("Converting Preparations");
            boolean doCollectionObjects = doAll;
            if (doCollectionObjects) {
                if (true) {
                    Session session = HibernateUtil.getCurrentSession();
                    try {
                        // Get a HashMap of all the PrepTypes for each Collection
                        Hashtable<Integer, Map<String, PrepType>> collToPrepTypeHash = new Hashtable<Integer, Map<String, PrepType>>();
                        Query q = session.createQuery("FROM Collection");
                        for (Object dataObj : q.list()) {
                            Collection collection = (Collection) dataObj;
                            Map<String, PrepType> prepTypeMap = conversion
                                    .createPreparationTypesFromUSys(collection); // Hashed by PrepType's Name

                            PrepType miscPT = prepTypeMap.get("misc");
                            if (miscPT != null) {
                                prepTypeMap.put("n/a", miscPT);
                            } else {
                                miscPT = prepTypeMap.get("Misc");
                                if (miscPT != null) {
                                    prepTypeMap.put("n/a", miscPT);
                                } else {
                                    log.error("******************************* Couldn't find 'Misc' PrepType!");
                                }
                            }
                            // So Cache a Map of PrepTYpes for each Collection
                            collToPrepTypeHash.put(collection.getCollectionId(), prepTypeMap);
                        }
                        conversion.convertPreparationRecords(collToPrepTypeHash);// ZZZ 

                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }

                frame.setDesc("Converting Loan Records");
                log.info("Converting Loan Records");
                boolean doLoanPreparations = doAll;
                if (doLoanPreparations) {
                    conversion.convertLoanRecords(false); // Loans
                    conversion.convertLoanAgentRecords(false);// Loans
                    conversion.convertLoanPreparations();

                    frame.setDesc("Converting Gift Records");
                    log.info("Converting Gift Records");
                    conversion.convertLoanAgentRecords(true); // Gifts
                    conversion.convertLoanRecords(true); // Gifts
                    conversion.convertGiftPreparations();
                    frame.incOverall();

                } else {
                    frame.incOverall();
                }

                // Arg1 - Use Numeric Catalog Number
                // Arg2 - Use the Prefix from Catalog Series
                frame.setDesc("Converting CollectionObjects Records");
                log.info("Converting CollectionObjects Records");
                conversion.convertCollectionObjects(true, false);
                frame.incOverall();

            } else {
                frame.incOverall();
                frame.incOverall();
            }

            conversion.updateBioLogicalObjAttrIds();// ZZZ 
            conversion.updatePrepAttrIds();// ZZZ 

            conversion.convertHostTaxonId();

            if (getSession() != null) {
                getSession().close();
                setSession(null);
            }

            setSession(HibernateUtil.getNewSession());

            if (stratToGTP != null) {
                if (doCUPaleo) {
                    stratToGTP.convertStratToGTP();
                } else if (doKUINVP) {
                    stratToGTP.convertStratToGTPKUIVP();

                } else if (ndgs) {
                    stratToGTP.convertStratToGTPNDGS();
                }
            }

            frame.setDesc("Converting Stratigraphy");
            log.info("Converting Stratigraphy");
            boolean doStrat = true;
            if (doStrat) {
                TableWriter tblWriter = convLogger.getWriter("FullStrat.html", "Straigraphy Conversion");
                if (stratToGTP != null) {
                    if (doCUPaleo || ndgs) {
                        stratToGTP.convertStrat(tblWriter, conversion.isPaleo(), doCUPaleo);

                    } else if (doKUINVP) {
                        stratToGTP.convertStratKUINVP(tblWriter, conversion.isPaleo());
                    }
                } else {
                    conversion.convertStrat(tblWriter, conversion.isPaleo());
                }
            }

            //-------------------------------------------
            // Get Discipline and Collection
            //-------------------------------------------

            frame.incOverall();

            if (getSession() != null) {
                getSession().close();
                setSession(null);
            }

            boolean status = false;
            Institution institution = null;
            Division division = null;
            Collection collection = null;
            Discipline dscp = null;
            Session localSession = HibernateUtil.getNewSession();
            Session cachedCurrentSession = getSession();
            setSession(null);
            try {
                if (conversion.getCurDisciplineID() == null) {
                    List<?> list = localSession.createQuery("FROM Discipline").list();
                    dscp = (Discipline) list.get(0);

                } else {
                    log.debug("Loading Discipline with Id[" + conversion.getCurDisciplineID() + "]");
                    List<?> list = localSession
                            .createQuery("FROM Discipline WHERE id = " + conversion.getCurDisciplineID())
                            .list();
                    dscp = (Discipline) list.get(0);
                }
                AppContextMgr.getInstance().setClassObject(Discipline.class, dscp);

                if (dscp.getCollections().size() == 1) {
                    collection = dscp.getCollections().iterator().next();
                }

                if (collection == null) {
                    if (conversion.getCurCollectionID() == null || conversion.getCurCollectionID() == 0) {
                        List<?> list = localSession.createQuery("FROM Collection").list();
                        collection = (Collection) list.get(0);

                    } else {
                        String hsql = "FROM Collection WHERE id = " + conversion.getCurCollectionID();
                        log.info(hsql);
                        List<?> list = localSession.createQuery(hsql).list();
                        if (list == null || list.size() == 0) {
                            UIRegistry.showError("Couldn't find the Collection record [" + hsql + "]");
                        }
                        collection = (Collection) list.get(0);
                    }
                }

                division = dscp.getDivision();
                localSession.lock(division, LockMode.NONE);
                institution = division.getInstitution();
                localSession.lock(institution, LockMode.NONE);
                institution.getDivisions().size();

                AppContextMgr.getInstance().setClassObject(Collection.class, collection);
                AppContextMgr.getInstance().setClassObject(Division.class, division);
                AppContextMgr.getInstance().setClassObject(Institution.class, institution);

                if (doFixCollectors) {
                    agentConverter.fixupForCollectors(division, dscp);
                }

                setSession(localSession);

                try {
                    for (CollectionInfo collInfo : CollectionInfo.getCollectionInfoList(oldDBConn, true)) {
                        if (collInfo.getCollectionId() == null) {
                            log.error("CollectionID: was null for " + collInfo.getCatSeriesName());
                            continue;
                        }
                        List<?> list = localSession
                                .createQuery("FROM Collection WHERE id = " + collInfo.getCollectionId()).list();

                        List<Collection> tmpCollList = (List<Collection>) list;
                        Collection tmpCollection = tmpCollList.get(0);

                        // create the standard user groups for this collection
                        Map<String, SpPrincipal> groupMap = createStandardGroups(localSession, tmpCollection);

                        // add the administrator as a Collections Manager in this group
                        specifyUser.addUserToSpPrincipalGroup(
                                groupMap.get(SpecifyUserTypes.UserType.Manager.toString()));

                        Transaction trans = localSession.beginTransaction();

                        for (SpPrincipal prin : groupMap.values()) {
                            localSession.saveOrUpdate(prin);
                        }

                        localSession.saveOrUpdate(specifyUser);

                        trans.commit();

                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                status = true;

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            localSession.close();

            localSession = HibernateUtil.getNewSession();
            setSession(localSession);

            specifyUser = (SpecifyUser) localSession.merge(specifyUser);

            division = (Division) localSession.createQuery("FROM Division WHERE id = " + division.getId())
                    .list().iterator().next();
            institution = (Institution) localSession
                    .createQuery("FROM Institution WHERE id = " + institution.getId()).list().iterator().next();
            collection = (Collection) localSession
                    .createQuery("FROM Collection WHERE id = " + collection.getId()).list().iterator().next();

            AppContextMgr.getInstance().setClassObject(Collection.class, collection);
            AppContextMgr.getInstance().setClassObject(Division.class, division);
            AppContextMgr.getInstance().setClassObject(Institution.class, institution);

            dscp = (Discipline) localSession.createQuery("FROM Discipline WHERE id = " + dscp.getId()).list()
                    .iterator().next();
            AppContextMgr.getInstance().setClassObject(Discipline.class, dscp);

            localSession.flush();

            setSession(cachedCurrentSession);

            frame.setDesc("Converting USYS Tables.");
            log.info("Converting USYS Tables.");
            boolean copyUSYSTables = doAll;
            if (copyUSYSTables) {
                if (status) {
                    BasicSQLUtils.deleteAllRecordsFromTable("picklist", BasicSQLUtils.myDestinationServerType);
                    BasicSQLUtils.deleteAllRecordsFromTable("picklistitem",
                            BasicSQLUtils.myDestinationServerType);

                    for (Collection collectionObj : (List<Collection>) localSession
                            .createQuery("FROM Collection").list()) {
                        log.debug("Loading PickLists for Collection [" + collectionObj.getCollectionName()
                                + "] id[" + collectionObj.getId() + "]");

                        conversion.convertUSYSTables(localSession, collectionObj);

                        frame.setDesc("Creating PickLists from XML.");

                        BuildSampleDatabase.createPickLists(localSession, null, true, collectionObj);

                        BuildSampleDatabase.createPickLists(localSession, collection.getDiscipline(), true,
                                collectionObj);
                    }

                } else {
                    log.error("STATUS was FALSE for PickList creation!");
                }

                frame.incOverall();

            } else {
                frame.incOverall();
            }

            if (localSession != null) {
                localSession.close();
            }

            frame.incOverall();

            doSetDisciplineIntoCEs(oldDBConn, newDBConn);

            frame.setDesc("Fixing Preferred Taxon");

            // MySQL Only ???
            sql = "UPDATE determination SET PreferredTaxonID = CASE WHEN "
                    + "(SELECT AcceptedID FROM taxon WHERE taxon.TaxonID = determination.TaxonID) IS NULL "
                    + "THEN determination.TaxonID ELSE (SELECT AcceptedID FROM taxon WHERE taxon.TaxonID = determination.TaxonID) END";
            System.out.println(sql);
            BasicSQLUtils.setSkipTrackExceptions(true);
            BasicSQLUtils.update(sql);

            frame.incOverall();

            ShipmentConverter shipmentConv = new ShipmentConverter(oldDBConn, newDBConn);
            shipmentConv.fixup();

            //------------------------------------------------
            // Localize Schema and make form fields visible
            //------------------------------------------------
            frame.setDesc("Localizing the Schema");
            conversion.doLocalizeSchema();

            frame.incOverall();

            //HabitatTaxonIdConverter habitatConverter = new HabitatTaxonIdConverter(oldDB.getConnection(), newDBConn);
            //habitatConverter.convert(conversion.getCollectionMemberId());

            frame.incOverall();

            agentConverter.fixAddressOfRecord();

            frame.incOverall();

            if (dbNameSource.startsWith("gcf")) {
                GulfInvertsFixer giFixer = new GulfInvertsFixer(oldDBConn, newDBConn, dbNameSource, null);
                giFixer.convert(conversion.getCollectionMemberId());
            }
            //checkDisciplines();

            frame.setDesc("Fixing Scope....");
            TableWriter tblWriter = convLogger.getWriter("ScopeUpdater.html", "Updating Scope Summary");
            ConvScopeFixer convScopeFixer = new ConvScopeFixer(oldDBConn, newDBConn, dbNameDest, tblWriter);
            convScopeFixer.doFixTables();
            convScopeFixer.checkTables();

            FixDBAfterLogin.fixUserPermissions(true);

            waitTime = 0;

            /*
            long stTime = System.currentTimeMillis();
                    
            sql = "SELECT count(*) FROM (SELECT ce.CollectingEventID, Count(ce.CollectingEventID) as cnt FROM collectingevent AS ce " +
                "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID " +
                "Inner Join collectionobjectcatalog AS cc ON co.CollectionObjectID = cc.CollectionObjectCatalogID " +    
                "WHERE ce.BiologicalObjectTypeCollectedID <  21 " +
                "GROUP BY ce.CollectingEventID) T1 WHERE cnt > 1";
                    
            int numCESharing = BasicSQLUtils.getCountAsInt(oldDBConn, sql);
                    
            String msg = String.format("Will this Collection share Collecting Events?\nThere are %d Collecting Events that are sharing now.\n(Sp5 was %ssharing them.)", numCESharing, isUsingEmbeddedCEsInSp5() ? "NOT " : "");
            boolean doingOneToOneForColObjToCE = !UIHelper.promptForAction("Share", "Adjust CEs", "Duplicate Collecting Events", msg);
                    
            waitTime = System.currentTimeMillis() - stTime;
            */

            frame.setDesc("Duplicating CollectingEvents Performing Maintenance...");
            File ceFile = new File(dbNameDest + ".ce_all");
            if (doingOneToOneForColObjToCE) {
                DuplicateCollectingEvents dce = new DuplicateCollectingEvents(oldDBConn, newDBConn, frame,
                        conversion.getCurAgentCreatorID(), dscp.getId());
                dce.performMaint(true);

                FileUtils.writeStringToFile(ceFile, dbNameDest);

            } else if (ceFile.exists()) {
                ceFile.delete();
            }

            //endTime = System.currentTimeMillis();

            int convertTimeInSeconds = (int) ((endTime - startTime - waitTime) / 1000.0);

            int colObjCnt = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collectionobject");
            ConvertStatSender sender = new ConvertStatSender();
            sender.sendConvertInfo(dbNameDest, colObjCnt, convertTimeInSeconds);

            frame.incOverall();

            fixHibernateHiLo(newDBConn);

            try {
                frame.setDesc("Discipline Duplicator...");
                DisciplineDuplicator d = new DisciplineDuplicator(conversion.getOldDBConn(),
                        conversion.getNewDBConn(), tblWriter, frame, conversion);
                d.doShowFieldsForDiscipline();
                frame.setDesc("Duplicating Collecting Events...");
                d.duplicateCollectingEvents();
                frame.setDesc("Duplicating Localities...");
                d.duplicateLocalities();
                frame.setDesc("Duplicating Geography...");
                d.duplicateGeography();

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            frame.setDesc("Running Table Checker to report on fields with data.");
            TableWriter tDSTblWriter = convLogger.getWriter("TableDataSummary.html", "Table Data Summary",
                    true);
            TableDataChecker tblDataChecker = new TableDataChecker(oldDBConn);
            tblDataChecker.createHTMLReport(tDSTblWriter);
            //tDSTblWriter.close();

            frame.setDesc("Updating Version...");
            updateVersionInfo(newConn);

            if (dbNameDest.startsWith("kui_fish_") || dbNameDest.startsWith("kui_tissue")) {
                ConvertMiscData.convertKUFishCruiseData(oldDBConn, newDBConn, conversion.getCurDisciplineID());
                ConvertMiscData.convertKUFishObsData(oldDBConn, newDBConn);

            } else if (dbNameDest.startsWith("ku_invert_")) {
                ConvertMiscData.convertKUInvertsObsData(oldDBConn, newDBConn);
            }

            // Check for mismatched Disciplines for CE and CE Attrs
            sql = "SELECT Count(ce.CollectingEventID) FROM collectingevent AS ce "
                    + "Inner Join collectingeventattribute AS cea ON ce.CollectingEventAttributeID = cea.CollectingEventAttributeID "
                    + "WHERE ce.DisciplineID <> cea.DisciplineID";

            int ceCnt = BasicSQLUtils.getCountAsInt(sql);
            if (ceCnt > 0) {
                UIRegistry.showErrorNonModal(String.format(
                        "There are %d CollectingEvents and CE Attributes where their DisciplineID do not match.",
                        ceCnt));
            }

            // Check for ColObjs that have bad DisciplineIDs compared to the Collection's Discipline
            sql = "SELECT Count(ce.CollectingEventID) FROM collectingevent AS ce "
                    + "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID "
                    + "Inner Join collection ON co.CollectionID = collection.UserGroupScopeId "
                    + "WHERE ce.DisciplineID <>  collection.DisciplineID";
            int dspCnt = BasicSQLUtils.getCountAsInt(sql);
            if (dspCnt > 0) {
                UIRegistry.showErrorNonModal(String.format(
                        "There are %d mismatches between the Collection Object Discipline and the Discipline of the Colleciton it is in",
                        dspCnt));
            }

            // Check for One-To-One for ColObj -> CE
            if (doingOneToOneForColObjToCE) {
                sql = "SELECT COUNT(*) FROM (SELECT ce.CollectingEventID, Count(ce.CollectingEventID) AS cnt FROM collectingevent AS ce "
                        + "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID "
                        + "GROUP BY ce.CollectingEventID) T1 WHERE cnt > 1";
                ceCnt = BasicSQLUtils.getCountAsInt(sql);
                if (ceCnt > 0) {
                    sql = "SELECT id,cnt FROM (SELECT ce.CollectingEventID as id, Count(ce.CollectingEventID) AS cnt FROM collectingevent AS ce "
                            + "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID "
                            + "GROUP BY ce.CollectingEventID) T1 WHERE cnt > 1";
                    for (Object[] row : BasicSQLUtils.query(sql)) {
                        log.debug(String.format("CE[%s] has %s Collection Objects.", row[0].toString(),
                                row[1].toString()));
                    }
                    UIRegistry.showErrorNonModal(String.format(
                            "There are %d CollectingEvents that have more than one Collection Object and they are suppose to be a One-To-One",
                            ceCnt));
                }
            }

            boolean doCheckLastEditedByNamesHashSet2 = !doCheckLastEditedByNamesHashSet;
            if (doCheckLastEditedByNamesHashSet2) {
                conversion.checkCreatedModifiedByAgents();
                //conversion.fixCreatedModifiedByAgents(itUsrPwd.first, itUsrPwd.second, dbNameSource);
            }

            log.info("Done - " + dbNameDest + " " + convertTimeInSeconds);
            frame.setDesc("Done - " + dbNameDest + " " + convertTimeInSeconds);

            //System.setProperty(AppPreferences.factoryName, "edu.ku.brc.specify.config.AppPrefsDBIOIImpl");    // Needed by AppReferences
            System.setProperty("edu.ku.brc.dbsupport.DataProvider",
                    "edu.ku.brc.specify.dbsupport.HibernateDataProvider"); // Needed By the Form System and any Data Get/Set

            createTableSummaryPage();
            conversion.cleanUp();
        }

        if (idMapperMgr != null && GenericDBConversion.shouldDeleteMapTables()) {
            idMapperMgr.cleanup();
        }

        //This will convert Specify5 queries exported from the 5 database to a file that can be imported
        //into the six database. Need to have standard location for files. Can probably also import the queries here.
        //QueryConverter.convert("/home/timo/Desktop/KUI_FishQueries.xml", "/home/timo/convertedSpQ.xml", "/home/timo/UnconvertedFields.xml");

        fixPreparationCollectionMemberID(newDBConn);

        frame.setTitle("Done - " + dbNameDest);
        frame.incOverall();
        frame.processDone();

    } catch (Exception ex) {
        ex.printStackTrace();

        if (idMapperMgr != null && GenericDBConversion.shouldDeleteMapTables()) {
            idMapperMgr.cleanup();
        }

    } finally {
        if (getSession() != null) {
            getSession().close();
        }
    }
}

From source file:edu.ku.brc.specify.datamodel.busrules.CollectionBusRules.java

License:Open Source License

/**
 * //from   w w  w  .  j av a2 s.  c  o m
 */
private void addNewCollection() {
    if (!DivisionBusRules.checkForParentSave(formViewObj, Discipline.getClassTableId())) {
        return;
    }

    UIRegistry.loadAndPushResourceBundle("specifydbsetupwiz");

    UIRegistry.writeSimpleGlassPaneMsg("Building Collection...", 20); // I18N
    isOKToCont = true;
    final AppContextMgr acm = AppContextMgr.getInstance();

    final SpecifyDBSetupWizard wizardPanel = new SpecifyDBSetupWizard(
            SpecifyDBSetupWizard.WizardType.Collection, null);

    String msg = UIRegistry.getResourceString("CREATECOLL");
    final CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(), "", true,
            CustomDialog.NONE_BTN, wizardPanel);
    dlg.setCustomTitleBar(msg);
    wizardPanel.setListener(new SpecifyDBSetupWizard.WizardListener() {
        @Override
        public void cancelled() {
            isOKToCont = false;
            dlg.setVisible(false);
        }

        @Override
        public void finished() {
            dlg.setVisible(false);
        }

        @Override
        public void hide() {
            dlg.setVisible(false);
        }

        @Override
        public void panelChanged(String title) {
            dlg.setTitle(title);
        }

        @Override
        public void helpContextChanged(String helpTarget) {

        }
    });
    dlg.createUI();
    dlg.pack();
    UIHelper.centerAndShow(dlg);

    UIRegistry.popResourceBundle();

    if (!isOKToCont) {
        UIRegistry.clearSimpleGlassPaneMsg();
        return;
    }

    wizardPanel.processDataForNonBuild();

    final BuildSampleDatabase bldSampleDB = new BuildSampleDatabase();
    final ProgressFrame progressFrame = bldSampleDB.createProgressFrame(msg); // I18N
    progressFrame.turnOffOverAll();

    progressFrame.setProcess(0, 4);
    progressFrame.setProcessPercent(true);
    progressFrame.getCloseBtn().setVisible(false);
    progressFrame.setAlwaysOnTop(true);
    progressFrame.adjustProgressFrame();

    UIHelper.centerAndShow(progressFrame);

    SwingWorker<Integer, Integer> bldWorker = new SwingWorker<Integer, Integer>() {
        Collection newCollection = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            Session session = null;
            try {
                session = HibernateUtil.getNewSession();
                DataProviderSessionIFace hSession = new HibernateDataProviderSession(session);

                Discipline discipline = (Discipline) formViewObj.getMVParent().getMultiViewParent().getData();
                //Institution    institution      = acm.getClassObject(Institution.class);
                SpecifyUser specifyAdminUser = acm.getClassObject(SpecifyUser.class);
                Agent userAgent = (Agent) hSession
                        .getData("FROM Agent WHERE id = " + Agent.getUserAgent().getId());
                Properties props = wizardPanel.getProps();
                DisciplineType disciplineType = DisciplineType.getByName(discipline.getType());

                discipline = (Discipline) session.merge(discipline);
                specifyAdminUser = (SpecifyUser) hSession
                        .getData("FROM SpecifyUser WHERE id = " + specifyAdminUser.getId());

                bldSampleDB.setSession(session);

                AutoNumberingScheme catNumScheme = bldSampleDB.createAutoNumScheme(props, "catnumfmt",
                        "Catalog Numbering Scheme", CollectionObject.getClassTableId());
                /*AutoNumberingScheme accNumScheme = null;
                        
                if (institution.getIsAccessionsGlobal())
                {
                List<?> list = hSession.getDataList("FROM AutoNumberingScheme WHERE tableNumber = "+Accession.getClassTableId());
                if (list != null && list.size() == 1)
                {
                    accNumScheme = (AutoNumberingScheme)list.get(0);
                }
                } else
                {
                accNumScheme = bldSampleDB.createAutoNumScheme(props, "accnumfmt", "Accession Numbering Scheme", Accession.getClassTableId()); // I18N
                }*/

                newCollection = bldSampleDB.createEmptyCollection(discipline,
                        props.getProperty("collPrefix").toString(), props.getProperty("collName").toString(),
                        userAgent, specifyAdminUser, catNumScheme, disciplineType.isEmbeddedCollecingEvent());

                acm.setClassObject(SpecifyUser.class, specifyAdminUser);
                Agent.setUserAgent(userAgent);

            } catch (Exception ex) {
                ex.printStackTrace();

            } finally {
                if (session != null) {
                    session.close();
                }
            }

            bldSampleDB.setDataType(null);

            return null;
        }

        @Override
        protected void done() {
            super.done();

            progressFrame.setVisible(false);
            progressFrame.dispose();

            if (newCollection != null) {
                List<?> dataItems = null;

                FormViewObj dispFVO = formViewObj.getMVParent().getMultiViewParent()
                        .getCurrentViewAsFormViewObj();
                Discipline discipline = (Discipline) dispFVO.getDataObj();
                DataProviderSessionIFace pSession = null;
                try {
                    pSession = DataProviderFactory.getInstance().createSession();

                    discipline = (Discipline) pSession
                            .getData("FROM Discipline WHERE id = " + discipline.getId());
                    //formViewObj.getMVParent().getMultiViewParent().setData(division);
                    acm.setClassObject(Discipline.class, discipline);

                    dataItems = pSession.getDataList("FROM Discipline");
                    if (dataItems.get(0) instanceof Object[]) {
                        Vector<Object> dataList = new Vector<Object>();
                        for (Object row : dataItems) {
                            Object[] cols = (Object[]) row;
                            dataList.add(cols[0]);
                        }
                        dataItems = dataList;
                    }

                } catch (Exception ex) {
                    System.err.println(ex);
                    ex.printStackTrace();

                } finally {
                    if (pSession != null) {
                        pSession.close();
                    }
                }

                int curInx = dispFVO.getRsController().getCurrentIndex();
                dispFVO.setDataObj(dataItems);
                dispFVO.getRsController().setIndex(curInx);

                //UIRegistry.clearSimpleGlassPaneMsg();

                UIRegistry.showLocalizedMsg("Specify.ABT_EXIT");
                CommandDispatcher.dispatch(new CommandAction(BaseTask.APP_CMD_TYPE, BaseTask.APP_REQ_EXIT));

            } else {
                // error creating
            }
            UIRegistry.clearSimpleGlassPaneMsg();
        }
    };

    bldWorker.execute();

}

From source file:edu.ku.brc.specify.datamodel.busrules.DisciplineBusRules.java

License:Open Source License

/**
 * //from w  w  w.  j a  v  a  2s . com
 */
private void addNewDiscipline() {
    if (!DivisionBusRules.checkForParentSave(formViewObj, Division.getClassTableId())) {
        return;
    }

    if (!DivisionBusRules.askForExitonChange("ASK_TO_ADD_DISP")) {
        return;
    }

    UIRegistry.loadAndPushResourceBundle("specifydbsetupwiz");

    UIRegistry.writeSimpleGlassPaneMsg("Building Discipline...", 20); // I18N
    isOKToCont = true;
    final AppContextMgr acm = AppContextMgr.getInstance();

    final SpecifyDBSetupWizard wizardPanel = new SpecifyDBSetupWizard(
            SpecifyDBSetupWizard.WizardType.Discipline, null);

    final CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(), "", true,
            CustomDialog.NONE_BTN, wizardPanel);
    dlg.setCustomTitleBar(UIRegistry.getResourceString("CREATEDISP"));
    wizardPanel.setListener(new SpecifyDBSetupWizard.WizardListener() {
        @Override
        public void cancelled() {
            isOKToCont = false;
            dlg.setVisible(false);
        }

        @Override
        public void finished() {
            dlg.setVisible(false);
        }

        @Override
        public void hide() {
            dlg.setVisible(false);
        }

        @Override
        public void panelChanged(String title) {
            dlg.setTitle(title);
        }

        @Override
        public void helpContextChanged(String helpTarget) {

        }
    });
    UIHelper.centerAndShow(dlg);

    UIRegistry.popResourceBundle();

    if (!isOKToCont) {
        UIRegistry.clearSimpleGlassPaneMsg();
        return;
    }

    wizardPanel.processDataForNonBuild();

    final BuildSampleDatabase bldSampleDB = new BuildSampleDatabase();
    final ProgressFrame progressFrame = bldSampleDB.createProgressFrame("Creating Disicipline"); // I18N
    progressFrame.turnOffOverAll();

    progressFrame.setProcess(0, 17);
    progressFrame.setProcessPercent(true);
    progressFrame.getCloseBtn().setVisible(false);
    progressFrame.setAlwaysOnTop(true);
    progressFrame.adjustProgressFrame();

    UIHelper.centerAndShow(progressFrame);

    SwingWorker<Integer, Integer> bldWorker = new SwingWorker<Integer, Integer>() {
        private int steps = 0;
        Pair<Discipline, Collection> pair = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @SuppressWarnings("cast")
        @Override
        protected Integer doInBackground() throws Exception {
            firePropertyChange(PROGRESS, 0, ++steps);

            bldSampleDB.setDataType(acm.getClassObject(DataType.class));
            Division curDivCached = acm.getClassObject(Division.class);
            Discipline curDispCached = acm.getClassObject(Discipline.class);
            Collection curCollCached = acm.getClassObject(Collection.class);

            acm.setClassObject(Division.class, null);
            acm.setClassObject(Discipline.class, null);
            acm.setClassObject(Collection.class, null);

            Session session = null;
            try {
                session = HibernateUtil.getNewSession();
                DataProviderSessionIFace hSession = new HibernateDataProviderSession(session);

                Division curDiv = (Division) formViewObj.getMVParent().getMultiViewParent().getData();
                Division division = hSession.get(Division.class, curDiv.getId());
                SpecifyUser specifyAdminUser = (SpecifyUser) acm.getClassObject(SpecifyUser.class);
                Agent userAgent = (Agent) hSession
                        .getData("FROM Agent WHERE id = " + Agent.getUserAgent().getId());
                Properties props = wizardPanel.getProps();
                DisciplineType dispType = (DisciplineType) props.get("disciplineType");

                division = (Division) session.merge(division);
                specifyAdminUser = (SpecifyUser) hSession
                        .getData("FROM SpecifyUser WHERE id = " + specifyAdminUser.getId());

                bldSampleDB.setSession(session);

                pair = bldSampleDB.createEmptyDisciplineAndCollection(division, props, dispType, userAgent,
                        specifyAdminUser, true, true);

                if (pair != null && pair.first != null && pair.second != null) {
                    acm.setClassObject(SpecifyUser.class, specifyAdminUser);
                    Agent.setUserAgent(userAgent);
                }

                acm.setClassObject(Division.class, curDivCached);
                acm.setClassObject(Discipline.class, curDispCached);
                acm.setClassObject(Collection.class, curCollCached);

            } catch (Exception ex) {
                ex.printStackTrace();

            } finally {
                if (session != null) {
                    session.close();
                }
            }

            bldSampleDB.setDataType(null);

            return null;
        }

        @Override
        protected void done() {
            super.done();

            progressFrame.setVisible(false);
            progressFrame.dispose();

            if (pair != null && pair.first != null && pair.second != null) {
                List<?> dataItems = null;

                FormViewObj divFVO = formViewObj.getMVParent().getMultiViewParent()
                        .getCurrentViewAsFormViewObj();
                Division division = (Division) divFVO.getDataObj();
                DataProviderSessionIFace pSession = null;
                try {
                    pSession = DataProviderFactory.getInstance().createSession();

                    division = (Division) pSession.getData("FROM Division WHERE id = " + division.getId());
                    division.forceLoad();

                    //formViewObj.getMVParent().getMultiViewParent().setData(division);
                    acm.setClassObject(Division.class, division);

                    dataItems = pSession.getDataList("FROM Division");
                    if (dataItems.get(0) instanceof Object[]) {
                        Vector<Object> dataList = new Vector<Object>();
                        for (Object row : dataItems) {
                            Object[] cols = (Object[]) row;
                            Division div = (Division) cols[0];
                            div.forceLoad();
                            dataList.add(div);
                        }
                        dataItems = dataList;
                    }

                } catch (Exception ex) {
                    System.err.println(ex);
                    ex.printStackTrace();

                } finally {
                    if (pSession != null) {
                        pSession.close();
                    }
                }

                //int curInx = divFVO.getRsController().getCurrentIndex();
                //divFVO.setDataObj(dataItems);
                //divFVO.getRsController().setIndex(curInx);

            } else {
                // error creating
            }
            UIRegistry.clearSimpleGlassPaneMsg();

            UIRegistry.showLocalizedMsg("Specify.ABT_EXIT");
            CommandDispatcher.dispatch(new CommandAction(BaseTask.APP_CMD_TYPE, BaseTask.APP_REQ_EXIT));

        }
    };

    bldWorker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (PROGRESS.equals(evt.getPropertyName())) {
                //progressFrame.setProcess((Integer)evt.getNewValue());
            }
        }
    });
    bldWorker.execute();

}