Search in sources :

Example 1 with ModelHelper

use of org.bimserver.plugins.ModelHelper in project BIMserver by opensourceBIM.

the class GeometryGenerator method generateGeometry.

@SuppressWarnings("unchecked")
public GenerateGeometryResult generateGeometry(RenderEnginePool renderEnginePool, final PluginManager pluginManager, final DatabaseSession databaseSession, final IfcModelInterface model, final int pid, final int rid, final boolean store, GeometryCache geometryCache) throws BimserverDatabaseException, GeometryGeneratingException, ObjectAlreadyExistsException, IfcModelInterfaceException {
    GenerateGeometryResult generateGeometryResult = new GenerateGeometryResult();
    packageMetaData = model.getPackageMetaData();
    productClass = packageMetaData.getEClass("IfcProduct");
    productRepresentationClass = packageMetaData.getEClass("IfcProductRepresentation");
    geometryFeature = productClass.getEStructuralFeature("geometry");
    representationFeature = productClass.getEStructuralFeature("Representation");
    representationsFeature = productRepresentationClass.getEStructuralFeature("Representations");
    if (geometryCache != null && !geometryCache.isEmpty()) {
        returnCachedData(model, geometryCache, databaseSession, pid, rid, store);
        return null;
    }
    long start = System.nanoTime();
    String pluginName = "";
    if (model.getPackageMetaData().getSchema() == Schema.IFC4) {
        pluginName = "org.bimserver.ifc.step.serializer.Ifc4StepSerializerPlugin";
    } else if (model.getPackageMetaData().getSchema() == Schema.IFC2X3TC1) {
        pluginName = "org.bimserver.ifc.step.serializer.Ifc2x3tc1StepSerializerPlugin";
    }
    try {
        final SerializerPlugin ifcSerializerPlugin = (SerializerPlugin) pluginManager.getPlugin(pluginName, true);
        if (ifcSerializerPlugin == null) {
            throw new UserException("No IFC serializer found");
        }
        int maxSimultanousThreads = Math.min(bimServer.getServerSettingsCache().getServerSettings().getRenderEngineProcesses(), Runtime.getRuntime().availableProcessors());
        maxSimultanousThreads = 1;
        final RenderEngineSettings settings = new RenderEngineSettings();
        settings.setPrecision(Precision.SINGLE);
        settings.setIndexFormat(IndexFormat.AUTO_DETECT);
        settings.setGenerateNormals(true);
        settings.setGenerateTriangles(true);
        settings.setGenerateWireFrame(false);
        final RenderEngineFilter renderEngineFilter = new RenderEngineFilter();
        if (maxSimultanousThreads == 1) {
            Runner runner = new Runner(null, renderEnginePool, databaseSession, settings, store, model, ifcSerializerPlugin, model, pid, rid, null, renderEngineFilter, generateGeometryResult);
            runner.run();
        } else {
            Set<EClass> classes = new HashSet<>();
            for (IdEObject object : model.getAllWithSubTypes(packageMetaData.getEClass("IfcProduct"))) {
                IdEObject representation = (IdEObject) object.eGet(representationFeature);
                if (representation != null && ((List<?>) representation.eGet(representationsFeature)).size() > 0) {
                    classes.add(object.eClass());
                }
            }
            if (classes.size() == 0) {
                return null;
            }
            classes.remove(packageMetaData.getEClass("IfcAnnotation"));
            classes.remove(packageMetaData.getEClass("IfcOpeningElement"));
            LOGGER.debug("Using " + maxSimultanousThreads + " processes for geometry generation");
            ThreadPoolExecutor executor = new ThreadPoolExecutor(maxSimultanousThreads, maxSimultanousThreads, 24, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(classes.size()));
            final Map<IdEObject, IdEObject> bigMap = new HashMap<IdEObject, IdEObject>();
            OidProvider oidProvider = new OidProvider() {

                @Override
                public long newOid(EClass eClass) {
                    return databaseSession.newOid(eClass);
                }
            };
            for (final EClass eClass : classes) {
                final BasicIfcModel targetModel = new BasicIfcModel(model.getPackageMetaData(), null);
                ModelHelper modelHelper = new ModelHelper(bimServer.getMetaDataManager(), targetModel);
                modelHelper.setOidProvider(oidProvider);
                IdEObject newOwnerHistory = modelHelper.copyBasicObjects(model, bigMap);
                for (IdEObject idEObject : model.getAll(eClass)) {
                    IdEObject newObject = modelHelper.copy(idEObject, false);
                    modelHelper.copyDecomposes(idEObject, newOwnerHistory);
                    bigMap.put(newObject, idEObject);
                    if (packageMetaData.getEClass("IfcElement").isSuperTypeOf(eClass)) {
                        EStructuralFeature hasOpeningsFeature = idEObject.eClass().getEStructuralFeature("HasOpenings");
                        for (IdEObject ifcRelVoidsElement : ((List<IdEObject>) idEObject.eGet(hasOpeningsFeature))) {
                            bigMap.put(modelHelper.copy(ifcRelVoidsElement, false), ifcRelVoidsElement);
                            EStructuralFeature relatedOpeningElementFeature = ifcRelVoidsElement.eClass().getEStructuralFeature("RelatedOpeningElement");
                            IdEObject relatedOpeningElement = (IdEObject) ifcRelVoidsElement.eGet(relatedOpeningElementFeature);
                            if (relatedOpeningElement != null) {
                                bigMap.put(modelHelper.copy(relatedOpeningElement, false), relatedOpeningElement);
                            }
                        }
                    }
                }
                executor.submit(new Runner(eClass, renderEnginePool, databaseSession, settings, store, targetModel, ifcSerializerPlugin, model, pid, rid, bigMap, renderEngineFilter, generateGeometryResult));
            }
            executor.shutdown();
            executor.awaitTermination(24, TimeUnit.HOURS);
        }
        long end = System.nanoTime();
        LOGGER.info("Rendertime: " + ((end - start) / 1000000) + "ms, " + "Reused: " + Formatters.bytesToString(bytesSaved.get()) + ", Total: " + Formatters.bytesToString(totalBytes.get()) + ", Final: " + Formatters.bytesToString(totalBytes.get() - bytesSaved.get()));
    } catch (Exception e) {
        LOGGER.error("", e);
        throw new GeometryGeneratingException(e);
    }
    return generateGeometryResult;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) EClass(org.eclipse.emf.ecore.EClass) OidProvider(org.bimserver.emf.OidProvider) List(java.util.List) UserException(org.bimserver.shared.exceptions.UserException) HashSet(java.util.HashSet) ModelHelper(org.bimserver.plugins.ModelHelper) IdEObject(org.bimserver.emf.IdEObject) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) SerializerPlugin(org.bimserver.plugins.serializers.SerializerPlugin) BasicIfcModel(org.bimserver.ifc.BasicIfcModel) IfcModelInterfaceException(org.bimserver.emf.IfcModelInterfaceException) UserException(org.bimserver.shared.exceptions.UserException) EntityNotFoundException(org.bimserver.plugins.renderengine.EntityNotFoundException) ObjectAlreadyExistsException(org.bimserver.plugins.ObjectAlreadyExistsException) RenderEngineException(org.bimserver.plugins.renderengine.RenderEngineException) RenderEngineFilter(org.bimserver.plugins.renderengine.RenderEngineFilter) RenderEngineSettings(org.bimserver.plugins.renderengine.RenderEngineSettings) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 2 with ModelHelper

use of org.bimserver.plugins.ModelHelper in project BIMserver by opensourceBIM.

the class DownloadByNewJsonQueryDatabaseAction method execute.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public IfcModelInterface execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    List<String> projectNames = new ArrayList<>();
    PluginConfiguration serializerPluginConfiguration = getDatabaseSession().get(StorePackage.eINSTANCE.getPluginConfiguration(), serializerOid, OldQuery.getDefault());
    SerializerPlugin serializerPlugin = (SerializerPlugin) getBimServer().getPluginManager().getPlugin(serializerPluginConfiguration.getPluginDescriptor().getPluginClassName(), true);
    Set<String> geometryFields = serializerPlugin.getRequiredGeometryFields();
    setProgress("Querying database...", -1);
    for (long roid : roids) {
        Revision revision = getDatabaseSession().get(StorePackage.eINSTANCE.getRevision(), roid, OldQuery.getDefault());
        projectNames.add(revision.getProject().getName() + "." + revision.getId());
    }
    String name = Joiner.on("-").join(projectNames);
    PackageMetaData lastPackageMetaData = null;
    Project lastProject = null;
    IfcModelSet ifcModelSet = new IfcModelSet();
    Map<Integer, Long> pidRoidMap = new HashMap<>();
    Set<CanInclude> updatedIncludes = new HashSet<>();
    for (long roid : roids) {
        Revision revision = getDatabaseSession().get(StorePackage.eINSTANCE.getRevision(), roid, OldQuery.getDefault());
        lastProject = revision.getProject();
        PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData(revision.getProject().getSchema());
        lastPackageMetaData = packageMetaData;
        JsonQueryObjectModelConverter converter = new JsonQueryObjectModelConverter(packageMetaData);
        try {
            ObjectNode queryObject = OBJECT_MAPPER.readValue(json, ObjectNode.class);
            converter.setCopyExternalDefines(true);
            Query query = converter.parseJson("query", (ObjectNode) queryObject);
            // We now have the original user query, we'll amend it a little bit to include geometry, but only if the serializer requires certain fields
            // TODO only checking the base level of the query now, should check recursive and possibly more
            // System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(new JsonQueryObjectModelConverter(packageMetaData).toJson(query)));
            pidRoidMap.put(revision.getProject().getId(), roid);
            IfcModelInterface ifcModel = getDatabaseSession().createServerModel(packageMetaData, pidRoidMap);
            ifcModelSet.add(ifcModel);
            Query secondQuery = new Query("second", query.getPackageMetaData());
            QueryPart queryPart2 = secondQuery.createQueryPart();
            if (geometryFields != null) {
                for (String defineName : query.getDefines().keySet()) {
                    Include define = query.getDefine(defineName);
                    apply(geometryFields, packageMetaData, define, updatedIncludes);
                }
                for (QueryPart queryPart : query.getQueryParts()) {
                    apply(geometryFields, packageMetaData, queryPart, updatedIncludes);
                    if (queryPart.hasReferences()) {
                        for (Reference reference : queryPart.getReferences()) {
                            apply(geometryFields, packageMetaData, reference.getInclude(), updatedIncludes);
                        }
                    }
                    if (queryPart.hasIncludes()) {
                        apply(geometryFields, packageMetaData, queryPart, updatedIncludes);
                    }
                    if (queryPart.hasTypes()) {
                        for (TypeDef typeDef : queryPart.getTypes()) {
                            if (packageMetaData.getEClass("IfcProduct").isSuperTypeOf(typeDef.geteClass())) {
                                Include include = queryPart.createInclude();
                                applyFields(geometryFields, new TypeDef(packageMetaData.getEClass("IfcProduct"), true), include);
                            }
                        }
                    }
                    if (queryPart.isIncludeAllFields()) {
                        Include newInclude = queryPart.createInclude();
                        applyFields(geometryFields, new TypeDef(packageMetaData.getEClass("IfcProduct"), true), newInclude);
                    }
                }
            }
            QueryObjectProvider queryObjectProvider = new QueryObjectProvider(getDatabaseSession(), getBimServer(), query, Collections.singleton(roid), packageMetaData);
            HashMapVirtualObject next = queryObjectProvider.next();
            while (next != null) {
                IdEObject newObject = packageMetaData.create(next.eClass());
                IdEObjectImpl idEObjectImpl = (IdEObjectImpl) newObject;
                idEObjectImpl.setPid(revision.getProject().getId());
                idEObjectImpl.setOid(next.getOid());
                for (EAttribute eAttribute : newObject.eClass().getEAllAttributes()) {
                    Object value = next.eGet(eAttribute);
                    if (eAttribute.isMany()) {
                        List<?> list = (List<?>) value;
                        if (list != null) {
                            AbstractEList targetList = (AbstractEList) newObject.eGet(eAttribute);
                            for (Object item : list) {
                                targetList.addUnique(item);
                            }
                        }
                    } else {
                        if (value != null || eAttribute.isUnsettable()) {
                            newObject.eSet(eAttribute, value);
                        }
                    }
                }
                ifcModel.add(next.getOid(), newObject);
                queryPart2.addOid(next.getOid());
                next = queryObjectProvider.next();
            }
            if (geometryFields != null) {
                for (QueryPart queryPart : secondQuery.getQueryParts()) {
                    apply(geometryFields, packageMetaData, queryPart, updatedIncludes);
                // if (queryPart.hasReferences()) {
                // for (Reference reference : queryPart.getReferences()) {
                // apply(geometryFields, packageMetaData, reference.getInclude(), updatedIncludes);
                // }
                // }
                // if (queryPart.hasIncludes()) {
                // apply(geometryFields, packageMetaData, queryPart, updatedIncludes);
                // }
                // if (queryPart.hasTypes()) {
                // for (TypeDef typeDef : queryPart.getTypes()) {
                // if (packageMetaData.getEClass("IfcProduct").isSuperTypeOf(typeDef.geteClass())) {
                // Include include = queryPart.createInclude();
                // applyFields(geometryFields, new TypeDef(packageMetaData.getEClass("IfcProduct"), true), include);
                // }
                // }
                // }
                // if (queryPart.isIncludeAllFields()) {
                // Include newInclude = queryPart.createInclude();
                // applyFields(geometryFields, new TypeDef(packageMetaData.getEClass("IfcProduct"), true), newInclude);
                // }
                }
            }
            queryObjectProvider = new QueryObjectProvider(getDatabaseSession(), getBimServer(), secondQuery, Collections.singleton(roid), packageMetaData);
            System.out.println(converter.toJson(secondQuery));
            next = queryObjectProvider.next();
            while (next != null) {
                IdEObject idEObject = ifcModel.get(next.getOid());
                if (idEObject == null) {
                    throw new RuntimeException("Object not found");
                }
                if (idEObject.eClass() != next.eClass()) {
                    // Something is wrong
                    throw new RuntimeException("Classes not the same");
                }
                for (EReference eReference : idEObject.eClass().getEAllReferences()) {
                    if (eReference.isMany()) {
                        List refOids = (List) next.eGet(eReference);
                        AbstractEList<IdEObject> list = (AbstractEList<IdEObject>) idEObject.eGet(eReference);
                        if (refOids != null) {
                            for (Object refOid : refOids) {
                                if (refOid instanceof Long) {
                                    IdEObject ref = ifcModel.get((long) refOid);
                                    if (ref != null) {
                                        if (eReference.isUnique()) {
                                            list.add(ref);
                                        } else {
                                            list.addUnique(ref);
                                        }
                                    // } else {
                                    // throw new BimserverDatabaseException("Could not find reference to " + eReference.getName() + " " + refOid);
                                    }
                                } else if (refOid instanceof HashMapWrappedVirtualObject) {
                                // IdEObject ref = ifcModel.get(((HashMapWrappedVirtualObject) refOid).get);
                                // if (ref != null) {
                                // list.add(ref);
                                // }
                                } else if (refOid instanceof HashMapVirtualObject) {
                                    HashMapVirtualObject hashMapVirtualObject = (HashMapVirtualObject) refOid;
                                    IdEObject listObject = packageMetaData.create(hashMapVirtualObject.eClass());
                                    List subList = (List<?>) hashMapVirtualObject.get("List");
                                    List newList = (List<?>) listObject.eGet(listObject.eClass().getEStructuralFeature("List"));
                                    for (Object o : subList) {
                                        if (o instanceof HashMapWrappedVirtualObject) {
                                            newList.add(convertWrapped(revision, ifcModel, (HashMapWrappedVirtualObject) o));
                                        } else if (o instanceof Long) {
                                            LOGGER.warn("TODO");
                                        // TODO
                                        } else {
                                            newList.add(o);
                                        }
                                    }
                                    list.addUnique(listObject);
                                } else {
                                    throw new BimserverDatabaseException("Unimplemented");
                                }
                            }
                        }
                    } else {
                        Object r = next.eGet(eReference);
                        if (r instanceof Long) {
                            long refOid = (Long) r;
                            IdEObject referred = ifcModel.get(refOid);
                            if (referred == null) {
                                System.out.println(eReference.getName() + " " + refOid);
                            }
                            idEObject.eSet(eReference, referred);
                        } else if (r instanceof HashMapWrappedVirtualObject) {
                            idEObject.eSet(eReference, convertWrapped(revision, ifcModel, (HashMapWrappedVirtualObject) r));
                        } else if (r instanceof HashMapVirtualObject) {
                            throw new BimserverDatabaseException("Unimplemented");
                        } else if (r == null) {
                        } else {
                            throw new BimserverDatabaseException("Unimplemented");
                        }
                    }
                }
                next = queryObjectProvider.next();
            }
            ifcModel.getModelMetaData().setName(name);
            ifcModel.getModelMetaData().setRevisionId(1);
            if (getAuthorization().getUoid() != -1) {
                ifcModel.getModelMetaData().setAuthorizedUser(getUserByUoid(getAuthorization().getUoid()).getName());
            }
            ifcModel.getModelMetaData().setDate(new Date());
        } catch (Throwable e) {
            throw new BimserverDatabaseException(e);
        }
    }
    IfcModelInterface ifcModel = getDatabaseSession().createServerModel(lastPackageMetaData, pidRoidMap);
    if (ifcModelSet.size() > 1) {
        setProgress("Merging IFC data...", -1);
        try {
            ifcModel = getBimServer().getMergerFactory().createMerger(getDatabaseSession(), getAuthorization().getUoid()).merge(lastProject, ifcModelSet, new ModelHelper(getBimServer().getMetaDataManager(), ifcModel));
        } catch (MergeException e) {
            throw new UserException(e);
        }
    } else {
        ifcModel = ifcModelSet.iterator().next();
    }
    ifcModel.getModelMetaData().setName(name);
    // ifcModel.getModelMetaData().setRevisionId(project.getRevisions().indexOf(virtualRevision) + 1);
    if (getAuthorization().getUoid() != -1) {
        ifcModel.getModelMetaData().setAuthorizedUser(getUserByUoid(getAuthorization().getUoid()).getName());
    }
    ifcModel.getModelMetaData().setDate(new Date());
    return ifcModel;
// for (Long roid : roids) {
// Revision virtualRevision = getRevisionByRoid(roid);
// pidRoidMap.put(virtualRevision.getProject().getId(), virtualRevision.getOid());
// project = virtualRevision.getProject();
// name += project.getName() + "-" + virtualRevision.getId() + "-";
// try {
// getAuthorization().canDownload(roid);
// } catch (UserException e) {
// if (!getAuthorization().hasRightsOnProjectOrSuperProjectsOrSubProjects(user, project)) {
// throw new UserException("User has insufficient rights to download revisions from this project");
// }
// if (!getAuthorization().hasRightsOnProjectOrSuperProjectsOrSubProjects(user, project)) {
// throw new UserException("User has insufficient rights to download revisions from this project");
// }
// }
// int size = 0;
// 
// for (ConcreteRevision concreteRevision : virtualRevision.getConcreteRevisions()) {
// try {
// int highestStopId = findHighestStopRid(project, concreteRevision);
// 
// PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData(concreteRevision.getProject().getSchema());
// lastPackageMetaData = packageMetaData;
// IfcModelInterface subModel = new ServerIfcModel(packageMetaData, pidRoidMap, getDatabaseSession());
// 
// OldQuery databaseQuery = new OldQuery(packageMetaData, concreteRevision.getProject().getId(), concreteRevision.getId(), virtualRevision.getOid(), null, Deep.NO, highestStopId);
// databaseQuery.updateOidCounters(concreteRevision, getDatabaseSession());
// JsonObject queryObject = (JsonObject)query;
// JsonArray queries = queryObject.get("queries").getAsJsonArray();
// for (JsonElement queryElement : queries) {
// processQueryPart(packageMetaData, queryObject, (JsonObject) queryElement, subModel, databaseQuery);
// }
// 
// size += subModel.size();
// subModel.getModelMetaData().setDate(concreteRevision.getDate());
// subModel.fixInverseMismatches();
// checkGeometry(serializerPluginConfiguration, getBimServer().getPluginManager(), subModel, project, concreteRevision, virtualRevision);
// ifcModelSet.add(subModel);
// } catch (GeometryGeneratingException | IfcModelInterfaceException e) {
// throw new UserException(e);
// }
// }
// 
// }
// TODO check, double merging??
// IfcModelInterface ifcModel = new BasicIfcModel(lastPackageMetaData, pidRoidMap);
// if (ifcModelSet.size() > 1) {
// try {
// ifcModel = getBimServer().getMergerFactory().createMerger(getDatabaseSession(), getAuthorization().getUoid()).merge(project, ifcModelSet, new ModelHelper(getBimServer().getMetaDataManager(), ifcModel));
// } catch (MergeException e) {
// throw new UserException(e);
// }
// } else {
// ifcModel = ifcModelSet.iterator().next();
// }
// if (name.endsWith("-")) {
// name = name.substring(0, name.length()-1);
// }
}
Also used : IdEObjectImpl(org.bimserver.emf.IdEObjectImpl) AbstractEList(org.eclipse.emf.common.util.AbstractEList) JsonQueryObjectModelConverter(org.bimserver.database.queries.om.JsonQueryObjectModelConverter) OldQuery(org.bimserver.database.OldQuery) Query(org.bimserver.database.queries.om.Query) HashMapWrappedVirtualObject(org.bimserver.shared.HashMapWrappedVirtualObject) HashMap(java.util.HashMap) IfcModelInterface(org.bimserver.emf.IfcModelInterface) QueryPart(org.bimserver.database.queries.om.QueryPart) ArrayList(java.util.ArrayList) Include(org.bimserver.database.queries.om.Include) CanInclude(org.bimserver.database.queries.om.CanInclude) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) EAttribute(org.eclipse.emf.ecore.EAttribute) TypeDef(org.bimserver.database.queries.om.Include.TypeDef) MergeException(org.bimserver.plugins.modelmerger.MergeException) QueryObjectProvider(org.bimserver.database.queries.QueryObjectProvider) PluginConfiguration(org.bimserver.models.store.PluginConfiguration) List(java.util.List) ArrayList(java.util.ArrayList) AbstractEList(org.eclipse.emf.common.util.AbstractEList) UserException(org.bimserver.shared.exceptions.UserException) EReference(org.eclipse.emf.ecore.EReference) HashSet(java.util.HashSet) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ModelHelper(org.bimserver.plugins.ModelHelper) IdEObject(org.bimserver.emf.IdEObject) PackageMetaData(org.bimserver.emf.PackageMetaData) Reference(org.bimserver.database.queries.om.Reference) EReference(org.eclipse.emf.ecore.EReference) SerializerPlugin(org.bimserver.plugins.serializers.SerializerPlugin) Date(java.util.Date) Project(org.bimserver.models.store.Project) CanInclude(org.bimserver.database.queries.om.CanInclude) Revision(org.bimserver.models.store.Revision) HashMapVirtualObject(org.bimserver.shared.HashMapVirtualObject) IfcModelSet(org.bimserver.plugins.IfcModelSet) HashMapWrappedVirtualObject(org.bimserver.shared.HashMapWrappedVirtualObject) HashMapVirtualObject(org.bimserver.shared.HashMapVirtualObject) IdEObject(org.bimserver.emf.IdEObject)

Example 3 with ModelHelper

use of org.bimserver.plugins.ModelHelper in project BIMserver by opensourceBIM.

the class DownloadCompareDatabaseAction method execute.

@Override
public IfcModelInterface execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException, ServerException {
    try {
        Revision revision1 = getRevisionByRoid(roid1);
        Revision revision2 = getRevisionByRoid(roid2);
        Project project = revision1.getProject();
        // bimServer.getCompareCache().getCompareResults(roid1,
        CompareResult compareResults = null;
        // roid2, compareType,
        // compareIdentifier);
        IfcModelInterface model1 = new DownloadDatabaseAction(getBimServer(), getDatabaseSession(), getAccessMethod(), roid1, -1, -1, getAuthorization()).execute();
        ModelMerger merger = getBimServer().getMergerFactory().createMerger(getDatabaseSession(), getAuthorization().getUoid());
        PackageMetaData packageMetaData = model1.getPackageMetaData();
        IfcModelInterface mergedModel = getDatabaseSession().createServerModel(packageMetaData, null);
        try (DatabaseSession secondSession = getBimServer().getDatabase().createSession(OperationType.READ_ONLY)) {
            IfcModelInterface model2 = new DownloadDatabaseAction(getBimServer(), secondSession, getAccessMethod(), roid2, -1, -1, getAuthorization()).execute();
            try {
                compareResults = getModelCompare().compare(model1, model2, compareType);
            } catch (ModelCompareException e) {
                throw new UserException(e);
            }
            // bimServer.getCompareCache().storeResults(roid1, roid2,
            // compareType, compareIdentifier, compareResults);
            mergedModel = merger.merge(project, new IfcModelSet(model1, model2), new ModelHelper(getBimServer().getMetaDataManager(), mergedModel));
        }
        mergedModel.getModelMetaData().setName(project.getName() + "." + revision1.getId() + "." + revision2.getId());
        Set<Long> added = new HashSet<Long>();
        Set<Long> modified = new HashSet<Long>();
        Set<Long> deleted = new HashSet<Long>();
        for (CompareContainer compareContainer : compareResults.getItems()) {
            for (CompareItem compareItem : compareContainer.getItems()) {
                DataObject dataObject = compareItem.getDataObject();
                if (compareItem instanceof ObjectAdded) {
                    added.add(dataObject.getOid());
                } else if (compareItem instanceof ObjectModified) {
                    modified.add(dataObject.getOid());
                } else if (compareItem instanceof ObjectRemoved) {
                    deleted.add(dataObject.getOid());
                }
            }
        }
        EClass ifcColourRgbClass = packageMetaData.getEClass("IfcColourRgb");
        EStructuralFeature nameFeature = ifcColourRgbClass.getEStructuralFeature("Name");
        EStructuralFeature redFeature = ifcColourRgbClass.getEStructuralFeature("Red");
        EStructuralFeature greenFeature = ifcColourRgbClass.getEStructuralFeature("Green");
        EStructuralFeature blueFeature = ifcColourRgbClass.getEStructuralFeature("Blue");
        IdEObject red = mergedModel.createAndAdd(ifcColourRgbClass);
        red.eSet(nameFeature, "red");
        red.eSet(redFeature, 0.5D);
        red.eSet(greenFeature, 0.0D);
        red.eSet(blueFeature, 0.0D);
        IdEObject green = mergedModel.createAndAdd(ifcColourRgbClass);
        green.eSet(nameFeature, "green");
        green.eSet(redFeature, 0D);
        green.eSet(greenFeature, 0.5D);
        green.eSet(blueFeature, 0D);
        IdEObject blue = mergedModel.createAndAdd(ifcColourRgbClass);
        blue.eSet(nameFeature, "blue");
        blue.eSet(redFeature, 0D);
        blue.eSet(greenFeature, 0D);
        blue.eSet(blueFeature, 0.5D);
        for (IdEObject product : mergedModel.getAllWithSubTypes(packageMetaData.getEClass("IfcProduct"))) {
            IdEObject color = null;
            if (added.contains(product.getOid())) {
                color = green;
            } else if (deleted.contains(product.getOid())) {
                color = red;
            } else if (modified.contains(product.getOid())) {
                color = blue;
            }
            if (color != null) {
                setColor(mergedModel, product, color);
            }
        }
        mergedModel.fixOidCounter();
        return mergedModel;
    } catch (IfcModelInterfaceException e) {
        throw new UserException(e);
    } catch (MergeException e) {
        throw new UserException(e);
    }
}
Also used : DatabaseSession(org.bimserver.database.DatabaseSession) IfcModelInterface(org.bimserver.emf.IfcModelInterface) CompareResult(org.bimserver.models.store.CompareResult) IfcModelInterfaceException(org.bimserver.emf.IfcModelInterfaceException) EClass(org.eclipse.emf.ecore.EClass) MergeException(org.bimserver.plugins.modelmerger.MergeException) CompareContainer(org.bimserver.models.store.CompareContainer) UserException(org.bimserver.shared.exceptions.UserException) ModelMerger(org.bimserver.plugins.modelmerger.ModelMerger) HashSet(java.util.HashSet) ModelHelper(org.bimserver.plugins.ModelHelper) IdEObject(org.bimserver.emf.IdEObject) PackageMetaData(org.bimserver.emf.PackageMetaData) ObjectRemoved(org.bimserver.models.store.ObjectRemoved) CompareItem(org.bimserver.models.store.CompareItem) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) Project(org.bimserver.models.store.Project) DataObject(org.bimserver.models.store.DataObject) Revision(org.bimserver.models.store.Revision) IfcModelSet(org.bimserver.plugins.IfcModelSet) ObjectAdded(org.bimserver.models.store.ObjectAdded) ModelCompareException(org.bimserver.plugins.modelcompare.ModelCompareException) ObjectModified(org.bimserver.models.store.ObjectModified)

Example 4 with ModelHelper

use of org.bimserver.plugins.ModelHelper in project BIMserver by opensourceBIM.

the class DownloadProjectsDatabaseAction method execute.

@Override
public IfcModelInterface execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    User user = getUserByUoid(getAuthorization().getUoid());
    Project project = null;
    String projectName = "";
    IfcModelSet ifcModelSet = new IfcModelSet();
    long incrSize = 0;
    for (long roid : roids) {
        Revision revision = getRevisionByRoid(roid);
        for (ConcreteRevision subRevision : revision.getConcreteRevisions()) {
            incrSize += subRevision.getSize();
        }
    }
    final long totalSize = incrSize;
    final AtomicLong total = new AtomicLong();
    PluginConfiguration serializerPluginConfiguration = getDatabaseSession().get(StorePackage.eINSTANCE.getPluginConfiguration(), serializerOid, OldQuery.getDefault());
    PackageMetaData lastPackageMetaData = null;
    IfcHeader ifcHeader = null;
    Map<Integer, Long> pidRoidMap = new HashMap<>();
    for (long roid : roids) {
        Revision revision = getRevisionByRoid(roid);
        project = revision.getProject();
        pidRoidMap.put(project.getId(), roid);
        if (getAuthorization().hasRightsOnProjectOrSuperProjectsOrSubProjects(user, project)) {
            for (ConcreteRevision concreteRevision : revision.getConcreteRevisions()) {
                ifcHeader = concreteRevision.getIfcHeader();
                PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData(concreteRevision.getProject().getSchema());
                lastPackageMetaData = packageMetaData;
                IfcModel subModel = getDatabaseSession().createServerModel(packageMetaData, pidRoidMap);
                ;
                int highestStopId = findHighestStopRid(project, concreteRevision);
                OldQuery query = new OldQuery(packageMetaData, concreteRevision.getProject().getId(), concreteRevision.getId(), revision.getOid(), Deep.YES, highestStopId);
                subModel.addChangeListener(new IfcModelChangeListener() {

                    @Override
                    public void objectAdded(IdEObject idEObject) {
                        total.incrementAndGet();
                        if (totalSize == 0) {
                            setProgress("Preparing download...", 0);
                        } else {
                            setProgress("Preparing download...", (int) Math.round(100.0 * total.get() / totalSize));
                        }
                    }
                });
                query.updateOidCounters(concreteRevision, getDatabaseSession());
                getDatabaseSession().getMap(subModel, query);
                projectName += concreteRevision.getProject().getName() + "-";
                subModel.getModelMetaData().setDate(concreteRevision.getDate());
                try {
                    checkGeometry(serializerPluginConfiguration, getBimServer().getPluginManager(), subModel, project, concreteRevision, revision);
                } catch (GeometryGeneratingException e) {
                    throw new UserException(e);
                }
                ifcModelSet.add(subModel);
            }
        } else {
            throw new UserException("User has no rights on project " + project.getOid());
        }
    }
    IfcModelInterface ifcModel = getDatabaseSession().createServerModel(lastPackageMetaData, pidRoidMap);
    if (ifcModelSet.size() == 1) {
        ifcModel = ifcModelSet.iterator().next();
    } else {
        try {
            ifcModel = getBimServer().getMergerFactory().createMerger(getDatabaseSession(), getAuthorization().getUoid()).merge(project, ifcModelSet, new ModelHelper(getBimServer().getMetaDataManager(), ifcModel));
        } catch (MergeException e) {
            throw new UserException(e);
        }
    }
    if (ifcHeader != null) {
        ifcHeader.load();
        ifcModel.getModelMetaData().setIfcHeader(ifcHeader);
    }
    if (projectName.endsWith("-")) {
        projectName = projectName.substring(0, projectName.length() - 1);
    }
    ifcModel.getModelMetaData().setName(projectName);
    return ifcModel;
}
Also used : User(org.bimserver.models.store.User) HashMap(java.util.HashMap) IfcModelInterface(org.bimserver.emf.IfcModelInterface) IfcModelChangeListener(org.bimserver.ifc.IfcModelChangeListener) GeometryGeneratingException(org.bimserver.GeometryGeneratingException) IfcModel(org.bimserver.ifc.IfcModel) ConcreteRevision(org.bimserver.models.store.ConcreteRevision) MergeException(org.bimserver.plugins.modelmerger.MergeException) PluginConfiguration(org.bimserver.models.store.PluginConfiguration) UserException(org.bimserver.shared.exceptions.UserException) ModelHelper(org.bimserver.plugins.ModelHelper) IdEObject(org.bimserver.emf.IdEObject) PackageMetaData(org.bimserver.emf.PackageMetaData) IfcHeader(org.bimserver.models.store.IfcHeader) OldQuery(org.bimserver.database.OldQuery) Project(org.bimserver.models.store.Project) AtomicLong(java.util.concurrent.atomic.AtomicLong) Revision(org.bimserver.models.store.Revision) ConcreteRevision(org.bimserver.models.store.ConcreteRevision) AtomicLong(java.util.concurrent.atomic.AtomicLong) IfcModelSet(org.bimserver.plugins.IfcModelSet)

Example 5 with ModelHelper

use of org.bimserver.plugins.ModelHelper in project BIMserver by opensourceBIM.

the class BranchToExistingProjectDatabaseAction method execute.

@Override
public ConcreteRevision execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    Revision oldRevision = getDatabaseSession().get(StorePackage.eINSTANCE.getRevision(), roid, OldQuery.getDefault());
    Project oldProject = oldRevision.getProject();
    User user = getDatabaseSession().get(StorePackage.eINSTANCE.getUser(), authorization.getUoid(), OldQuery.getDefault());
    if (!authorization.hasRightsOnProjectOrSuperProjectsOrSubProjects(user, oldProject)) {
        throw new UserException("User has insufficient rights to download revisions from this project");
    }
    IfcModelSet ifcModelSet = new IfcModelSet();
    PackageMetaData lastMetaData = null;
    for (ConcreteRevision subRevision : oldRevision.getConcreteRevisions()) {
        PackageMetaData packageMetaData = bimServer.getMetaDataManager().getPackageMetaData(subRevision.getProject().getSchema());
        IfcModel subModel = new BasicIfcModel(packageMetaData, null);
        getDatabaseSession().getMap(subModel, new OldQuery(packageMetaData, subRevision.getProject().getId(), subRevision.getId(), -1, Deep.YES));
        subModel.getModelMetaData().setDate(subRevision.getDate());
        ifcModelSet.add(subModel);
        lastMetaData = packageMetaData;
    }
    IfcModelInterface model = new BasicIfcModel(lastMetaData, null);
    try {
        model = bimServer.getMergerFactory().createMerger(getDatabaseSession(), authorization.getUoid()).merge(oldRevision.getProject(), ifcModelSet, new ModelHelper(bimServer.getMetaDataManager(), model));
    } catch (MergeException e) {
        throw new UserException(e);
    }
    model.resetOids();
    // TODO
    CheckinDatabaseAction checkinDatabaseAction = new CheckinDatabaseAction(bimServer, getDatabaseSession(), getAccessMethod(), destPoid, authorization, model, comment, comment, false, -1, -1);
    return checkinDatabaseAction.execute();
}
Also used : User(org.bimserver.models.store.User) ModelHelper(org.bimserver.plugins.ModelHelper) PackageMetaData(org.bimserver.emf.PackageMetaData) IfcModelInterface(org.bimserver.emf.IfcModelInterface) BasicIfcModel(org.bimserver.ifc.BasicIfcModel) OldQuery(org.bimserver.database.OldQuery) Project(org.bimserver.models.store.Project) IfcModel(org.bimserver.ifc.IfcModel) BasicIfcModel(org.bimserver.ifc.BasicIfcModel) Revision(org.bimserver.models.store.Revision) ConcreteRevision(org.bimserver.models.store.ConcreteRevision) ConcreteRevision(org.bimserver.models.store.ConcreteRevision) MergeException(org.bimserver.plugins.modelmerger.MergeException) IfcModelSet(org.bimserver.plugins.IfcModelSet) UserException(org.bimserver.shared.exceptions.UserException)

Aggregations

ModelHelper (org.bimserver.plugins.ModelHelper)14 IfcModelInterface (org.bimserver.emf.IfcModelInterface)13 PackageMetaData (org.bimserver.emf.PackageMetaData)12 UserException (org.bimserver.shared.exceptions.UserException)12 Revision (org.bimserver.models.store.Revision)10 IfcModelSet (org.bimserver.plugins.IfcModelSet)10 MergeException (org.bimserver.plugins.modelmerger.MergeException)10 OldQuery (org.bimserver.database.OldQuery)9 ConcreteRevision (org.bimserver.models.store.ConcreteRevision)8 HashMap (java.util.HashMap)7 IdEObject (org.bimserver.emf.IdEObject)7 IfcModel (org.bimserver.ifc.IfcModel)7 Project (org.bimserver.models.store.Project)7 BasicIfcModel (org.bimserver.ifc.BasicIfcModel)6 HashSet (java.util.HashSet)4 IfcModelInterfaceException (org.bimserver.emf.IfcModelInterfaceException)4 PluginConfiguration (org.bimserver.models.store.PluginConfiguration)4 User (org.bimserver.models.store.User)4 EClass (org.eclipse.emf.ecore.EClass)4 ArrayList (java.util.ArrayList)3