Search in sources :

Example 6 with SLongCheckinActionState

use of org.bimserver.interfaces.objects.SLongCheckinActionState in project BIMserver by opensourceBIM.

the class AsyncTestAddExtendedData2 method start.

private void start() {
    try {
        BimServerClientInterface client = LocalDevSetup.setupJson("http://localhost:8080");
        SFile file = new SFile();
        file.setData("test".getBytes(Charsets.UTF_8));
        file.setMime("text");
        file.setFilename("test.txt");
        long fileId = client.getServiceInterface().uploadFile(file);
        SProject project = client.getServiceInterface().addProject(RandomUtils.nextInt(1, 100000000) + "", "ifc2x3tc1");
        SDeserializerPluginConfiguration deserializerForExtension = client.getServiceInterface().getSuggestedDeserializerForExtension("ifc", project.getOid());
        long topicId = client.getServiceInterface().initiateCheckin(project.getOid(), deserializerForExtension.getOid());
        client.checkinAsync(project.getOid(), "initial", deserializerForExtension.getOid(), false, Paths.get("C:\\Git\\TestFiles\\TestData\\data\\AC11-FZK-Haus-IFC.ifc"), topicId);
        while (true) {
            SLongCheckinActionState progress = (SLongCheckinActionState) client.getNotificationRegistryInterface().getProgress(topicId);
            System.out.println(progress.getState());
            if (progress.getState() == SActionState.FINISHED) {
                SExtendedDataSchema extendedDataSchemaByNamespace = client.getServiceInterface().getExtendedDataSchemaByName("GEOMETRY_GENERATION_REPORT_JSON_1_1");
                SExtendedData extendedData = new SExtendedData();
                extendedData.setFileId(fileId);
                extendedData.setTitle("test3");
                extendedData.setSchemaId(extendedDataSchemaByNamespace.getOid());
                client.getServiceInterface().addExtendedDataToRevision(progress.getRoid(), extendedData);
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } catch (ServiceException e) {
        e.printStackTrace();
    } catch (PublicInterfaceNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) SExtendedData(org.bimserver.interfaces.objects.SExtendedData) ServiceException(org.bimserver.shared.exceptions.ServiceException) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException) SLongCheckinActionState(org.bimserver.interfaces.objects.SLongCheckinActionState) BimServerClientInterface(org.bimserver.plugins.services.BimServerClientInterface) IOException(java.io.IOException) SFile(org.bimserver.interfaces.objects.SFile) SProject(org.bimserver.interfaces.objects.SProject) SExtendedDataSchema(org.bimserver.interfaces.objects.SExtendedDataSchema)

Example 7 with SLongCheckinActionState

use of org.bimserver.interfaces.objects.SLongCheckinActionState in project BIMserver by opensourceBIM.

the class TestBigModelEmfRemote method test.

@Test
public void test() {
    boolean doreuse = true;
    boolean useLowLevelCalls = false;
    try (BimServerClientFactory factory = new JsonBimServerClientFactory("http://localhost:8080")) {
        BimServerClientInterface bimServerClient = factory.create(new UsernamePasswordAuthenticationInfo("admin@bimserver.org", "admin"));
        SProject newProject = bimServerClient.getServiceInterface().addProject("test" + Math.random(), "ifc2x3tc1");
        IfcModelInterface model = null;
        if (useLowLevelCalls) {
            model = bimServerClient.newModel(newProject, true);
        } else {
            model = new BasicIfcModel(bimServerClient.getMetaDataManager().getPackageMetaData("ifc2x3tc1"), null);
        }
        RichIfcModel richIfcModel = new RichIfcModel(model, !useLowLevelCalls);
        IfcBuilding ifcBuilding = richIfcModel.createDefaultProjectStructure(0, 0, 0);
        IfcRelAggregates buildingAggregation = richIfcModel.create(IfcRelAggregates.class);
        buildingAggregation.setRelatingObject(ifcBuilding);
        for (int i = 1; i <= 200; i++) {
            IfcBuildingStorey ifcBuildingStorey = richIfcModel.create(IfcBuildingStorey.class);
            ifcBuildingStorey.setName("Storey " + i);
            ifcBuildingStorey.setCompositionType(IfcElementCompositionEnum.ELEMENT);
            ifcBuildingStorey.setElevation(3000 * i);
            IfcLocalPlacement storeyPlacement = richIfcModel.create(IfcLocalPlacement.class);
            storeyPlacement.setRelativePlacement(richIfcModel.createBasicPosition(0, 0, i * 3000));
            ifcBuildingStorey.setObjectPlacement(storeyPlacement);
            buildingAggregation.getRelatedObjects().add(ifcBuildingStorey);
            IfcRelAggregates storeyAggregation = richIfcModel.create(IfcRelAggregates.class);
            storeyAggregation.setRelatingObject(ifcBuildingStorey);
            for (int x = 1; x <= 40; x++) {
                for (int y = 1; y <= 40; y++) {
                    createSpace(richIfcModel, richIfcModel.getDefaultRepresentationContext(), storeyPlacement, storeyAggregation, x, y, doreuse);
                }
            }
        }
        long roid = -1;
        if (useLowLevelCalls) {
            roid = model.commit("Initial model");
        } else {
            Serializer serializer = new Ifc2x3tc1StepSerializer(null);
            serializer.init(model, null, true);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            serializer.writeToOutputStream(baos, null);
            java.nio.file.Files.write(Paths.get("tmp.ifc"), baos.toByteArray());
            SDeserializerPluginConfiguration deserializer = bimServerClient.getServiceInterface().getSuggestedDeserializerForExtension("ifc", newProject.getOid());
            SLongCheckinActionState checkinSync = bimServerClient.checkinSync(newProject.getOid(), "New", deserializer.getOid(), false, baos.size(), "newfile", new ByteArrayInputStream(baos.toByteArray()));
            roid = checkinSync.getRoid();
        }
        SSerializerPluginConfiguration serializerByContentType = bimServerClient.getServiceInterface().getSerializerByName("Ifc2x3tc1 (Streaming)");
        bimServerClient.download(roid, serializerByContentType.getOid(), new FileOutputStream(new File("created.ifc")));
    } catch (Throwable e) {
        e.printStackTrace();
        if (e instanceof AssertionError) {
            throw (AssertionError) e;
        }
        fail(e.getMessage());
    }
}
Also used : SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) RichIfcModel(org.bimserver.utils.RichIfcModel) UsernamePasswordAuthenticationInfo(org.bimserver.shared.UsernamePasswordAuthenticationInfo) IfcModelInterface(org.bimserver.emf.IfcModelInterface) JsonBimServerClientFactory(org.bimserver.client.json.JsonBimServerClientFactory) SProject(org.bimserver.interfaces.objects.SProject) JsonBimServerClientFactory(org.bimserver.client.json.JsonBimServerClientFactory) BimServerClientFactory(org.bimserver.shared.BimServerClientFactory) IfcLocalPlacement(org.bimserver.models.ifc2x3tc1.IfcLocalPlacement) BimServerClientInterface(org.bimserver.plugins.services.BimServerClientInterface) IfcBuildingStorey(org.bimserver.models.ifc2x3tc1.IfcBuildingStorey) IfcBuilding(org.bimserver.models.ifc2x3tc1.IfcBuilding) Serializer(org.bimserver.plugins.serializers.Serializer) Ifc2x3tc1StepSerializer(org.bimserver.ifc.step.serializer.Ifc2x3tc1StepSerializer) SLongCheckinActionState(org.bimserver.interfaces.objects.SLongCheckinActionState) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BasicIfcModel(org.bimserver.ifc.BasicIfcModel) Ifc2x3tc1StepSerializer(org.bimserver.ifc.step.serializer.Ifc2x3tc1StepSerializer) IfcRelAggregates(org.bimserver.models.ifc2x3tc1.IfcRelAggregates) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) SSerializerPluginConfiguration(org.bimserver.interfaces.objects.SSerializerPluginConfiguration) File(java.io.File) Test(org.junit.Test)

Example 8 with SLongCheckinActionState

use of org.bimserver.interfaces.objects.SLongCheckinActionState in project BIMserver by opensourceBIM.

the class ServiceImpl method checkinFromUrlAsync.

@Override
public Long checkinFromUrlAsync(Long poid, String comment, Long deserializerOid, String fileName, String urlString, Boolean merge) throws ServerException, UserException {
    requireAuthenticationAndRunningServer();
    final DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.READ_ONLY);
    String username = "Unknown";
    String userUsername = "Unknown";
    try {
        Long topicId = initiateCheckin(poid, deserializerOid);
        User user = (User) session.get(StorePackage.eINSTANCE.getUser(), getAuthorization().getUoid(), OldQuery.getDefault());
        username = user.getName();
        userUsername = user.getUsername();
        Path homeDirIncoming = getBimServer().getHomeDir().resolve("incoming");
        if (!Files.isDirectory(homeDirIncoming)) {
            Files.createDirectory(homeDirIncoming);
        }
        Path userDirIncoming = homeDirIncoming.resolve(userUsername);
        if (!Files.exists(userDirIncoming)) {
            Files.createDirectory(userDirIncoming);
        }
        Project project = session.get(poid, OldQuery.getDefault());
        if (project == null) {
            throw new UserException("No project found with poid " + poid);
        }
        URL url = new URL(urlString);
        URLConnection openConnection = url.openConnection();
        InputStream input = openConnection.getInputStream();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
        if (fileName == null) {
            if (urlString.contains("/")) {
                fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
            } else {
                fileName = urlString;
            }
            if (fileName.contains("?")) {
                fileName = fileName.substring(0, fileName.indexOf("?"));
            }
            fileName = URLDecoder.decode(fileName, Charsets.UTF_8.name());
        }
        Path file = userDirIncoming.resolve(fileName);
        if (fileName.contains(" ")) {
            fileName = fileName.replace(" ", "_");
        }
        SLongCheckinActionState checkinInternal = checkinInternal(topicId, poid, comment, deserializerOid, (long) openConnection.getContentLength(), fileName, input, merge, false, session, username, userUsername, project, file, -1);
        return checkinInternal.getTopicId();
    // DeserializerPluginConfiguration deserializerPluginConfiguration = session.get(StorePackage.eINSTANCE.getDeserializerPluginConfiguration(), deserializerOid, OldQuery.getDefault());
    // if (deserializerPluginConfiguration == null) {
    // throw new UserException("Deserializer with oid " + deserializerOid + " not found");
    // }
    // OutputStream outputStream = Files.newOutputStream(file);
    // InputStream inputStream = new MultiplexingInputStream(input, outputStream);
    // DeserializerPlugin deserializerPlugin = (DeserializerPlugin) getBimServer().getPluginManager().getPlugin(deserializerPluginConfiguration.getPluginDescriptor().getPluginClassName(), true);
    // ObjectType settings = deserializerPluginConfiguration.getSettings();
    // 
    // Deserializer deserializer = deserializerPlugin.createDeserializer(new PluginConfiguration(settings));
    // deserializer.init(getBimServer().getDatabase().getMetaDataManager().getPackageMetaData("ifc2x3tc1"));
    // 
    // IfcModelInterface model = deserializer.read(inputStream, fileName, 0, null);
    // 
    // CheckinDatabaseAction checkinDatabaseAction = new CheckinDatabaseAction(getBimServer(), null, getInternalAccessMethod(), poid, getAuthorization(), model, comment, fileName, merge);
    // LongCheckinAction longAction = new LongCheckinAction(-1L, getBimServer(), username, userUsername, getAuthorization(), checkinDatabaseAction);
    // getBimServer().getLongActionManager().start(longAction);
    // if (sync) {
    // longAction.waitForCompletion();
    // }
    // return longAction.getProgressTopic().getKey().getId();
    } catch (UserException e) {
        throw e;
    } catch (Throwable e) {
        LOGGER.error("", e);
        throw new ServerException(e);
    } finally {
        session.close();
    }
}
Also used : Path(java.nio.file.Path) SUser(org.bimserver.interfaces.objects.SUser) User(org.bimserver.models.store.User) ServerException(org.bimserver.shared.exceptions.ServerException) DatabaseSession(org.bimserver.database.DatabaseSession) ByteArrayInputStream(java.io.ByteArrayInputStream) MultiplexingInputStream(org.bimserver.utils.MultiplexingInputStream) InputStream(java.io.InputStream) SLongCheckinActionState(org.bimserver.interfaces.objects.SLongCheckinActionState) URL(java.net.URL) URLConnection(java.net.URLConnection) Project(org.bimserver.models.store.Project) SProject(org.bimserver.interfaces.objects.SProject) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) UserException(org.bimserver.shared.exceptions.UserException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 9 with SLongCheckinActionState

use of org.bimserver.interfaces.objects.SLongCheckinActionState in project BIMserver by opensourceBIM.

the class UploadServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (request.getHeader("Origin") != null && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) {
        response.setStatus(403);
        return;
    }
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    String token = (String) request.getSession().getAttribute("token");
    ObjectNode result = OBJECT_MAPPER.createObjectNode();
    response.setContentType("text/json");
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        long poid = -1;
        String comment = null;
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            InputStream in = null;
            String name = "";
            long deserializerOid = -1;
            boolean merge = false;
            boolean sync = false;
            String compression = null;
            String action = null;
            long topicId = -1;
            try {
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    if (item.isFormField()) {
                        if ("action".equals(item.getFieldName())) {
                            action = Streams.asString(item.openStream());
                        } else if ("token".equals(item.getFieldName())) {
                            token = Streams.asString(item.openStream());
                        } else if ("poid".equals(item.getFieldName())) {
                            poid = Long.parseLong(Streams.asString(item.openStream()));
                        } else if ("comment".equals(item.getFieldName())) {
                            comment = Streams.asString(item.openStream());
                        } else if ("topicId".equals(item.getFieldName())) {
                            topicId = Long.parseLong(Streams.asString(item.openStream()));
                        } else if ("sync".equals(item.getFieldName())) {
                            sync = Streams.asString(item.openStream()).equals("true");
                        } else if ("merge".equals(item.getFieldName())) {
                            merge = Streams.asString(item.openStream()).equals("true");
                        } else if ("compression".equals(item.getFieldName())) {
                            compression = Streams.asString(item.openStream());
                        } else if ("deserializerOid".equals(item.getFieldName())) {
                            deserializerOid = Long.parseLong(Streams.asString(item.openStream()));
                        }
                    } else {
                        name = item.getName();
                        in = item.openStream();
                        if ("file".equals(action)) {
                            ServiceInterface serviceInterface = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                            SFile file = new SFile();
                            byte[] data = IOUtils.toByteArray(in);
                            file.setData(data);
                            file.setSize(data.length);
                            file.setFilename(name);
                            file.setMime(item.getContentType());
                            result.put("fileId", serviceInterface.uploadFile(file));
                        } else if (poid != -1) {
                            InputStream realStream = null;
                            if ("gzip".equals(compression)) {
                                realStream = new GZIPInputStream(in);
                            } else if ("deflate".equals(compression)) {
                                realStream = new InflaterInputStream(in);
                            } else {
                                realStream = in;
                            }
                            // When uploading in async mode, we want to return as soon as the whole stream has been read (that's not when the checkin process has finished!)
                            TriggerOnCloseInputStream triggerOnCloseInputStream = new TriggerOnCloseInputStream(realStream);
                            InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(triggerOnCloseInputStream);
                            inputStreamDataSource.setName(name);
                            DataHandler ifcFile = new DataHandler(inputStreamDataSource);
                            if (token != null) {
                                ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                if (topicId == -1) {
                                    if (sync) {
                                        SLongCheckinActionState checkinSync = service.checkinSync(poid, comment, deserializerOid, -1L, name, ifcFile, merge);
                                        result = (ObjectNode) getBimServer().getJsonHandler().getJsonConverter().toJson(checkinSync);
                                        service.cleanupLongAction(checkinSync.getTopicId());
                                    } else {
                                        // When async, we can return as soon as all the data has been read
                                        long newTopicId = service.checkinAsync(poid, comment, deserializerOid, -1L, name, ifcFile, merge);
                                        triggerOnCloseInputStream.await();
                                        result.put("topicId", newTopicId);
                                    }
                                } else {
                                    if (sync) {
                                        SLongCheckinActionState checkinSync = service.checkinInitiatedSync(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge);
                                        result = (ObjectNode) getBimServer().getJsonHandler().getJsonConverter().toJson(checkinSync);
                                        service.cleanupLongAction(checkinSync.getTopicId());
                                    } else {
                                        service.checkinInitiatedAsync(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge);
                                        triggerOnCloseInputStream.await();
                                        result.put("topicId", topicId);
                                    }
                                }
                            }
                        } else {
                            result.put("exception", "No poid");
                        }
                    }
                }
            } catch (MalformedStreamException e) {
                LOGGER.error(comment);
                LOGGER.error("", e);
            }
        }
    } catch (Exception e) {
        LOGGER.error("", e);
        sendException(response, e);
        return;
    }
    response.getWriter().write(result.toString());
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) InputStream(java.io.InputStream) InflaterInputStream(java.util.zip.InflaterInputStream) SLongCheckinActionState(org.bimserver.interfaces.objects.SLongCheckinActionState) DataHandler(javax.activation.DataHandler) ServletException(javax.servlet.ServletException) MalformedStreamException(org.apache.commons.fileupload.MultipartStream.MalformedStreamException) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) InputStreamDataSource(org.bimserver.utils.InputStreamDataSource) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) ServiceInterface(org.bimserver.shared.interfaces.ServiceInterface) SFile(org.bimserver.interfaces.objects.SFile) MalformedStreamException(org.apache.commons.fileupload.MultipartStream.MalformedStreamException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 10 with SLongCheckinActionState

use of org.bimserver.interfaces.objects.SLongCheckinActionState in project BIMserver by opensourceBIM.

the class BimServerClient method checkin.

public SLongCheckinActionState checkin(long poid, String comment, long deserializerOid, URL url, CheckinProgressHandler progressHandler) throws ServerException, UserException, PublicInterfaceNotFoundException {
    long topicId = getServiceInterface().initiateCheckin(poid, deserializerOid);
    ProgressHandler progressHandlerWrapper = new ProgressHandler() {

        @Override
        public void progress(SLongActionState state) {
            progressHandler.progress(state.getTitle(), state.getProgress());
        }
    };
    getNotificationsManager().registerProgressHandler(topicId, progressHandlerWrapper);
    try {
        InputStream openStream = url.openStream();
        try {
            channel.checkinAsync(baseAddress, token, poid, comment, deserializerOid, false, -1, url.toString(), openStream, topicId);
        } finally {
            openStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    getNotificationsManager().unregisterProgressHandler(topicId, progressHandlerWrapper);
    return (SLongCheckinActionState) getRegistry().getProgress(topicId);
}
Also used : ProgressHandler(org.bimserver.plugins.services.ProgressHandler) CheckinProgressHandler(org.bimserver.plugins.services.CheckinProgressHandler) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SLongCheckinActionState(org.bimserver.interfaces.objects.SLongCheckinActionState) SLongActionState(org.bimserver.interfaces.objects.SLongActionState) IOException(java.io.IOException)

Aggregations

SLongCheckinActionState (org.bimserver.interfaces.objects.SLongCheckinActionState)19 SDeserializerPluginConfiguration (org.bimserver.interfaces.objects.SDeserializerPluginConfiguration)14 SProject (org.bimserver.interfaces.objects.SProject)14 UsernamePasswordAuthenticationInfo (org.bimserver.shared.UsernamePasswordAuthenticationInfo)11 Test (org.junit.Test)11 Path (java.nio.file.Path)10 JsonBimServerClientFactory (org.bimserver.client.json.JsonBimServerClientFactory)10 BimServerClient (org.bimserver.client.BimServerClient)9 IOException (java.io.IOException)6 InputStream (java.io.InputStream)6 ClientIfcModel (org.bimserver.client.ClientIfcModel)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 CheckinProgressHandler (org.bimserver.plugins.services.CheckinProgressHandler)5 BimServerClientInterface (org.bimserver.plugins.services.BimServerClientInterface)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 SLongActionState (org.bimserver.interfaces.objects.SLongActionState)3 UserException (org.bimserver.shared.exceptions.UserException)3 URL (java.net.URL)2 IfcModelInterface (org.bimserver.emf.IfcModelInterface)2