Example usage for org.hibernate Query setLong

List of usage examples for org.hibernate Query setLong

Introduction

In this page you can find the example usage for org.hibernate Query setLong.

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setLong(String name, long val) 

Source Link

Document

Bind a named long-valued parameter.

Usage

From source file:de.fhdo.gui.admin.modules.collaboration.SvAssignment.java

License:Apache License

private void initList() {
    // Header//  www .java  2 s  . c  om
    List<GenericListHeaderType> header = new LinkedList<GenericListHeaderType>();
    header.add(
            new GenericListHeaderType("Terminologiename", 350, "", true, "String", true, true, false, false));
    header.add(new GenericListHeaderType("Typ", 150, "", true, "String", true, true, false, false));
    header.add(new GenericListHeaderType("Benutzername", 150, "", true, "String", true, true, false, false));
    header.add(new GenericListHeaderType("Vorname", 150, "", true, "String", true, true, false, false));
    header.add(new GenericListHeaderType("Nachname", 150, "", true, "String", true, true, false, false));
    header.add(new GenericListHeaderType("Organisation", 200, "", true, "String", true, true, false, false));

    // Daten laden
    Session hb_session_kollab = HibernateUtil.getSessionFactory().openSession();
    //hb_session_kollab.getTransaction().begin();
    Session hb_session_term = de.fhdo.terminologie.db.HibernateUtil.getSessionFactory().openSession();
    //hb_session_term.getTransaction().begin();

    List<GenericListRowType> dataList = new LinkedList<GenericListRowType>();
    try {

        //1.GetAll CS
        String hqlCs = "select distinct cs from CodeSystem cs";
        Query qCs = hb_session_term.createQuery(hqlCs);
        List<CodeSystem> csList = qCs.list();

        for (CodeSystem cs : csList) {
            SvAssignmentData data = new SvAssignmentData();
            data.setClassId(cs.getId());
            data.setClassname("CodeSystem");
            data.setTermName(cs.getName());

            //Check for userAssignment
            Query q = hb_session_kollab.createQuery("select distinct a from AssignedTerm a "
                    + "join fetch a.collaborationuser u join fetch u.organisation o "
                    + "WHERE a.classId= :p_classId AND a.classname= :p_classname");
            q.setLong("p_classId", cs.getId());
            q.setString("p_classname", "CodeSystem");
            List<AssignedTerm> atList = q.list();

            if (atList.size() == 1) {

                data.setUsername(atList.get(0).getCollaborationuser().getUsername());
                data.setFirstName(atList.get(0).getCollaborationuser().getFirstName());
                data.setName(atList.get(0).getCollaborationuser().getName());
                data.setCollaborationuserId(atList.get(0).getCollaborationuser().getId());
                data.setOrganisation(atList.get(0).getCollaborationuser().getOrganisation().getOrganisation());
                data.setAssignedTermId(atList.get(0).getId());
            } else {
                data.setUsername("-");
                data.setFirstName("-");
                data.setName("-");
                data.setCollaborationuserId(null);
                data.setOrganisation("-");
                data.setAssignedTermId(null);
            }
            GenericListRowType row = createRowFromSvAssignmentData(data);
            dataList.add(row);
        }

        //2.GetAll VS
        String hqlVs = "select distinct vs from ValueSet vs";
        Query qVs = hb_session_term.createQuery(hqlVs);
        List<ValueSet> vsList = qVs.list();

        for (ValueSet vs : vsList) {
            SvAssignmentData data = new SvAssignmentData();
            data.setClassId(vs.getId());
            data.setClassname("ValueSet");
            data.setTermName(vs.getName());

            //Check for userAssignment
            Query q = hb_session_kollab.createQuery("select distinct a from AssignedTerm a "
                    + "join fetch a.collaborationuser u join fetch u.organisation o "
                    + "WHERE a.classId= :p_classId AND a.classname= :p_classname");
            q.setLong("p_classId", vs.getId());
            q.setString("p_classname", "ValueSet");
            List<AssignedTerm> atList = q.list();

            if (atList.size() == 1) {

                data.setUsername(atList.get(0).getCollaborationuser().getUsername());
                data.setFirstName(atList.get(0).getCollaborationuser().getFirstName());
                data.setName(atList.get(0).getCollaborationuser().getName());
                data.setCollaborationuserId(atList.get(0).getCollaborationuser().getId());
                data.setOrganisation(atList.get(0).getCollaborationuser().getOrganisation().getOrganisation());
                data.setAssignedTermId(atList.get(0).getId());
            } else {
                data.setUsername("-");
                data.setFirstName("-");
                data.setName("-");
                data.setCollaborationuserId(null);
                data.setOrganisation("-");
                data.setAssignedTermId(null);
            }
            GenericListRowType row = createRowFromSvAssignmentData(data);
            dataList.add(row);
        }
    } catch (Exception e) {
        logger.error("[" + this.getClass().getCanonicalName() + "] Fehler bei initList(): " + e.getMessage());
    } finally {
        hb_session_kollab.close();
        hb_session_term.close();
    }

    // Liste initialisieren
    Include inc = (Include) getFellow("incList");
    Window winGenericList = (Window) inc.getFellow("winGenericList");
    genericList = (GenericList) winGenericList;

    //genericList.setUserDefinedId("1");
    genericList.setListActions(this);
    genericList.setButton_new(false);
    genericList.setButton_edit(true);
    genericList.setButton_delete(false);
    genericList.setListHeader(header);
    genericList.setDataList(dataList);
}

From source file:de.fhdo.helper.DeleteTermHelper.java

License:Apache License

public static String deleteCS_CSV(Boolean onlyCSV, Long codeSystemId, Long codeSystemVersionId) {

    //get Missing Id's for all CSEV
    String result = "\n";
    List csevIds = null;/* w  w w  . ja va 2s .  c o  m*/
    Session hb_session = HibernateUtil.getSessionFactory().openSession();

    try {

        String hqlCsevNumber = "select csev.versionId,csev.codeSystemEntity.id from CodeSystemEntityVersion csev join csev.codeSystemEntity cse join cse.codeSystemVersionEntityMemberships csvem";
        hqlCsevNumber += " join csvem.codeSystemVersion csv where csv.versionId=:versionId";
        Query q_CsevNumber = hb_session.createQuery(hqlCsevNumber);
        q_CsevNumber.setParameter("versionId", codeSystemVersionId);
        csevIds = q_CsevNumber.list();
        //Start deleting
        hb_session.getTransaction().begin();
        //Delete Translations, CodeSystemConcept
        int rowCountCsct = 0;
        int rowCountCsc = 0;
        int rowCountCvsm = 0;
        int rowCountCsmv = 0;
        int rowCountCseva = 0;
        int rowCountAt = 0;
        int rowCountCsev = 0;
        int rowCountCsvem = 0;
        int rowCountCse = 0;
        int rowCountCsv = 0;
        int rowCountLu = 0;
        int rowCountLt = 0;
        int rowCountMp = 0;
        int rowCountDvhcs = 0;
        int rowCountCs = 0;

        for (Object o : csevIds) {
            Object[] x = (Object[]) o;
            Long csevId = (Long) x[0];
            Long cseId = (Long) x[1];

            String hql_csct = "delete from CodeSystemConceptTranslation where codeSystemConcept.codeSystemEntityVersionId=:csevId";
            Query q_csct = hb_session.createQuery(hql_csct);
            q_csct.setParameter("csevId", csevId);
            rowCountCsct += q_csct.executeUpdate();

            String hql_csc = "delete from CodeSystemConcept where codeSystemEntityVersionId=:csevId";
            Query q_csc = hb_session.createQuery(hql_csc);
            q_csc.setParameter("csevId", csevId);
            rowCountCsc += q_csc.executeUpdate();

            String hql_cvsm = "delete from ConceptValueSetMembership where codeSystemEntityVersionId=:csevId";
            Query q_cvsm = hb_session.createQuery(hql_cvsm);
            q_cvsm.setParameter("csevId", csevId);
            rowCountCvsm += q_cvsm.executeUpdate();

            String hql_csmv = "delete from CodeSystemMetadataValue where codeSystemEntityVersionId=:csevId";
            Query q_csmv = hb_session.createQuery(hql_csmv);
            q_csmv.setParameter("csevId", csevId);
            rowCountCsmv += q_csmv.executeUpdate();

            String hql_cseva1 = "delete from CodeSystemEntityVersionAssociation where codeSystemEntityVersionId1=:csevId";
            Query q_cseva1 = hb_session.createQuery(hql_cseva1);
            q_cseva1.setParameter("csevId", csevId);
            rowCountCseva += q_cseva1.executeUpdate();

            String hql_cseva2 = "delete from CodeSystemEntityVersionAssociation where codeSystemEntityVersionId2=:csevId";
            Query q_cseva2 = hb_session.createQuery(hql_cseva2);
            q_cseva2.setParameter("csevId", csevId);
            rowCountCseva += q_cseva2.executeUpdate();

            String hql_at = "delete from AssociationType where codeSystemEntityVersionId=:csevId";
            Query q_at = hb_session.createQuery(hql_at);
            q_at.setParameter("csevId", csevId);
            rowCountAt += q_at.executeUpdate();

            String hql_csev = "delete from CodeSystemEntityVersion where versionId=:csevId";
            Query q_csev = hb_session.createQuery(hql_csev);
            q_csev.setParameter("csevId", csevId);
            rowCountCsev += q_csev.executeUpdate();

            String hql_csvem = "delete from CodeSystemVersionEntityMembership where codeSystemVersionId=:csvId";
            Query q_csvem = hb_session.createQuery(hql_csvem);
            q_csvem.setParameter("csvId", codeSystemVersionId);
            rowCountCsvem += q_csvem.executeUpdate();

            String hql_cse = "delete from CodeSystemEntity where id=:cseId";
            Query q_cse = hb_session.createQuery(hql_cse);
            q_cse.setParameter("cseId", cseId);
            rowCountCse += q_cse.executeUpdate();
        }

        //lu
        String hql_lu = "delete from LicencedUser where codeSystemVersionId=:csvId";
        Query q_lu = hb_session.createQuery(hql_lu);
        q_lu.setParameter("csvId", codeSystemVersionId);
        rowCountLu += q_lu.executeUpdate();

        //lt
        String hql_lt = "delete from LicenceType where codeSystemVersionId=:csvId";
        Query q_lt = hb_session.createQuery(hql_lt);
        q_lt.setParameter("csvId", codeSystemVersionId);
        rowCountLt += q_lt.executeUpdate();

        //CSV lschen
        String hql_csv = "delete from CodeSystemVersion where versionId=:versionId";
        Query q_csv = hb_session.createQuery(hql_csv);
        q_csv.setParameter("versionId", codeSystemVersionId);
        rowCountCsv += q_csv.executeUpdate();

        result += "csct: " + rowCountCsct + "\n";
        result += "csc: " + rowCountCsc + "\n";
        result += "cvsm: " + rowCountCvsm + "\n";
        result += "csmv: " + rowCountCsmv + "\n";
        result += "cseva: " + rowCountCseva + "\n";
        result += "at: " + rowCountAt + "\n";
        result += "csev: " + rowCountCsev + "\n";
        result += "csvem: " + rowCountCsvem + "\n";
        result += "cse: " + rowCountCse + "\n";
        result += "lu: " + rowCountLu + "\n";
        result += "lt: " + rowCountLt + "\n";
        result += "csv: " + rowCountCsv + "\n";

        if (!onlyCSV) {

            //Check for VSMV Reste and delete
            String hqlMpSearch = "from MetadataParameter where codeSystemId=:csId";
            Query q_MpSearch = hb_session.createQuery(hqlMpSearch);
            q_MpSearch.setParameter("csId", codeSystemId);
            List<MetadataParameter> mpList = q_MpSearch.list();

            for (MetadataParameter mp : mpList) {
                String hql_csmv2 = "delete from CodeSystemMetadataValue where metadataParameterId=:mpId";
                Query q_csmv2 = hb_session.createQuery(hql_csmv2);
                q_csmv2.setParameter("mpId", mp.getId());
                rowCountCsmv += q_csmv2.executeUpdate();
            }

            //Mp
            String hql_mp = "delete from MetadataParameter where codeSystemId=:csId";
            Query q_mp = hb_session.createQuery(hql_mp);
            q_mp.setParameter("csId", codeSystemId);
            rowCountMp += q_mp.executeUpdate();

            //Dvhcs
            Query q_dvhcs = hb_session
                    .createSQLQuery("delete from domain_value_has_code_system " + "where code_system_id = ?");
            q_dvhcs.setLong(0, codeSystemId);
            rowCountDvhcs += q_dvhcs.executeUpdate();

            //CS
            String hql_cs = "delete from CodeSystem where id=:id";
            Query q_cs = hb_session.createQuery(hql_cs);
            q_cs.setParameter("id", codeSystemId);
            rowCountCs += q_cs.executeUpdate();

            result += "mp: " + rowCountMp + "\n";
            result += "dvhcs: " + rowCountDvhcs + "\n";
            result += "cs: " + rowCountCs + "\n";
        }

        hb_session.getTransaction().commit();
    } catch (Exception e) {
        hb_session.getTransaction().rollback();
        result += "An Error occured: " + e.getMessage();
    } finally {
        hb_session.close();
    }
    return result;
}

From source file:de.fhdo.terminologie.helper.DeleteTermHelperWS.java

License:Apache License

public static String deleteCS_CSV(Session hb_session, Boolean onlyCSV, Long codeSystemId,
        Long codeSystemVersionId) {

    //get Missing Id's for all CSEV
    String result = "\n";
    List csevIds = null;/*from w  w w. ja v a  2s  .c o m*/

    //Delete Translations, CodeSystemConcept
    int rowCountCsct = 0;
    int rowCountCsc = 0;
    int rowCountCvsm = 0;
    int rowCountCsmv = 0;
    int rowCountCseva = 0;
    int rowCountAt = 0;
    int rowCountCsev = 0;
    int rowCountCsvem = 0;
    int rowCountCse = 0;
    int rowCountCsv = 0;
    int rowCountLu = 0;
    int rowCountLt = 0;
    int rowCountMp = 0;
    int rowCountDvhcs = 0;
    int rowCountCs = 0;

    //try
    // {
    CodeSystem cs = (CodeSystem) hb_session.get(CodeSystem.class, codeSystemId);

    if (codeSystemVersionId == null) {
        for (CodeSystemVersion csv : cs.getCodeSystemVersions()) {
            result += "Version: " + csv.getName();
            result += deleteCS_CSV(hb_session, false, codeSystemId, csv.getVersionId());
        }

        //Check for VSMV Reste and delete
        String hqlMpSearch = "from MetadataParameter where codeSystemId=:csId";
        Query q_MpSearch = hb_session.createQuery(hqlMpSearch);
        q_MpSearch.setParameter("csId", codeSystemId);
        List<MetadataParameter> mpList = q_MpSearch.list();

        for (MetadataParameter mp : mpList) {
            String hql_csmv2 = "delete from CodeSystemMetadataValue where metadataParameterId=:mpId";
            Query q_csmv2 = hb_session.createQuery(hql_csmv2);
            q_csmv2.setParameter("mpId", mp.getId());
            rowCountCsmv += q_csmv2.executeUpdate();
        }

        //Mp
        String hql_mp = "delete from MetadataParameter where codeSystemId=:csId";
        Query q_mp = hb_session.createQuery(hql_mp);
        q_mp.setParameter("csId", codeSystemId);
        rowCountMp += q_mp.executeUpdate();

        //Dvhcs
        Query q_dvhcs = hb_session
                .createSQLQuery("delete from domain_value_has_code_system " + "where code_system_id = ?");
        q_dvhcs.setLong(0, codeSystemId);
        rowCountDvhcs += q_dvhcs.executeUpdate();

        //CS
        String hql_cs = "delete from CodeSystem where id=:id";
        Query q_cs = hb_session.createQuery(hql_cs);
        q_cs.setParameter("id", codeSystemId);
        rowCountCs += q_cs.executeUpdate();

        result += "CodeSystem: " + cs.getName() + "\n";
        result += "mp: " + rowCountMp + "\n";
        result += "dvhcs: " + rowCountDvhcs + "\n";
        result += "cs: " + rowCountCs + "\n\n";

        //hb_session.getTransaction().commit();
    } else {

        if (cs.getCodeSystemVersions().size() < 1 && onlyCSV)
            return "Ein Code System MUSS eine Version haben! \nBitte legen sie eine neue an bevor sie diese lschen. \nSie knnen alternativ das gesamte Code System lschen.";

        String hqlCsevNumber = "select csev.versionId,csev.codeSystemEntity.id from CodeSystemEntityVersion csev join csev.codeSystemEntity cse join cse.codeSystemVersionEntityMemberships csvem";
        hqlCsevNumber += " join csvem.codeSystemVersion csv where csv.versionId=:versionId";
        Query q_CsevNumber = hb_session.createQuery(hqlCsevNumber);
        q_CsevNumber.setParameter("versionId", codeSystemVersionId);
        csevIds = q_CsevNumber.list();
        //Start deleting
        //hb_session.getTransaction().begin();
        int count = 0;

        for (Object o : csevIds) {
            if (count % 100 == 0)
                logger.debug("Count: " + count);

            Object[] x = (Object[]) o;
            Long csevId = (Long) x[0];
            Long cseId = (Long) x[1];

            rowCountCsc += removeConcept(cseId, csevId, codeSystemVersionId, hb_session);

            count++;
        }

        //lu
        String hql_lu = "delete from LicencedUser where codeSystemVersionId=:csvId";
        Query q_lu = hb_session.createQuery(hql_lu);
        q_lu.setParameter("csvId", codeSystemVersionId);
        rowCountLu += q_lu.executeUpdate();

        //lt
        String hql_lt = "delete from LicenceType where codeSystemVersionId=:csvId";
        Query q_lt = hb_session.createQuery(hql_lt);
        q_lt.setParameter("csvId", codeSystemVersionId);
        rowCountLt += q_lt.executeUpdate();

        //CSV lschen
        String hql_csv = "delete from CodeSystemVersion where versionId=:versionId";
        Query q_csv = hb_session.createQuery(hql_csv);
        q_csv.setParameter("versionId", codeSystemVersionId);
        rowCountCsv += q_csv.executeUpdate();

        result += "Codesystem Version successfully deleted.\n\n";
        result += "Concepts: " + rowCountCsc + "\n";
        //result += "Translations: " + rowCountCsct + "\n";

        //        result += "csct: " + rowCountCsct + "\n";
        //        result += "csc: " + rowCountCsc + "\n";
        //        result += "cvsm: " + rowCountCvsm + "\n";
        //        result += "csmv: " + rowCountCsmv + "\n";
        //        result += "cseva: " + rowCountCseva + "\n";
        //        result += "at: " + rowCountAt + "\n";
        //        result += "csev: " + rowCountCsev + "\n";
        //        result += "csvem: " + rowCountCsvem + "\n";
        //        result += "cse: " + rowCountCse + "\n";
        //        result += "lu: " + rowCountLu + "\n";
        //        result += "lt: " + rowCountLt + "\n";
        //        result += "csv: " + rowCountCsv + "\n\n";
        //hb_session.getTransaction().commit();
    }
    //    }
    //    catch (Exception e)
    //    {
    //      //hb_session.getTransaction().rollback();
    //      result += "An Error occured: " + e.getMessage();
    //    }
    //    finally
    //    {
    //      //hb_session.close();
    //    }
    return result;
}

From source file:de.fhdo.terminologie.helper.HQLParameterHelper.java

License:Apache License

public void applySQLParameter(Query q) {
    Iterator<String> it = parameterMap.keySet().iterator();

    while (it.hasNext()) {
        String key = it.next();//from   ww  w.j a v  a 2  s .  c om
        HQLObject obj = parameterMap.get(key);

        String s = "";

        if (obj.obj instanceof String) {
            s = "%" + obj.obj.toString() + "%";
            q.setString("s_" + obj.fieldName, s);
        } else if (obj.obj instanceof java.util.Date) {
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //s = sdf.format(obj.obj);

            //q.setDate("s_" + obj.fieldName, (java.util.Date)obj.obj);
            q.setTimestamp("s_" + obj.fieldName, (java.util.Date) obj.obj);
            //logger.debug("SDF: " + sdf.format(obj.obj));
        } else if (obj.obj instanceof Boolean) {
            //s = Boolean.parseBoolean(obj.obj.toString()) ? "1" : "0";
            q.setBoolean("s_" + obj.fieldName, (Boolean) obj.obj);
            //logger.debug("Bool: " + s);
        } else if (obj.obj instanceof Integer) {
            //s = ((Integer)obj.obj).toString();
            q.setInteger("s_" + obj.fieldName, (Integer) obj.obj);
        } else if (obj.obj instanceof Long) {
            //s = ((Integer)obj.obj).toString();
            q.setLong("s_" + obj.fieldName, (Long) obj.obj);
        } else {
            s = obj.obj.toString();
            q.setString("s_" + obj.fieldName, s);

            logger.warn("Typ nicht gefunden: " + obj.obj.getClass().getCanonicalName());
        }

    }
}

From source file:de.fhdo.terminologie.ws.administration._export.ExportCodeSystemSVS.java

License:Apache License

public String exportSVS(ExportCodeSystemContentResponseType reponse) {
    String s = ""; // Status-Meldung
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    ExportType exportType = new ExportType();

    try {// ww w  .jav a 2  s.  c  om

        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLStreamWriter xmlsw = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(baos));

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

        try {

            /*if(parameter.getExportInfos().isUpdateCheck()){
                //Request-Parameter fr ReturnValueSetDetails erstellen
                if (logger.isInfoEnabled())
                  logger.info("[ExportSVs] Erstelle Request-Parameter fr ReturnCodeSystemDetails");
                    
                ReturnCodeSystemDetailsRequestType requestCodeSystemDetails = new ReturnCodeSystemDetailsRequestType();
                requestCodeSystemDetails.setCodeSystem(parameter.getCodeSystem());
                requestCodeSystemDetails.getCodeSystem().getCodeSystemVersions().add((CodeSystemVersion) parameter.getCodeSystem().getCodeSystemVersions().toArray()[0]);
                requestCodeSystemDetails.setLoginToken(parameter.getLoginToken());
                    
                //ValueSetDetails abrufen
                ReturnCodeSystemDetails rcsd = new ReturnCodeSystemDetails();
                ReturnCodeSystemDetailsResponseType responseCodeSystemDetails = rcsd.ReturnCodeSystemDetails(requestCodeSystemDetails, "");
                if (logger.isInfoEnabled())
                  logger.info("[ExportSVS] ReturnCodeSystemDetails abgerufen");
                    
                if (responseCodeSystemDetails.getReturnInfos().getStatus() == ReturnType.Status.OK
            && responseCodeSystemDetails.getCodeSystem() != null)
                {
                    if(!responseCodeSystemDetails.getCodeSystem().getCurrentVersionId().equals(((CodeSystemVersion)parameter.getCodeSystem().getCodeSystemVersions().toArray()[0]).getVersionId())){
            ((CodeSystemVersion)parameter.getCodeSystem().getCodeSystemVersions().toArray()[0]).setVersionId(responseCodeSystemDetails.getCodeSystem().getCurrentVersionId());
                    }
                }
            } */

            String hql = "select distinct csv from CodeSystemVersion csv join csv.codeSystem cs"
                    + " where cs.id=:id and" + " csv.versionId=:versionId";

            org.hibernate.Query q = hb_session.createQuery(hql);
            q.setLong("id", parameter.getCodeSystem().getId());
            q.setLong("versionId",
                    parameter.getCodeSystem().getCodeSystemVersions().iterator().next().getVersionId());

            List<CodeSystemVersion> csvList = q.list();
            CodeSystemVersion csv = null;
            if (csvList != null && csvList.size() == 1) {
                csv = csvList.get(0);
            }

            if (csv != null) {
                //Erstellung Hauptknoten

                xmlsw.writeStartElement("valueSet");
                if (csv.getCodeSystem().getName() != null) {
                    xmlsw.writeAttribute("name", EscCharCheckQuot.check(csv.getCodeSystem().getName()));
                } else {
                    xmlsw.writeAttribute("name", "");
                }
                if (csv.getCodeSystem().getName() != null) {
                    xmlsw.writeAttribute("displayName", EscCharCheckQuot.check(csv.getCodeSystem().getName()));
                } else {
                    xmlsw.writeAttribute("displayName", "");
                }
                if (csv.getReleaseDate() != null) {
                    xmlsw.writeAttribute("effectiveDate",
                            EscCharCheckQuot.check(sdf.format(csv.getReleaseDate())));
                } else {
                    xmlsw.writeAttribute("effectiveDate", "");
                }
                if (csv.getOid() != null) {
                    xmlsw.writeAttribute("id", EscCharCheckQuot.check(csv.getOid()));
                } else {
                    xmlsw.writeAttribute("id", "");
                }
                if (csv.getStatus() == 1) {
                    xmlsw.writeAttribute("statusCode", "final");
                } else {
                    xmlsw.writeAttribute("statusCode", "not final");
                }
                if (csv.getCodeSystem().getWebsite() != null) {
                    xmlsw.writeAttribute("website", EscCharCheckQuot.check(csv.getCodeSystem().getWebsite()));
                } else {
                    xmlsw.writeAttribute("website", "");
                }
                if (csv.getName() != null) {
                    xmlsw.writeAttribute("version", EscCharCheckQuot.check(csv.getName()));
                } else {
                    xmlsw.writeAttribute("version", "");
                }
                if (csv.getCodeSystem().getDescription() != null) {
                    xmlsw.writeAttribute("beschreibung",
                            EscCharCheckQuot.check(csv.getCodeSystem().getDescription()));
                } else {
                    xmlsw.writeAttribute("beschreibung", "");
                }
                if (csv.getCodeSystem().getDescriptionEng() != null) {
                    xmlsw.writeAttribute("description",
                            EscCharCheckQuot.check(csv.getCodeSystem().getDescriptionEng()));
                } else {
                    xmlsw.writeAttribute("description", "");
                }

                String hqlC = "select distinct cse from CodeSystemEntity cse join cse.codeSystemVersionEntityMemberships csvem join csvem.codeSystemVersion csv join cse.codeSystemEntityVersions csev join csev.codeSystemConcepts csc"
                        + " where csv.versionId=:versionId";

                org.hibernate.Query qC = hb_session.createQuery(hqlC);
                qC.setLong("versionId",
                        parameter.getCodeSystem().getCodeSystemVersions().iterator().next().getVersionId());

                List<CodeSystemEntity> cselist = qC.list();

                if (logger.isInfoEnabled())
                    logger.info("[ExportSVS] ListValueSetContents abgerufen");

                //SVS-Inhalt erstellen
                if (logger.isInfoEnabled())
                    logger.info("[ExportSVS] Erstelle SVS-Inhalt mit Konzepten...");

                xmlsw.writeStartElement("conceptList");

                // Flaches Vokabular, einfach alle Eintrge exportieren
                for (CodeSystemEntity cse : cselist) {
                    for (CodeSystemEntityVersion csev : cse.getCodeSystemEntityVersions()) {
                        // Nur aktuellste Version exportieren
                        if (cse.getCurrentVersionId().longValue() == csev.getVersionId().longValue()) {

                            CodeSystemConcept csc = csev.getCodeSystemConcepts().iterator().next();
                            if (csev.getStatusVisibility() == 1) {
                                if (logger.isDebugEnabled())
                                    logger.debug("Schreibe Code: " + csc.getCode());

                                xmlsw.writeStartElement("concept");
                                if (csc.getCode() != null) {
                                    xmlsw.writeAttribute("code", EscCharCheckQuot.check(csc.getCode()));
                                } else {
                                    xmlsw.writeAttribute("code", "");
                                }
                                if (csc.getTerm() != null) {
                                    xmlsw.writeAttribute("displayName", csc.getTerm());
                                } else {
                                    xmlsw.writeAttribute("displayName", "");
                                }
                                if (csc.getDescription() != null) {
                                    xmlsw.writeAttribute("concept_beschreibung",
                                            EscCharCheckQuot.check(csc.getDescription()));
                                } else {
                                    xmlsw.writeAttribute("concept_beschreibung", "");
                                }
                                if (csc.getMeaning() != null) {
                                    xmlsw.writeAttribute("deutsch", EscCharCheckQuot.check(csc.getMeaning()));
                                } else {
                                    xmlsw.writeAttribute("deutsch", "");
                                }
                                if (csc.getHints() != null) {
                                    xmlsw.writeAttribute("hinweise", EscCharCheckQuot.check(csc.getHints()));
                                } else {
                                    xmlsw.writeAttribute("hinweise", "");
                                }
                                if (csv.getOid() != null) {
                                    xmlsw.writeAttribute("codeSystem", EscCharCheckQuot.check(csv.getOid()));
                                } else {
                                    xmlsw.writeAttribute("codeSystem", "");
                                }

                                Iterator<CodeSystemMetadataValue> it = csev.getCodeSystemMetadataValues()
                                        .iterator();
                                /*List<CodeSystemMetadataValue> myList = IteratorUtils.toList(it);
                                boolean output = true;
                                        
                                for(CodeSystemMetadataValue v:myList){
                                        
                                    for(CodeSystemMetadataValue vInt:myList){
                                                
                                        if(!v.equals(vInt) && (v.getMetadataParameter().getParamName().equals(vInt.getMetadataParameter().getParamName()))
                                           && (v.getParameterValue().equals("") && !vInt.getParameterValue().equals(""))){
                                            output = false;
                                        }
                                    }
                                            
                                    if(output)
                                        xmlsw.writeAttribute(EscCharCheckQuot.checkAttribute(v.getMetadataParameter().getParamName().toLowerCase()), v.getParameterValue());
                                }*/

                                while (it.hasNext()) {

                                    CodeSystemMetadataValue csmv = (CodeSystemMetadataValue) it.next();
                                    if (csmv.getParameterValue() != null) {
                                        xmlsw.writeAttribute(
                                                EscCharCheckQuot.checkAttribute(csmv.getMetadataParameter()
                                                        .getParamName().toLowerCase()),
                                                csmv.getParameterValue());
                                    } else {
                                        xmlsw.writeAttribute(
                                                EscCharCheckQuot.checkAttribute(csmv.getMetadataParameter()
                                                        .getParamName().toLowerCase()),
                                                EscCharCheckQuot.check(csmv.getParameterValue()));
                                    }
                                }

                                xmlsw.writeEndElement();
                                countExported++;
                                //System.out.println("\n" + countExported);
                            }
                        }
                    }
                }
                xmlsw.writeEndElement();
                xmlsw.writeEndElement();
                xmlsw.flush();
                xmlsw.close();

                if (logger.isInfoEnabled())
                    logger.info("[ExportSVS] SVS-Inhalt erstellt");
            } else {
                throw new Exception("ExportSVS: CSV is NULL");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage());
            s = "Fehler: " + ex.getLocalizedMessage();
        }

        if (countExported > 0) {

            exportType.setFilecontent(baos.toByteArray());
            baos.close();

            exportType.setUrl("");
            reponse.getReturnInfos()
                    .setMessage("Export abgeschlossen. " + countExported + " Konzepte exportiert.");
        } else {
            reponse.getReturnInfos().setMessage("Keine Konzepte exportiert.");
            if (logger.isInfoEnabled())
                logger.info("[ExportSVS] Kein Export erstellt...");
        }

        //Format-ID (SVS) setzen
        exportType.setFormatId(ExportCodeSystemContentRequestType.EXPORT_SVS_ID);

        //ExportInfos in Response schreiben
        reponse.setExportInfos(exportType);
        //hb_session.getTransaction().commit();
        hb_session.close();

    } catch (Exception ex) {
        s = "Fehler: " + ex.getLocalizedMessage();
        ex.printStackTrace();
    }

    return s;
}

From source file:de.fhdo.terminologie.ws.administration._export.ExportCSV.java

License:Apache License

public String exportCSV(ExportCodeSystemContentResponseType reponse) {
    String s = ""; // Status-Meldung
    //int count = countExported;

    CsvWriter csv;/*from   w w  w.j a v a 2s. com*/
    ExportType exportType = new ExportType();
    paramList = new HashMap<Integer, String>();
    hb_session = HibernateUtil.getSessionFactory().openSession();
    //hb_session.getTransaction().begin();

    try {
        //TODO URL erstellen und setzen (Namenskonvention?) 
        //TODO ggf. auf bereits identischen Export-File prfen
        //String csv_output_url = "/var/lib/tomcat6/webapps/csv_test_output.csv";
        //csv = new CsvWriter(new FileWriter(csv_output_url), ';');

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //csv = new CsvWriter(bos, ';', Charset.forName("ISO-8859-1")); // TODO Charset prfen
        //csv.setTextQualifier('\'');
        csv = new CsvWriter(bos, PropertiesHelper.getInstance().getDelimiter(), Charset.forName("ISO-8859-1")); // TODO Charset prfen
        csv.setTextQualifier(PropertiesHelper.getInstance().getExportCsvQualifier());
        csv.setForceQualifier(PropertiesHelper.getInstance().isExportCsvForceQualifier());

        try {
            //Request-Parameter fr ReturnCodeSystemDetails erstellen
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] Erstelle Request-Parameter fr ReturnCodeSystemDetails");

            ReturnCodeSystemDetailsRequestType requestCodeSystemDetails = new ReturnCodeSystemDetailsRequestType();
            requestCodeSystemDetails.setCodeSystem(parameter.getCodeSystem());
            if (requestCodeSystemDetails.getCodeSystem() != null
                    && requestCodeSystemDetails.getCodeSystem().getCodeSystemVersions() != null)
                requestCodeSystemDetails.getCodeSystem().getCodeSystemVersions().add(
                        (CodeSystemVersion) parameter.getCodeSystem().getCodeSystemVersions().toArray()[0]);
            requestCodeSystemDetails.setLoginToken(parameter.getLoginToken());

            //CodeSystemDetails abrufen
            ReturnCodeSystemDetails rcsd = new ReturnCodeSystemDetails();
            ReturnCodeSystemDetailsResponseType responseCodeSystemDetails = rcsd
                    .ReturnCodeSystemDetails(requestCodeSystemDetails, "");
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] ReturnCodeSystemDetails abgerufen");

            /*if (parameter.getExportInfos().isUpdateCheck())
            {
              if (responseCodeSystemDetails.getReturnInfos().getStatus() == Status.OK
                      && responseCodeSystemDetails.getCodeSystem() != null)
              {
                if (!responseCodeSystemDetails.getCodeSystem().getCurrentVersionId().equals(((CodeSystemVersion) parameter.getCodeSystem().getCodeSystemVersions().toArray()[0]).getVersionId()))
                {
                  ((CodeSystemVersion) parameter.getCodeSystem().getCodeSystemVersions().toArray()[0]).setVersionId(responseCodeSystemDetails.getCodeSystem().getCurrentVersionId());
                    
                  requestCodeSystemDetails = new ReturnCodeSystemDetailsRequestType();
                  requestCodeSystemDetails.setCodeSystem(parameter.getCodeSystem());
                  requestCodeSystemDetails.getCodeSystem().getCodeSystemVersions().add((CodeSystemVersion) parameter.getCodeSystem().getCodeSystemVersions().toArray()[0]);
                  requestCodeSystemDetails.setLoginToken(parameter.getLoginToken());
                    
                  //CodeSystemDetails abrufen
                  rcsd = new ReturnCodeSystemDetails();
                  responseCodeSystemDetails = rcsd.ReturnCodeSystemDetails(requestCodeSystemDetails, "");
                  if (logger.isInfoEnabled())
                    logger.info("[ExportCSV] ReturnCodeSystemDetails abgerufen");
                }
              }
            }*/

            //Request-Parameter fr ListCodeSystemConcepts erstellen
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] Erstelle Request-Parameter fr ListCodeSystemConcepts");

            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] ListCodeSystemConcepts abgerufen");

            String hql = "select distinct csv from CodeSystemVersion csv join csv.codeSystem cs"
                    + " where cs.id=:id and" + " csv.versionId=:versionId";

            org.hibernate.Query q = hb_session.createQuery(hql);
            q.setLong("id", parameter.getCodeSystem().getId());
            q.setLong("versionId",
                    parameter.getCodeSystem().getCodeSystemVersions().iterator().next().getVersionId());

            List<CodeSystemVersion> csvList = q.list();
            CodeSystemVersion csversion = null;
            if (csvList != null && csvList.size() == 1) {
                csversion = csvList.get(0);
            }

            String hqlM = "select distinct mp from MetadataParameter mp join mp.codeSystem cs"
                    + " where cs.id=:id";

            org.hibernate.Query qM = hb_session.createQuery(hqlM);
            qM.setLong("id", parameter.getCodeSystem().getId());
            List<MetadataParameter> mlist = qM.list();

            //=================================================
            // CSV-Header erstellen und Dauerattribute auslesen
            //=================================================
            csv.write("code");
            csv.write("codeSystem");
            csv.write("displayName");
            csv.write("parentCode");
            csv.write("concept_Beschreibung");
            csv.write("meaning");
            csv.write("hints");
            int count = 0;
            for (MetadataParameter mp : mlist) {
                String para = mp.getParamName();
                String b = para.substring(0, 1);
                b = b.toLowerCase();
                para = b + para.substring(1);

                csv.write(para); //lowerCase
                paramList.put(count, mp.getParamName());//Normal UpperCase
                count++;
                if (para.equals("level"))
                    levelExists = true;
            }

            if (!levelExists)
                csv.write("level");

            //ENDE Header erstellen
            csv.endRecord();

            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] CSV-Header erstellt.");

            //CSV-Inhalt erstellen
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] Erstelle CSV-Inhalt mit Konzepten...");

            int countRoot = 0;

            String hqlC = "select distinct cse from CodeSystemEntity cse join cse.codeSystemVersionEntityMemberships csvem join csvem.codeSystemVersion csv join cse.codeSystemEntityVersions csev join csev.codeSystemConcepts csc"
                    + " where csv.versionId=:versionId";

            if (parameter.getExportParameter() != null
                    && parameter.getExportParameter().getDateFrom() != null) {
                // Datum fr Synchronisation hinzufgen
                hqlC += " and csev.statusVisibilityDate>:dateFrom";
            }

            org.hibernate.Query qC = hb_session.createQuery(hqlC);
            qC.setLong("versionId",
                    parameter.getCodeSystem().getCodeSystemVersions().iterator().next().getVersionId());

            if (parameter.getExportParameter() != null
                    && parameter.getExportParameter().getDateFrom() != null) {
                // Datum fr Synchronisation hinzufgen
                qC.setDate("dateFrom", parameter.getExportParameter().getDateFrom());
                logger.debug("Snych-Zeit: " + parameter.getExportParameter().getDateFrom().toString());
            } else
                logger.debug("keine Snych-Zeit angegeben");

            List<CodeSystemEntity> cselist = qC.list();
            for (CodeSystemEntity cse : cselist) {
                for (CodeSystemEntityVersion csev : cse.getCodeSystemEntityVersions()) {
                    // Nur aktuellste Version exportieren
                    if (cse.getCurrentVersionId().longValue() == csev.getVersionId().longValue()) {

                        CodeSystemConcept csc = csev.getCodeSystemConcepts().iterator().next();
                        if (csev.getStatusVisibility() == 1) {
                            if (logger.isDebugEnabled())
                                logger.debug("Schreibe Code: " + csc.getCode());
                            CodeSystemVersionEntityMembership member = cse
                                    .getCodeSystemVersionEntityMemberships().iterator().next();
                            writeEntry(csv, 0, csev, member, null, csversion);
                        }
                    }
                }
            }

            /*
            for (CodeSystemEntity cse : cselist)//responseListCodeSystemConcepts.getCodeSystemEntity())
            {
              CodeSystemVersionEntityMembership member = cse.getCodeSystemVersionEntityMemberships().iterator().next();
              boolean isAxis = false;
              boolean isMainClass = false;
              if (member.getIsAxis() != null)
                isAxis = member.getIsAxis().booleanValue();
              if (member.getIsMainClass() != null)
                isMainClass = member.getIsMainClass().booleanValue();
                    
              if (isAxis || isMainClass)
              {
                countRoot++;
                    
                for (CodeSystemEntityVersion csev : cse.getCodeSystemEntityVersions())
                {
                  // Nur aktuellste Version exportieren
                  if (cse.getCurrentVersionId().longValue() == csev.getVersionId().longValue())
                  {
                    writeEntry(csv, 0, csev, member, null, csversion);
                    
                    // TODO Beziehungen ausgeben
                    for (CodeSystemEntityVersionAssociation assChild : csev.getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1())
                    {
                      if (assChild.getCodeSystemEntityVersionByCodeSystemEntityVersionId2() != null)
                      {
            long childId = assChild.getCodeSystemEntityVersionByCodeSystemEntityVersionId2().getVersionId();
            exportChild(csv, 1, childId, cselist, csev, csversion);
                      }
                    }
                  }
                }
              }
            }
                    
            if (countRoot == 0)
            {
              // Flaches Vokabular, einfach alle Eintrge exportieren
              for (CodeSystemEntity cse : cselist)
              {
                for (CodeSystemEntityVersion csev : cse.getCodeSystemEntityVersions())
                {
                  // Nur aktuellste Version exportieren
                  if (cse.getCurrentVersionId().longValue() == csev.getVersionId().longValue())
                  {
                    writeEntry(csv, 0, csev, null, null, csversion);
                  }
                }
              }
            }
            */
            /*Iterator<CodeSystemEntity> it_CSE = responseListCodeSystemConcepts.getCodeSystemEntity().iterator();
                    
             while (it_CSE.hasNext())
             {
             Iterator<CodeSystemEntityVersion> it_CSEV = it_CSE.next().getCodeSystemEntityVersions().iterator();
                    
             while (it_CSEV.hasNext())
             {
             Iterator<CodeSystemConcept> it_CSC = it_CSEV.next().getCodeSystemConcepts().iterator();
                    
             while (it_CSC.hasNext())
             {
             temp_CSC = it_CSC.next();
                    
             //CSV-Zeile erstellen (CodeSystemConcept)
                    
             //CodeSystem-Name (immer)                
             csv.write(csvEntryCodeSystem);
             //CodeSystem-Beschreibung (Parameter codeSystemInfo == true)
             if (parameter.getExportParameter().getCodeSystemInfos())
             {
             csv.write(csvEntryCodeSystemDescription);
             }
             //CodeSystem-Version (immer)
             csv.write(csvEntryCodeSystemVersion);
             //CodeSystem-Version Beschreibung (Parameter codeSystemInfo == true)
             if (parameter.getExportParameter().getCodeSystemInfos())
             {
             csv.write(csvEntryCodeSystemVersionDescription);
             }
             //CodeSystem-OID (immer)
             csv.write(csvEntryCodeSystemOid);
             //CodeSystemVersion-Ablaufdatum (Parameter codeSystemInfo == true)
             if (parameter.getExportParameter().getCodeSystemInfos())
             {
             csv.write(csvEntryCodeSystemExpirationDate);
             }
                    
                    
             //Code (immer)
             csv.write(temp_CSC.getCode());
             //Term (immer)
             csv.write(temp_CSC.getTerm());
             //isPreferred (immer)
             if (temp_CSC.getIsPreferred())
             {
             csv.write("Bevorzugt");
             }
             else
             {
             csv.write("Nicht bevorzugt");
             }
                    
                    
             //bersetzungen (Parameter translations == true)
             if (parameter.getExportParameter().getTranslations())
             {
             //TODO Translations in CSV-Inhalt                 
             }
                    
             //bersetzungen (Parameter associationInfos == true)
             if (!parameter.getExportParameter().getAssociationInfos().isEmpty())
             {
             //TODO AssociationInfos CSV-Header                                
             }
                    
             count++;
             csv.endRecord();
                    
                    
             } //END CodeSystemConcept
             } //END CodeSystemEntityVersion
             } //END CodeSystemEntity
             */
            //ENDE CSV-Inhalt erstellen
            //Sort
            //Collections.sort(entryList, new AlphanumComparator());

            for (Entry e : entryList) {
                writeCsvEntry(csv, e.level, e.csev, e.csevParent, e.csv);
            }

            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] CSV-Inhalt erstellt");

        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage());
            s = "Fehler: " + ex.getLocalizedMessage();
        }

        //CSV-Datei schliessen
        csv.close();
        //if (logger.isInfoEnabled())
        //  logger.info("[ExportCSV] CSV-Datei geschrieben. Dateipfad: " + csv_output_url);

        if (countExported > 0) {
            //countExported = count;
            //CSV-Datei in Byte umwandeln

            /*File file = new File(csv_output_url);
             byte[] filecontent = new byte[(int) file.length()];
             FileInputStream fileInputStream = new FileInputStream(file);
             fileInputStream.read(filecontent);
             fileInputStream.close();
             if (logger.isInfoEnabled())
             logger.info("[ExportCSV] CSV-Datei in byte[] umgewandelt. (filecontent) ");*/
            //Filecontent setzen
            exportType.setFilecontent(bos.toByteArray());
            //Export-URL setzen
            //exportType.setUrl(csv_output_url);
            exportType.setUrl("");
            reponse.getReturnInfos()
                    .setMessage("Export abgeschlossen. " + countExported + " Konzepte exportiert.");
        } else {
            reponse.getReturnInfos().setMessage("Keine Konzepte exportiert.");
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] Kein Export erstellt...");
        }

        //Format-ID (CSV) setzen
        exportType.setFormatId(ExportCodeSystemContentRequestType.EXPORT_CSV_ID);

        //ExportInfos in Response schreiben
        reponse.setExportInfos(exportType);
    } catch (Exception ex) {
        s = "Fehler: " + ex.getLocalizedMessage();
        ex.printStackTrace();
    }

    //hb_session.getTransaction().commit();
    hb_session.close();
    return s;
}

From source file:de.fhdo.terminologie.ws.administration._export.ExportValueSetCSV.java

License:Apache License

public String exportCSV(ExportValueSetContentResponseType reponse) {
    String s = ""; // Status-Meldung
    //int count = countExported;

    CsvWriter csv;/*from  w w w  . j  a  v a2 s  .c  o m*/
    ExportType exportType = new ExportType();
    HashMap<Integer, String> paramList = new HashMap<Integer, String>();

    //hb_session.getTransaction().begin();
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        csv = new CsvWriter(bos, ';', Charset.forName("ISO-8859-1")); // TODO Charset prfen
        csv.setTextQualifier('\'');
        csv.setForceQualifier(true);

        try {

            //Request-Parameter fr ReturnValueSetDetails erstellen
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] Erstelle Request-Parameter fr ReturnValueSetDetails");

            ReturnValueSetDetailsRequestType requestValueSetDetails = new ReturnValueSetDetailsRequestType();
            requestValueSetDetails.setValueSet(parameter.getValueSet());
            requestValueSetDetails.getValueSet().getValueSetVersions()
                    .add((ValueSetVersion) parameter.getValueSet().getValueSetVersions().toArray()[0]);
            requestValueSetDetails.setLoginToken(parameter.getLoginToken());

            //ValueSetDetails abrufen
            ReturnValueSetDetails rcsd = new ReturnValueSetDetails();
            ReturnValueSetDetailsResponseType responseValueSetDetails = rcsd
                    .ReturnValueSetDetails(requestValueSetDetails, "");
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] ReturnValueSetDetails abgerufen");

            /*if (parameter.getExportInfos().isUpdateCheck())
            {
              if (responseValueSetDetails.getReturnInfos().getStatus() == ReturnType.Status.OK
                      && responseValueSetDetails.getValueSet() != null)
              {
                if (!responseValueSetDetails.getValueSet().getCurrentVersionId().equals(((ValueSetVersion) parameter.getValueSet().getValueSetVersions().toArray()[0]).getVersionId()))
                {
                  ((ValueSetVersion) parameter.getValueSet().getValueSetVersions().toArray()[0]).setVersionId(responseValueSetDetails.getValueSet().getCurrentVersionId());
                }
              }
            }*/

            ListValueSetContentsRequestType requestListCodeSystemConcepts = new ListValueSetContentsRequestType();
            requestListCodeSystemConcepts.setValueSet(parameter.getValueSet());
            requestListCodeSystemConcepts.getValueSet().getValueSetVersions()
                    .add((ValueSetVersion) parameter.getValueSet().getValueSetVersions().toArray()[0]);
            requestListCodeSystemConcepts.setLoginToken(parameter.getLoginToken());
            //requestListCodeSystemConcepts.setLookForward(true);

            boolean syncEnabled = parameter.getExportParameter() != null
                    && parameter.getExportParameter().getDateFrom() != null;
            if (syncEnabled) {
                // Datum fr Synchronisation hinzufgen
                logger.debug("Datum fr Synchronisation hinzufgen: "
                        + parameter.getExportParameter().getDateFrom().toString());

                ValueSetVersion vsv = ((ValueSetVersion) requestListCodeSystemConcepts.getValueSet()
                        .getValueSetVersions().toArray()[0]);
                if (vsv.getConceptValueSetMemberships() == null
                        || vsv.getConceptValueSetMemberships().size() == 0) {
                    ConceptValueSetMembership cvsm = new ConceptValueSetMembership();
                    cvsm.setStatusDate(parameter.getExportParameter().getDateFrom());
                    vsv.getConceptValueSetMemberships().add(cvsm);
                } else {
                    ((ConceptValueSetMembership) vsv.getConceptValueSetMemberships().toArray()[0])
                            .setStatusDate(parameter.getExportParameter().getDateFrom());
                }
            }

            //ListCodeSystemConcepts abrufen
            ListValueSetContents lcsc = new ListValueSetContents();
            ListValueSetContentsResponseType responseListCodeSystemConcepts = lcsc
                    .ListValueSetContents(requestListCodeSystemConcepts, "");
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] ListValueSetContents abgerufen");

            org.hibernate.Session hb_session = HibernateUtil.getSessionFactory().openSession();
            try {
                String hqlM = "select distinct mp from MetadataParameter mp join mp.valueSet vs"
                        + " where vs.id=:id";

                org.hibernate.Query qM = hb_session.createQuery(hqlM);
                qM.setLong("id", parameter.getValueSet().getId());
                List<MetadataParameter> mlist = qM.list();

                //=================================================
                // CSV-Header erstellen und Dauerattribute auslesen
                //=================================================
                //csv.write("level");
                csv.write("code");
                csv.write("codeSystem");
                csv.write("displayName");
                csv.write("parentCode");
                csv.write("concept_Beschreibung");
                csv.write("meaning");
                csv.write("hints");
                int count = 0;
                for (MetadataParameter mp : mlist) {
                    String para = mp.getParamName();
                    String b = para.substring(0, 1);
                    b = b.toLowerCase();
                    para = b + para.substring(1);

                    csv.write(para); //lowerCase
                    paramList.put(count, mp.getParamName());//Normal UpperCase
                    count++;
                }

                //ENDE Header erstellen
                csv.endRecord();

                // Flaches Vokabular, einfach alle Eintrge exportieren
                for (CodeSystemEntity cse : responseListCodeSystemConcepts.getCodeSystemEntity()) {
                    for (CodeSystemEntityVersion csev : cse.getCodeSystemEntityVersions()) {
                        // Nur aktuellste Version exportieren
                        if (cse.getCurrentVersionId().longValue() == csev.getVersionId().longValue()) {

                            ConceptValueSetMembership cvsm = null;
                            for (ConceptValueSetMembership cvsmL : csev.getConceptValueSetMemberships()) {

                                Long cvsmLVsvId = cvsmL.getId().getValuesetVersionId();
                                Long paramVsvId = parameter.getValueSet().getValueSetVersions().iterator()
                                        .next().getVersionId();
                                Long cvsmCsevId = cvsmL.getId().getCodeSystemEntityVersionId();
                                Long paramCsevId = csev.getVersionId();
                                if ((cvsmLVsvId.equals(paramVsvId)) && (cvsmCsevId.equals(paramCsevId))) {
                                    cvsm = cvsmL;
                                    break;
                                }
                            }

                            // 1) nur Status=1
                            // 2) alle Status > 0, wenn Synchronisierungsdatum angegeben ist
                            if (cvsm != null && cvsm.getStatus() != null
                                    && (cvsm.getStatus() == 1 || (syncEnabled && cvsm.getStatus() > 0))) {
                                CodeSystemConcept csc = csev.getCodeSystemConcepts().iterator().next();

                                if (logger.isDebugEnabled())
                                    logger.debug("Schreibe Code: " + csc.getCode());

                                if (csc.getCode() != null) {
                                    csv.write(csc.getCode());
                                } else {
                                    csv.write("");
                                }
                                /*String hqlC = "select distinct csv from CodeSystemVersion csv join csv.codeSystemVersionEntityMemberships csvem join csvem.codeSystemEntity cse join cse.codeSystemEntityVersions csev"
                                 + " where csev.versionId=:versionId";
                                        
                                 org.hibernate.Query qC = hb_session.createQuery(hqlC);
                                 qC.setLong("versionId", csev.getVersionId());
                                        
                                 List<CodeSystemVersion> csvlist = qC.list();*/

                                if (cse.getCodeSystemVersionEntityMemberships().iterator().next()
                                        .getCodeSystemVersion().getOid() != null) {
                                    csv.write(cse.getCodeSystemVersionEntityMemberships().iterator().next()
                                            .getCodeSystemVersion().getOid());
                                } else {
                                    csv.write("");
                                }
                                /*if(csvlist.size() == 1){
                                        
                                 csv.write(csev.getCodeSystemEntity().getCodeSystemVersionEntityMemberships().iterator().next().getCodeSystemVersion().getOid());
                                 }else{
                                 csv.write("");
                                 }*/

                                if (csc.getTerm() != null) {
                                    csv.write(csc.getTerm());
                                } else {
                                    csv.write("");
                                }
                                csv.write("");
                                if (cvsm.getDescription() != null) {
                                    csv.write(cvsm.getDescription());
                                } else {
                                    csv.write("");
                                }

                                if (cvsm.getMeaning() != null) {
                                    csv.write(cvsm.getMeaning());
                                } else {
                                    csv.write("");
                                }

                                if (cvsm.getHints() != null) {
                                    csv.write(cvsm.getHints());
                                } else {
                                    csv.write("");
                                }

                                //Get vsmv for csev/cvsm
                                String hqlMv = "select distinct vsmv from ValueSetMetadataValue vsmv join vsmv.metadataParameter mp join vsmv.codeSystemEntityVersion csev"
                                        + " where vsmv.valuesetVersionId=:valuesetVersionId AND csev.versionId=:codeSystemEntityVersionId";

                                org.hibernate.Query qMv = hb_session.createQuery(hqlMv);
                                qMv.setLong("valuesetVersionId", parameter.getValueSet().getValueSetVersions()
                                        .iterator().next().getVersionId());
                                qMv.setLong("codeSystemEntityVersionId", csev.getVersionId());
                                List<ValueSetMetadataValue> vsmvList = qMv.list();

                                for (int i = 0; i < paramList.size(); i++) {

                                    ValueSetMetadataValue vsmv = null;
                                    for (ValueSetMetadataValue vsmvL : vsmvList) {

                                        if (vsmvL.getMetadataParameter().getParamName()
                                                .equals(paramList.get(i))) {
                                            vsmv = vsmvL;
                                            break;
                                        }
                                    }

                                    if (vsmv != null && vsmv.getParameterValue() != null) {
                                        csv.write(vsmv.getParameterValue());
                                    } else {
                                        csv.write("");
                                    }
                                }
                                csv.endRecord();
                                countExported++;
                            }
                        }
                    }
                }

                if (logger.isInfoEnabled())
                    logger.info("[ExportCSV] CSV-Inhalt erstellt");
            } catch (Exception ex) {
                logger.error(ex.getMessage());
                s = "Fehler (hibernate): " + ex.getLocalizedMessage();
            } finally {
                hb_session.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage());
            s = "Fehler: " + ex.getLocalizedMessage();
        }

        //CSV-Datei schliessen
        csv.close();
        //if (logger.isInfoEnabled())
        //  logger.info("[ExportCSV] CSV-Datei geschrieben. Dateipfad: " + csv_output_url);

        if (countExported > 0) {
            //countExported = count;

            //Filecontent setzen
            exportType.setFilecontent(bos.toByteArray());
            //Export-URL setzen
            //exportType.setUrl(csv_output_url);
            exportType.setUrl("");
            reponse.getReturnInfos()
                    .setMessage("Export abgeschlossen. " + countExported + " Konzepte exportiert.");
        } else {
            reponse.getReturnInfos().setMessage("Keine Konzepte exportiert.");
            if (logger.isInfoEnabled())
                logger.info("[ExportCSV] Kein Export erstellt...");
        }

        //Format-ID (CSV) setzen
        exportType.setFormatId(ExportValueSetContentRequestType.EXPORT_CSV_ID);

        //ExportInfos in Response schreiben
        reponse.setExportInfos(exportType);
        //hb_session.getTransaction().commit();

    } catch (Exception ex) {
        s = "Fehler: " + ex.getLocalizedMessage();
        ex.printStackTrace();
    }

    return s;
}

From source file:de.fhdo.terminologie.ws.administration._export.ExportValueSetSVS.java

License:Apache License

public String exportSVS(ExportValueSetContentResponseType reponse) {
    String s = ""; // Status-Meldung
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    ExportType exportType = new ExportType();
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    Document doc = null;/*from w  w  w  .jav a  2 s. co m*/

    try {
        builder = builderFactory.newDocumentBuilder();

        doc = builder.newDocument();
        //ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //StreamResult result = new StreamResult(bos);
        //TransformerFactory transformerFactory = TransformerFactory.newInstance();
        //Transformer transformer = transformerFactory.newTransformer();
        //DOMSource source = new DOMSource(doc);

        /*if (parameter.getExportInfos().isUpdateCheck())
        {
          //Request-Parameter fr ReturnValueSetDetails erstellen
          if (logger.isInfoEnabled())
            logger.info("[ExportSVS] Erstelle Request-Parameter fr ReturnValueSetDetails");
                
          ReturnValueSetDetailsRequestType requestValueSetDetails = new ReturnValueSetDetailsRequestType();
          requestValueSetDetails.setValueSet(parameter.getValueSet());
          requestValueSetDetails.getValueSet().getValueSetVersions().add((ValueSetVersion) parameter.getValueSet().getValueSetVersions().toArray()[0]);
          requestValueSetDetails.setLoginToken(parameter.getLoginToken());
                
          //ValueSetDetails abrufen
          ReturnValueSetDetails rcsd = new ReturnValueSetDetails();
          ReturnValueSetDetailsResponseType responseValueSetDetails = rcsd.ReturnValueSetDetails(requestValueSetDetails, "");
          if (logger.isInfoEnabled())
            logger.info("[ExportSVS] ReturnValueSetDetails abgerufen");
                
          if (responseValueSetDetails.getReturnInfos().getStatus() == ReturnType.Status.OK
        && responseValueSetDetails.getValueSet() != null)
          {
            if (!responseValueSetDetails.getValueSet().getCurrentVersionId().equals(((ValueSetVersion) parameter.getValueSet().getValueSetVersions().toArray()[0]).getVersionId()))
            {
              ((ValueSetVersion) parameter.getValueSet().getValueSetVersions().toArray()[0]).setVersionId(responseValueSetDetails.getValueSet().getCurrentVersionId());
            }
          }
        }*/

        // Hibernate-Block, Session ffnen
        org.hibernate.Session hb_session = HibernateUtil.getSessionFactory().openSession();
        try {
            String hql = "select distinct vsv from ValueSetVersion vsv join vsv.valueSet vs" + " where "
                    + " vsv.versionId=:versionId";

            org.hibernate.Query q = hb_session.createQuery(hql);
            //q.setLong("id", parameter.getValueSet().getId());
            q.setLong("versionId",
                    parameter.getValueSet().getValueSetVersions().iterator().next().getVersionId());

            List<ValueSetVersion> vsvList = q.list();
            ValueSetVersion vsv = null;
            if (vsvList != null && vsvList.size() == 1) {
                vsv = vsvList.get(0);
            }

            if (vsv != null) {
                //Erstellung Hauptknoten
                Element valueSet = doc.createElement("valueSet");
                doc.appendChild(valueSet);

                Attr name = doc.createAttribute("name");
                name.setValue(EscCharCheck.check(vsv.getValueSet().getName()));
                valueSet.setAttributeNode(name);

                Attr displayName = doc.createAttribute("displayName");
                displayName.setValue(EscCharCheck.check(vsv.getValueSet().getName()));
                valueSet.setAttributeNode(displayName);

                Attr effectiveDate = doc.createAttribute("effectiveDate");
                if (vsv.getReleaseDate() != null) {
                    effectiveDate.setValue(sdf.format(vsv.getReleaseDate()));
                    valueSet.setAttributeNode(effectiveDate);
                } else {
                    effectiveDate.setValue("");
                    valueSet.setAttributeNode(effectiveDate);
                }

                Attr id = doc.createAttribute("id");
                id.setValue(EscCharCheck.check(vsv.getOid()));
                valueSet.setAttributeNode(id);

                Attr statusCode = doc.createAttribute("statusCode");
                if (vsv.getStatus() == 1) {
                    statusCode.setValue("final");
                } else {
                    statusCode.setValue("not final");
                }
                valueSet.setAttributeNode(statusCode);

                Attr website = doc.createAttribute("website");
                website.setValue(EscCharCheck.check(vsv.getValueSet().getWebsite()));
                valueSet.setAttributeNode(website);

                Attr version = doc.createAttribute("version");
                version.setValue(EscCharCheck.check(vsv.getName()));
                valueSet.setAttributeNode(version);

                Attr beschreibung = doc.createAttribute("beschreibung");
                beschreibung.setValue(EscCharCheck.check(vsv.getValueSet().getDescription()));
                valueSet.setAttributeNode(beschreibung);

                Attr description = doc.createAttribute("description");
                description.setValue(EscCharCheck.check(vsv.getValueSet().getDescriptionEng()));
                valueSet.setAttributeNode(description);

                Element conceptList = doc.createElement("conceptList");
                valueSet.appendChild(conceptList);

                ListValueSetContentsRequestType requestListCodeSystemConcepts = new ListValueSetContentsRequestType();
                requestListCodeSystemConcepts.setValueSet(parameter.getValueSet());
                requestListCodeSystemConcepts.getValueSet().getValueSetVersions()
                        .add((ValueSetVersion) parameter.getValueSet().getValueSetVersions().toArray()[0]);
                requestListCodeSystemConcepts.setLoginToken(parameter.getLoginToken());
                //requestListCodeSystemConcepts.setLookForward(true);

                boolean syncEnabled = parameter.getExportParameter() != null
                        && parameter.getExportParameter().getDateFrom() != null;

                if (syncEnabled) {
                    // Datum fr Synchronisation hinzufgen
                    logger.debug("Datum fr Synchronisation hinzufgen: "
                            + parameter.getExportParameter().getDateFrom().toString());

                    ValueSetVersion vsvRequest = ((ValueSetVersion) requestListCodeSystemConcepts.getValueSet()
                            .getValueSetVersions().toArray()[0]);
                    if (vsvRequest.getConceptValueSetMemberships() == null
                            || vsvRequest.getConceptValueSetMemberships().size() == 0) {
                        ConceptValueSetMembership cvsm = new ConceptValueSetMembership();
                        cvsm.setStatusDate(parameter.getExportParameter().getDateFrom());
                        vsvRequest.getConceptValueSetMemberships().add(cvsm);
                    } else {
                        ((ConceptValueSetMembership) vsvRequest.getConceptValueSetMemberships().toArray()[0])
                                .setStatusDate(parameter.getExportParameter().getDateFrom());
                    }
                }

                //ListCodeSystemConcepts abrufen
                ListValueSetContents lcsc = new ListValueSetContents();
                ListValueSetContentsResponseType responseListCodeSystemConcepts = lcsc
                        .ListValueSetContents(requestListCodeSystemConcepts, hb_session, "");
                if (logger.isInfoEnabled())
                    logger.info("[ExportSVS] ListValueSetContents abgerufen");

                //SVS-Inhalt erstellen
                if (logger.isInfoEnabled())
                    logger.info("[ExportSVS] Erstelle SVS-Inhalt mit Konzepten...");

                // Flaches Vokabular, einfach alle Eintrge exportieren
                for (CodeSystemEntity cse : responseListCodeSystemConcepts.getCodeSystemEntity()) {
                    for (CodeSystemEntityVersion csev : cse.getCodeSystemEntityVersions()) {
                        // Nur aktuellste Version exportieren
                        if (cse.getCurrentVersionId().longValue() == csev.getVersionId().longValue()) {

                            ConceptValueSetMembership cvsm = null;
                            for (ConceptValueSetMembership cvsmL : csev.getConceptValueSetMemberships()) {
                                Long cvsmLVsvId = cvsmL.getId().getValuesetVersionId();
                                Long paramVsvId = parameter.getValueSet().getValueSetVersions().iterator()
                                        .next().getVersionId();
                                Long cvsmCsevId = cvsmL.getId().getCodeSystemEntityVersionId();
                                Long paramCsevId = csev.getVersionId();

                                if ((cvsmLVsvId.equals(paramVsvId)) && (cvsmCsevId.equals(paramCsevId))) {
                                    cvsm = cvsmL;
                                    break;
                                }
                            }

                            // 1) nur Status=1
                            // 2) alle Status > 0, wenn Synchronisierungsdatum angegeben ist
                            if (cvsm != null && cvsm.getStatus() != null
                                    && (cvsm.getStatus() == 1 || (syncEnabled && cvsm.getStatus() > 0))) {
                                CodeSystemConcept csc = csev.getCodeSystemConcepts().iterator().next();

                                if (logger.isDebugEnabled())
                                    logger.debug("Schreibe Code: " + csc.getCode());

                                Element concept = doc.createElement("concept");

                                Attr code = doc.createAttribute("code");
                                code.setValue(EscCharCheck.check(csc.getCode()));
                                concept.setAttributeNode(code);

                                Attr displayNameC = doc.createAttribute("displayName");
                                displayNameC.setValue(EscCharCheck.check(csc.getTerm()));
                                concept.setAttributeNode(displayNameC);

                                Attr concept_beschreibungC = doc.createAttribute("concept_beschreibung");
                                concept_beschreibungC.setValue(EscCharCheck.check(cvsm.getDescription()));
                                concept.setAttributeNode(concept_beschreibungC);

                                Attr deutschC = doc.createAttribute("deutsch");
                                deutschC.setValue(EscCharCheck.check(cvsm.getMeaning()));
                                concept.setAttributeNode(deutschC);

                                Attr hinweiseC = doc.createAttribute("hinweise");
                                hinweiseC.setValue(EscCharCheck.check(cvsm.getHints()));
                                concept.setAttributeNode(hinweiseC);

                                /*String hqlC = "select distinct csv from CodeSystemVersion csv join csv.codeSystemVersionEntityMemberships csvem join csvem.codeSystemEntity cse join cse.codeSystemEntityVersions csev"
                                 + " where csev.versionId=:versionId";
                                        
                                 org.hibernate.Query qC = hb_session.createQuery(hqlC);
                                 qC.setLong("versionId", parameter.getValueSet().getValueSetVersions().iterator().next().getVersionId());
                                        
                                 List<CodeSystemVersion> csvlist = qC.list();
                                 if(csvlist.size() == 1){*/
                                Attr codeSystem = doc.createAttribute("codeSystem");
                                codeSystem
                                        .setValue(EscCharCheck.check(cse.getCodeSystemVersionEntityMemberships()
                                                .iterator().next().getCodeSystemVersion().getOid()));//csvlist.get(0).getOid());
                                concept.setAttributeNode(codeSystem);
                                //}

                                String hqlM = "select distinct vsmv from ValueSetMetadataValue vsmv join vsmv.metadataParameter mp join vsmv.codeSystemEntityVersion csev"
                                        + " where vsmv.valuesetVersionId=:valuesetVersionId AND csev.versionId=:codeSystemEntityVersionId";

                                org.hibernate.Query qM = hb_session.createQuery(hqlM);
                                qM.setLong("valuesetVersionId", parameter.getValueSet().getValueSetVersions()
                                        .iterator().next().getVersionId());
                                qM.setLong("codeSystemEntityVersionId", csev.getVersionId());
                                List<ValueSetMetadataValue> mlist = qM.list();

                                Iterator<ValueSetMetadataValue> it = mlist.iterator();
                                if (!mlist.isEmpty()) {
                                    while (it.hasNext()) {

                                        ValueSetMetadataValue vsmv = (ValueSetMetadataValue) it.next();
                                        if (vsmv.getMetadataParameter().getParamName().equals("Level")) {
                                            Attr level = doc.createAttribute("level");
                                            if (vsmv.getParameterValue() != null) {
                                                level.setValue(EscCharCheck.check(vsmv.getParameterValue()));
                                            } else {
                                                level.setValue("");
                                            }
                                            concept.setAttributeNode(level);
                                        }
                                        if (vsmv.getMetadataParameter().getParamName().equals("Type")) {
                                            Attr type = doc.createAttribute("type");
                                            if (vsmv.getParameterValue() != null) {
                                                type.setValue(EscCharCheck.check(vsmv.getParameterValue()));
                                            } else {
                                                type.setValue("");
                                            }
                                            concept.setAttributeNode(type);
                                        }
                                        if (vsmv.getMetadataParameter().getParamName()
                                                .equals("Relationships")) {
                                            Attr relationships = doc.createAttribute("relationships");
                                            if (vsmv.getParameterValue() != null) {
                                                relationships
                                                        .setValue(EscCharCheck.check(vsmv.getParameterValue()));
                                            } else {
                                                relationships.setValue("");
                                            }
                                            concept.setAttributeNode(relationships);
                                        }
                                        if (vsmv.getMetadataParameter().getParamName()
                                                .equals("Einheit print")) {
                                            Attr einheit_print = doc.createAttribute("einheit_print");
                                            if (vsmv.getParameterValue() != null) {
                                                einheit_print
                                                        .setValue(EscCharCheck.check(vsmv.getParameterValue()));
                                            } else {
                                                einheit_print.setValue("");
                                            }
                                            concept.setAttributeNode(einheit_print);
                                        }
                                        if (vsmv.getMetadataParameter().getParamName()
                                                .equals("Einheit codiert")) {
                                            Attr einheit_codiert = doc.createAttribute("einheit_codiert");
                                            if (vsmv.getParameterValue() != null) {
                                                einheit_codiert
                                                        .setValue(EscCharCheck.check(vsmv.getParameterValue()));
                                            } else {
                                                einheit_codiert.setValue("");
                                            }
                                            concept.setAttributeNode(einheit_codiert);
                                        }
                                    }
                                } else {

                                    Attr level = doc.createAttribute("level");
                                    level.setValue("");
                                    concept.setAttributeNode(level);

                                    Attr type = doc.createAttribute("type");
                                    type.setValue("");
                                    concept.setAttributeNode(type);

                                    Attr relationships = doc.createAttribute("relationships");
                                    relationships.setValue("");
                                    concept.setAttributeNode(relationships);

                                    Attr einheit_print = doc.createAttribute("einheit_print");
                                    einheit_print.setValue("");
                                    concept.setAttributeNode(einheit_print);

                                    Attr einheit_codiert = doc.createAttribute("einheit_codiert");
                                    einheit_codiert.setValue("");
                                    concept.setAttributeNode(einheit_codiert);
                                }
                                conceptList.appendChild(concept);
                                countExported++;
                            }
                        }
                    }
                }

                if (logger.isInfoEnabled())
                    logger.info("[ExportSVS] SVS-Inhalt erstellt");
            } else {
                //hb_session.close();
                //throw new Exception("ExportSVS: Keine Ergebnisse oder ValueSetVersion existiert nicht");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage());
            s = "Fehler (hibernate): " + ex.getLocalizedMessage();
        } finally {
            hb_session.close();
        }

        if (countExported > 0) {

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer trans = tf.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            trans.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
            XMLFormatter formatter = new XMLFormatter();
            String formattedXml = formatter.format(output);
            formattedXml = formattedXml.replace("\"", "'");
            formattedXml = formattedXml.replace("&quot;", "\"");
            formattedXml = formattedXml.replace("&amp;", "&");
            formattedXml = formattedXml.replace("&lt;", "<");
            formattedXml = formattedXml.replace("&gt;", ">");
            formattedXml = formattedXml.replace("&apos;", "'");

            exportType.setFilecontent(formattedXml.getBytes("UTF-8"));

            exportType.setUrl("");
            reponse.getReturnInfos()
                    .setMessage("Export abgeschlossen. " + countExported + " Konzepte exportiert.");
        } else {
            reponse.getReturnInfos().setMessage("Keine Konzepte exportiert.");
            if (logger.isInfoEnabled())
                logger.info("[ExportSVS] Kein Export erstellt...");
        }

        //Format-ID (SVS) setzen
        exportType.setFormatId(ExportValueSetContentRequestType.EXPIRT_SVS_ID);

        //ExportInfos in Response schreiben
        reponse.setExportInfos(exportType);
        //hb_session.getTransaction().commit();

    } catch (Exception ex) {
        if (parameter.getValueSet().getValueSetVersions().iterator().next().getVersionId() == null) {
            s = "Fehler: VersionId muss angegeben werden!";
        } else {
            s = "Fehler: " + ex.getLocalizedMessage();
        }
        ex.printStackTrace();
    }

    return s;
}

From source file:de.fhdo.terminologie.ws.administration._import.ImportLOINC_V254.java

License:Apache License

public String importLOINC_Associations(ImportCodeSystemResponseType response) {
    StaticStatus.importCount = 0;/*from   w  ww . j av a 2  s . co  m*/
    StaticStatus.importTotal = 0;

    String s = "";
    //if (codesMap == null)
    //  codesMap = new HashMap<String, Long>();

    int count = 0, countFehler = 0;

    CsvReader csv;
    try {
        //slogger.debug("codesMap-Size: " + codesMap.size());

        byte[] bytes = parameter.getImportInfos().getFilecontent();
        logger.debug("convert to InputStream...");
        InputStream is = new ByteArrayInputStream(bytes);
        csv = new CsvReader(is, Charset.forName("ISO-8859-1"));
        csv.setDelimiter(',');
        csv.setUseTextQualifier(true);
        csv.readHeaders();
        logger.debug("Count header: " + csv.getHeaderCount());
        for (int i = 0; i < csv.getHeaderCount(); ++i)
            logger.debug("header: " + csv.getHeader(i));

        // Hibernate-Block, Session ffnen
        org.hibernate.Session hb_session = HibernateUtil.getSessionFactory().openSession();
        org.hibernate.Transaction tx = hb_session.beginTransaction();

        try // try-catch-Block zum Abfangen von Hibernate-Fehlern
        {
            if (parameter.getCodeSystem() == null || parameter.getCodeSystem().getId() == 0
                    || parameter.getCodeSystem().getCodeSystemVersions() == null
                    || parameter.getCodeSystem().getCodeSystemVersions().size() == 0) {
                // Fehlermeldung
                tx.rollback();
                HibernateUtil.getSessionFactory().close();
                return "No code system specified!";
            }

            CodeSystemVersion codesystemVersion = (CodeSystemVersion) parameter.getCodeSystem()
                    .getCodeSystemVersions().toArray()[0];
            logger.debug("CSV-name: " + codesystemVersion.getName());

            if ((codesystemVersion.getVersionId() == null || codesystemVersion.getVersionId() == 0)
                    && codesystemVersion.getName() != null && codesystemVersion.getName().length() > 0) {
                // find codesystem version-id from name
                logger.debug("find codesystem version-id from name: " + codesystemVersion.getName());

                Query q = hb_session.createQuery("select distinct csv from CodeSystemVersion csv"
                        + " join csv.codeSystem" + " where csv.name=:version_name and id=:cs_id");
                q.setString("version_name", codesystemVersion.getName());
                q.setLong("cs_id", parameter.getCodeSystem().getId());

                List<CodeSystemVersion> list = q.list();

                if (list != null && list.size() > 0) {
                    CodeSystemVersion csv_db = list.get(0);
                    codesystemVersion.setVersionId(csv_db.getVersionId());
                }
            }

            long csv_id = codesystemVersion.getVersionId();
            logger.debug("codesystem version id: " + csv_id);

            // read associations
            associationMap = new HashMap<String, AssociationType>();
            List<AssociationType> associationList = hb_session.createQuery("from AssociationType").list();
            for (int i = 0; i < associationList.size(); ++i) {
                associationMap.put(associationList.get(i).getForwardName(), associationList.get(i));
            }

            logger.debug("Start import...");

            int countEvery = 0;

            // load data
            while (csv.readRecord()) {
                countEvery++;

                CreateConceptAssociationRequestType request = new CreateConceptAssociationRequestType();
                request.setLoginToken(parameter.getLoginToken());

                request.setCodeSystemEntityVersionAssociation(new CodeSystemEntityVersionAssociation());

                String code1 = csv.get("LOINC");
                String code2 = csv.get("MAP_TO");
                String comment = csv.get("COMMENT");

                // CSV-ID fr LOINC-Code lesen
                long csev_id1 = getCSEV_VersionIdFromCode(code1, csv_id, hb_session);
                long csev_id2 = getCSEV_VersionIdFromCode(code2, csv_id, hb_session);

                //logger.warn(new Date().getTime() + ", Codes gelesen");
                if (csev_id1 > 0 && csev_id2 > 0) {
                    // IDs setzen
                    request.getCodeSystemEntityVersionAssociation()
                            .setCodeSystemEntityVersionByCodeSystemEntityVersionId1(
                                    new CodeSystemEntityVersion());
                    request.getCodeSystemEntityVersionAssociation()
                            .setCodeSystemEntityVersionByCodeSystemEntityVersionId2(
                                    new CodeSystemEntityVersion());

                    request.getCodeSystemEntityVersionAssociation()
                            .getCodeSystemEntityVersionByCodeSystemEntityVersionId1().setVersionId(csev_id1);
                    request.getCodeSystemEntityVersionAssociation()
                            .getCodeSystemEntityVersionByCodeSystemEntityVersionId2().setVersionId(csev_id2);

                    request.getCodeSystemEntityVersionAssociation().setAssociationKind(1); // ontologisch
                    request.getCodeSystemEntityVersionAssociation().setLeftId(csev_id1);

                    request.getCodeSystemEntityVersionAssociation().setAssociationType(new AssociationType());

                    // Assoziationstyp erhalten
                    if (comment != null && comment.length() > 0 && associationMap.containsKey(comment)) {
                        request.getCodeSystemEntityVersionAssociation().getAssociationType()
                                .setCodeSystemEntityVersionId(
                                        associationMap.get(comment).getCodeSystemEntityVersionId());
                    } else {
                        if (comment != null && comment.length() > 0) {
                            // Neuen Beziehungstyp einfgen
                            CreateConceptAssociationTypeRequestType requestAssociation = new CreateConceptAssociationTypeRequestType();
                            requestAssociation.setLoginToken(parameter.getLoginToken());
                            requestAssociation.setCodeSystem(parameter.getCodeSystem());
                            requestAssociation.setCodeSystemEntity(new CodeSystemEntity());
                            requestAssociation.getCodeSystemEntity()
                                    .setCodeSystemEntityVersions(new HashSet<CodeSystemEntityVersion>());
                            AssociationType at = new AssociationType();
                            if (comment.length() > 48)
                                at.setForwardName(comment.substring(0, 48));
                            else
                                at.setForwardName(comment);
                            at.setReverseName("");
                            CodeSystemEntityVersion csev = new CodeSystemEntityVersion();
                            csev.setAssociationTypes(new HashSet<AssociationType>());
                            csev.getAssociationTypes().add(at);
                            requestAssociation.getCodeSystemEntity().getCodeSystemEntityVersions().add(csev);

                            CreateConceptAssociationType ccat = new CreateConceptAssociationType();
                            CreateConceptAssociationTypeResponseType responseAssociation = ccat
                                    .CreateConceptAssociationType(requestAssociation, hb_session,
                                            loginInfoType);

                            if (responseAssociation.getReturnInfos().getStatus() == ReturnType.Status.OK) {
                                CodeSystemEntityVersion csev_result = (CodeSystemEntityVersion) responseAssociation
                                        .getCodeSystemEntity().getCodeSystemEntityVersions().toArray()[0];
                                request.getCodeSystemEntityVersionAssociation().getAssociationType()
                                        .setCodeSystemEntityVersionId(csev_result.getVersionId());
                            } else
                                request.getCodeSystemEntityVersionAssociation().getAssociationType()
                                        .setCodeSystemEntityVersionId(5l); // TODO gehrt zu
                        } else {
                            // Standard-Beziehung nehmen
                            request.getCodeSystemEntityVersionAssociation().getAssociationType()
                                    .setCodeSystemEntityVersionId(5l); // TODO gehrt zu
                        }
                    }

                    //logger.warn(new Date().getTime() + ", Assoziationstyp bestimmt");
                    StaticStatus.importCount++;
                    if (StaticStatus.importCount % 100 == 0)
                        logger.debug("Lese Datensatz " + StaticStatus.importCount + ", count: " + count);

                    // Beziehung speichern
                    // Dienst aufrufen (Konzept einfgen)
                    CreateConceptAssociation cca = new CreateConceptAssociation();
                    CreateConceptAssociationResponseType responseCCA = cca.CreateConceptAssociation(request,
                            hb_session, loginInfoType);

                    if (responseCCA.getReturnInfos().getStatus() == ReturnType.Status.OK) {
                        count++;

                        if (StaticStatus.importCount % 100 == 0)
                            logger.debug(
                                    "Neue Beziehung hinzugefgt, ID1: " + csev_id1 + ", ID2: " + csev_id2);
                    } else
                        countFehler++;

                    //logger.warn(new Date().getTime() + ", Assoziation in DB eingefgt");
                } else {
                    countFehler++;
                    logger.debug("Term ist nicht angegeben");
                }

                //logger.warn(new Date().getTime() + ", vor Speicherbereinigung");
                //Mimimum acceptable free memory you think your app needs 
                //long minRunningMemory = (1024 * 1024);
                //Runtime runtime = Runtime.getRuntime();
                if (countEvery % 500 == 0) {
                    //logger.debug("FreeMemory: " + runtime.freeMemory());

                    // wichtig, sonst kommt es bei greren Dateien zum Java-Heapspace-Fehler
                    hb_session.flush();
                    hb_session.clear();

                    if (countEvery % 1000 == 0) {
                        // sicherheitshalber aufrufen
                        System.gc();
                    }
                }

                //logger.warn(new Date().getTime() + ", nach Speicherbereinigung");
                //logger.warn(new Date().getTime() + ", Lese nchsten Record");
                csv.skipLine();

                if (countFehler > 10)
                    break;
            }

            if (count == 0 || countFehler > 10) {
                tx.rollback();
                response.getReturnInfos().setMessage("No associations imported. Count errors: " + countFehler);
            } else {
                logger.debug("Import completed, speicher Ergebnisse in DB (commit): " + count);
                tx.commit();
                countImported = count;
                response.getReturnInfos().setMessage(
                        "Import completed. " + count + " associations imported, " + countFehler + " errors.");
            }
        } catch (Exception ex) {
            LoggingOutput.outputException(ex, this);
            logger.error("Error while importing LOINC-associations: " + ex.getMessage());
            s = "Error while importing LOINC-associations: " + ex.getLocalizedMessage();

            try {
                tx.rollback();
                logger.info("[ImportLOINC.java] Rollback durchgefhrt!");
            } catch (Exception exRollback) {
                logger.info(exRollback.getMessage());
                logger.info("[ImportLOINC.java] Rollback fehlgeschlagen!");
            }
        } finally {
            // Session schlieen
            HibernateUtil.getSessionFactory().close();
        }

    } catch (Exception ex) {
        s = "Error while importing LOINC associations: " + ex.getLocalizedMessage();
        LoggingOutput.outputException(ex, this);
    }

    associationMap.clear();
    associationMap = null;
    //codesMap.clear();
    //codesMap = null;

    logger.debug("ImportLOINC-associations - completed");
    return s;
}

From source file:de.fhdo.terminologie.ws.administration._import.ImportLOINC_V254.java

License:Apache License

private long getCSEV_VersionIdFromCode(String code, long csv_id, Session hb_session) {
    //String hql = "from CodeSystemConcept"

    Query q = hb_session.createQuery(
            "select distinct csc from CodeSystemConcept csc" + " join csc.codeSystemEntityVersion csev"
                    + " join csev.codeSystemEntity cse" + " join cse.codeSystemVersionEntityMemberships csvem"
                    + " where code=:s_code and codeSystemVersionId=:csv_id");
    q.setString("s_code", code);
    q.setLong("csv_id", csv_id);
    List<CodeSystemConcept> list = q.list();

    if (list != null && list.size() > 0) {
        CodeSystemConcept csc = list.get(0);
        return csc.getCodeSystemEntityVersionId();
    } else {//from   ww  w.j  av  a 2 s. c o m
        logger.warn("Concept with code '" + code + "' not found in map!");
    }

    /*if (codesMap.containsKey(code))
     return codesMap.get(code);
     else
     {
     logger.warn("Concept with code '" + code + "' not found in map!");
     }*/
    return 0;
}