Search in sources :

Example 1 with SFile

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

the class ServiceImpl method getFileMeta.

@Override
public SFile getFileMeta(Long fileId) throws ServerException, UserException {
    DatabaseSession session = getBimServer().getDatabase().createSession();
    try {
        org.bimserver.models.store.File file = (org.bimserver.models.store.File) session.get(StorePackage.eINSTANCE.getFile(), fileId, OldQuery.getDefault());
        file.setData(null);
        return getBimServer().getSConverter().convertToSObject(file);
    } catch (Exception e) {
        return handleException(e);
    } finally {
        session.close();
    }
}
Also used : DatabaseSession(org.bimserver.database.DatabaseSession) File(org.bimserver.models.store.File) File(org.bimserver.models.store.File) SFile(org.bimserver.interfaces.objects.SFile) BcfFile(org.opensourcebim.bcf.BcfFile) IOException(java.io.IOException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) SerializerException(org.bimserver.plugins.serializers.SerializerException) BcfException(org.opensourcebim.bcf.BcfException) UserException(org.bimserver.shared.exceptions.UserException) CannotBeScheduledException(org.bimserver.longaction.CannotBeScheduledException) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) ServerException(org.bimserver.shared.exceptions.ServerException) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException)

Example 2 with SFile

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

the class ServiceImpl method uploadFile.

@Override
public Long uploadFile(SFile file) throws ServerException, UserException {
    DatabaseSession session = getBimServer().getDatabase().createSession();
    try {
        File convertFromSObject = getBimServer().getSConverter().convertFromSObject(file, session.create(File.class), session);
        UploadFileDatabaseAction action = new UploadFileDatabaseAction(session, getInternalAccessMethod(), convertFromSObject);
        return session.executeAndCommitAction(action);
    } catch (Exception e) {
        return handleException(e);
    } finally {
        session.close();
    }
}
Also used : DatabaseSession(org.bimserver.database.DatabaseSession) File(org.bimserver.models.store.File) SFile(org.bimserver.interfaces.objects.SFile) BcfFile(org.opensourcebim.bcf.BcfFile) IOException(java.io.IOException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) SerializerException(org.bimserver.plugins.serializers.SerializerException) BcfException(org.opensourcebim.bcf.BcfException) UserException(org.bimserver.shared.exceptions.UserException) CannotBeScheduledException(org.bimserver.longaction.CannotBeScheduledException) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) ServerException(org.bimserver.shared.exceptions.ServerException) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) UploadFileDatabaseAction(org.bimserver.database.actions.UploadFileDatabaseAction)

Example 3 with SFile

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

the class DownloadServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        boolean useGzip = false;
        if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
            useGzip = true;
        }
        OutputStream outputStream = response.getOutputStream();
        boolean zip = request.getParameter("zip") != null && request.getParameter("zip").equals("on");
        if (useGzip && !zip) {
            response.setHeader("Content-Encoding", "gzip");
            outputStream = new GZIPOutputStream(response.getOutputStream());
        }
        String token = (String) request.getSession().getAttribute("token");
        if (token == null) {
            token = request.getParameter("token");
        }
        long topicId = -1;
        if (request.getParameter("topicId") != null) {
            topicId = Long.parseLong(request.getParameter("topicId"));
        }
        ServiceMap serviceMap = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL);
        String action = request.getParameter("action");
        if (action != null) {
            if (action.equals("extendeddata")) {
                SExtendedData sExtendedData = serviceMap.getServiceInterface().getExtendedData(Long.parseLong(request.getParameter("edid")));
                SFile file = serviceMap.getServiceInterface().getFile(sExtendedData.getFileId());
                if (file.getMime() != null) {
                    response.setContentType(file.getMime());
                }
                if (file.getFilename() != null) {
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getFilename() + "\"");
                }
                outputStream.write(file.getData());
                if (outputStream instanceof GZIPOutputStream) {
                    ((GZIPOutputStream) outputStream).finish();
                }
                outputStream.flush();
                return;
            } else if (action.equals("getfile")) {
                String type = request.getParameter("type");
                if (type.equals("proto")) {
                    try {
                        String protocolBuffersFile = serviceMap.getAdminInterface().getProtocolBuffersFile(request.getParameter("name"));
                        outputStream.write(protocolBuffersFile.getBytes(Charsets.UTF_8));
                        outputStream.flush();
                    } catch (ServiceException e) {
                        LOGGER.error("", e);
                    }
                } else if (type.equals("serverlog")) {
                    try {
                        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
                        writer.write(serviceMap.getAdminInterface().getServerLog());
                        writer.flush();
                    } catch (ServerException e) {
                        LOGGER.error("", e);
                    } catch (UserException e) {
                        LOGGER.error("", e);
                    }
                }
            } else if (action.equals("getBcfImage")) {
                long extendedDataId = Long.parseLong(request.getParameter("extendedDataId"));
                String topicGuid = request.getParameter("topicGuid");
                String name = request.getParameter("name");
                BcfFile bcfFile = BcfCache.INSTANCE.get(extendedDataId);
                if (bcfFile == null) {
                    SExtendedData extendedData = serviceMap.getServiceInterface().getExtendedData(extendedDataId);
                    long fileId = extendedData.getFileId();
                    SFile file = serviceMap.getServiceInterface().getFile(fileId);
                    try {
                        bcfFile = BcfFile.read(new ByteArrayInputStream(file.getData()), new ReadOptions(false));
                        BcfCache.INSTANCE.put(extendedDataId, bcfFile);
                    } catch (BcfException e) {
                        e.printStackTrace();
                    }
                }
                TopicFolder topicFolder = bcfFile.getTopicFolder(topicGuid);
                if (topicFolder != null) {
                    byte[] data = topicFolder.getSnapshot(topicGuid + "/" + name);
                    if (data != null) {
                        response.setContentType("image/png");
                        IOUtils.write(data, outputStream);
                        if (outputStream instanceof GZIPOutputStream) {
                            ((GZIPOutputStream) outputStream).finish();
                        }
                        outputStream.flush();
                        return;
                    }
                }
            }
        } else {
            if (request.getParameter("topicId") != null) {
                topicId = Long.parseLong(request.getParameter("topicId"));
            }
            if (topicId == -1) {
                response.getWriter().println("No valid topicId");
                return;
            }
            SDownloadResult checkoutResult = serviceMap.getServiceInterface().getDownloadData(topicId);
            if (checkoutResult == null) {
                LOGGER.error("Invalid topicId: " + topicId);
            } else {
                DataSource dataSource = checkoutResult.getFile().getDataSource();
                PluginConfiguration pluginConfiguration = new PluginConfiguration(serviceMap.getPluginInterface().getPluginSettings(checkoutResult.getSerializerOid()));
                final ProgressTopic progressTopic = getBimServer().getNotificationsManager().getProgressTopic(topicId);
                ProgressReporter progressReporter = new ProgressReporter() {

                    private long lastMax;

                    private long lastProgress;

                    private int stage = 3;

                    private Date start = new Date();

                    private String title = "Downloading...";

                    @Override
                    public void update(long progress, long max) {
                        if (progressTopic != null) {
                            LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                            ds.setStart(start);
                            ds.setState(progress == max ? ActionState.FINISHED : ActionState.STARTED);
                            ds.setTitle(title);
                            ds.setStage(stage);
                            ds.setProgress((int) Math.round(100.0 * progress / max));
                            progressTopic.stageProgressUpdate(ds);
                            this.lastMax = max;
                            this.lastProgress = progress;
                        }
                    }

                    @Override
                    public void setTitle(String title) {
                        if (progressTopic != null) {
                            stage++;
                            this.title = title;
                            LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                            ds.setStart(new Date());
                            ds.setState(lastProgress == lastMax ? ActionState.FINISHED : ActionState.STARTED);
                            ds.setTitle(title);
                            ds.setStage(stage);
                            ds.setProgress((int) Math.round(100.0 * lastProgress / lastMax));
                            progressTopic.stageProgressUpdate(ds);
                        }
                    }
                };
                try {
                    if (zip) {
                        if (pluginConfiguration.getString("ZipExtension") != null) {
                            response.setHeader("Content-Disposition", "inline; filename=\"" + dataSource.getName() + "." + pluginConfiguration.getString(SerializerPlugin.ZIP_EXTENSION) + "\"");
                        } else {
                            response.setHeader("Content-Disposition", "inline; filename=\"" + dataSource.getName() + ".zip" + "\"");
                        }
                        response.setContentType("application/zip");
                        String nameInZip = dataSource.getName() + "." + pluginConfiguration.getString(SerializerPlugin.EXTENSION);
                        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
                        zipOutputStream.putNextEntry(new ZipEntry(nameInZip));
                        processDataSource(zipOutputStream, dataSource, progressReporter);
                        try {
                            zipOutputStream.finish();
                        } catch (IOException e) {
                        // Sometimes it's already closed, that's no problem
                        }
                    } else {
                        if (request.getParameter("mime") == null) {
                            response.setContentType(pluginConfiguration.getString(SerializerPlugin.CONTENT_TYPE));
                            response.setHeader("Content-Disposition", "inline; filename=\"" + dataSource.getName() + "." + pluginConfiguration.getString(SerializerPlugin.EXTENSION) + "\"");
                        } else {
                            response.setContentType(request.getParameter("mime"));
                        }
                        processDataSource(outputStream, dataSource, progressReporter);
                    }
                } catch (SerializerException s) {
                    if (s.getCause() != null && s.getCause() instanceof IOException) {
                    } else {
                        LOGGER.error("", s);
                    }
                    LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                    ds.setStart(new Date());
                    ds.setState(ActionState.AS_ERROR);
                    ds.setTitle("Serialization Error");
                    ds.setProgress(-1);
                    ds.setStage(3);
                    ds.getErrors().add(s.getMessage());
                    progressTopic.stageProgressUpdate(ds);
                }
            }
        }
        if (outputStream instanceof GZIPOutputStream) {
            ((GZIPOutputStream) outputStream).finish();
        }
        outputStream.flush();
    } catch (NumberFormatException e) {
        LOGGER.error("", e);
        response.getWriter().println("Some number was incorrectly formatted");
    } catch (ServiceException e) {
        LOGGER.error("", e);
        response.getWriter().println(e.getUserMessage());
    } catch (EOFException e) {
    } catch (Exception e) {
        LOGGER.error("", e);
    }
}
Also used : ServiceMap(org.bimserver.webservices.ServiceMap) LongActionState(org.bimserver.models.store.LongActionState) ZipOutputStream(java.util.zip.ZipOutputStream) OutputStream(java.io.OutputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) ZipEntry(java.util.zip.ZipEntry) BcfFile(org.opensourcebim.bcf.BcfFile) GZIPOutputStream(java.util.zip.GZIPOutputStream) ReadOptions(org.opensourcebim.bcf.ReadOptions) EOFException(java.io.EOFException) PluginConfiguration(org.bimserver.plugins.PluginConfiguration) UserException(org.bimserver.shared.exceptions.UserException) SFile(org.bimserver.interfaces.objects.SFile) ServerException(org.bimserver.shared.exceptions.ServerException) TopicFolder(org.opensourcebim.bcf.TopicFolder) BcfException(org.opensourcebim.bcf.BcfException) SDownloadResult(org.bimserver.interfaces.objects.SDownloadResult) ProgressReporter(org.bimserver.plugins.serializers.ProgressReporter) IOException(java.io.IOException) SerializerException(org.bimserver.plugins.serializers.SerializerException) Date(java.util.Date) ServletException(javax.servlet.ServletException) ServiceException(org.bimserver.shared.exceptions.ServiceException) SerializerException(org.bimserver.plugins.serializers.SerializerException) IOException(java.io.IOException) EOFException(java.io.EOFException) BcfException(org.opensourcebim.bcf.BcfException) UserException(org.bimserver.shared.exceptions.UserException) ServerException(org.bimserver.shared.exceptions.ServerException) ExtendedDataSource(org.bimserver.plugins.serializers.ExtendedDataSource) DataSource(javax.activation.DataSource) ProgressTopic(org.bimserver.notifications.ProgressTopic) SExtendedData(org.bimserver.interfaces.objects.SExtendedData) ServiceException(org.bimserver.shared.exceptions.ServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipOutputStream(java.util.zip.ZipOutputStream) OutputStreamWriter(java.io.OutputStreamWriter)

Example 4 with SFile

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

the class ServiceRunnerServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (request.getRequestURI().endsWith("/servicelist")) {
        processServiceList(request, response);
        return;
    }
    String token = null;
    if (request.getHeader("Authorization") != null) {
        String a = request.getHeader("Authorization");
        if (a.startsWith("Bearer")) {
            token = a.substring(7);
        }
    }
    if (token == null) {
        token = request.getHeader("Token");
    }
    LOGGER.info("Token: " + token);
    String serviceName = request.getHeader("ServiceName");
    if (serviceName == null) {
        serviceName = request.getRequestURI();
        if (serviceName.startsWith("/services/")) {
            serviceName = serviceName.substring(10);
        }
    }
    LOGGER.info("ServiceName: " + serviceName);
    long serviceOid = Long.parseLong(serviceName);
    String inputType = request.getHeader("Input-Type");
    LOGGER.info("Input-Type: " + inputType);
    try (DatabaseSession session = getBimServer().getDatabase().createSession()) {
        Authorization authorization = Authorization.fromToken(getBimServer().getEncryptionKey(), token);
        User user = session.get(authorization.getUoid(), OldQuery.getDefault());
        if (user == null) {
            LOGGER.error("Service \"" + serviceName + "\" not found for this user");
            throw new UserException("No user found with uoid " + authorization.getUoid());
        }
        if (user.getState() == ObjectState.DELETED) {
            LOGGER.error("User has been deleted");
            throw new UserException("User has been deleted");
        }
        InternalServicePluginConfiguration foundService = null;
        UserSettings userSettings = user.getUserSettings();
        for (InternalServicePluginConfiguration internalServicePluginConfiguration : userSettings.getServices()) {
            if (internalServicePluginConfiguration.getOid() == serviceOid) {
                foundService = internalServicePluginConfiguration;
                break;
            }
        }
        if (foundService == null) {
            LOGGER.info("Service \"" + serviceName + "\" not found for this user");
            throw new ServletException("Service \"" + serviceName + "\" not found for this user");
        }
        PluginDescriptor pluginDescriptor = foundService.getPluginDescriptor();
        ServicePlugin servicePlugin = getBimServer().getPluginManager().getServicePlugin(pluginDescriptor.getPluginClassName(), true);
        if (servicePlugin instanceof BimBotsServiceInterface) {
            LOGGER.info("Found service " + servicePlugin);
            BimBotsServiceInterface bimBotsServiceInterface = (BimBotsServiceInterface) servicePlugin;
            try {
                if (getBimServer().getServerSettingsCache().getServerSettings().isStoreServiceRuns()) {
                    LOGGER.info("Storing intermediate results");
                    // When we store service runs, we can just use the streaming deserializer to stream directly to the database, after that we'll trigger the actual service
                    // Create or find project and link user and service to project
                    // Checkin stream into project
                    // Trigger service
                    ServiceInterface serviceInterface = getBimServer().getServiceFactory().get(authorization, AccessMethod.INTERNAL).get(ServiceInterface.class);
                    SProject project = serviceInterface.addProject("tmp-" + new Random().nextInt(), "ifc2x3tc1");
                    SDeserializerPluginConfiguration deserializer = serviceInterface.getSuggestedDeserializerForExtension("ifc", project.getOid());
                    if (deserializer == null) {
                        throw new BimBotsException("No deserializer found");
                    }
                    serviceInterface.checkin(project.getOid(), "Auto checkin", deserializer.getOid(), -1L, "s", new DataHandler(new InputStreamDataSource(request.getInputStream())), false, true);
                    project = serviceInterface.getProjectByPoid(project.getOid());
                    PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData(project.getSchema());
                    IfcModelInterface model = new BasicIfcModel(packageMetaData, null);
                    try {
                        Revision revision = session.get(project.getLastRevisionId(), OldQuery.getDefault());
                        session.getMap(model, new OldQuery(packageMetaData, project.getId(), revision.getId(), revision.getOid(), null, Deep.NO));
                    } catch (BimserverDatabaseException e) {
                        e.printStackTrace();
                    }
                    BimServerBimBotsInput input = new BimServerBimBotsInput(getBimServer(), authorization.getUoid(), null, null, model);
                    BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, getBimServer().getSConverter().convertToSObject(foundService.getSettings()));
                    SExtendedData extendedData = new SExtendedData();
                    SFile file = new SFile();
                    file.setData(output.getData());
                    file.setFilename(output.getContentDisposition());
                    file.setMime(output.getContentType());
                    file.setSize(output.getData().length);
                    Long fileId = serviceInterface.uploadFile(file);
                    extendedData.setFileId(fileId);
                    extendedData.setTitle(output.getTitle());
                    SExtendedDataSchema extendedDataSchema = null;
                    try {
                        extendedDataSchema = serviceInterface.getExtendedDataSchemaByName(output.getSchemaName());
                    } catch (UserException e) {
                        extendedDataSchema = new SExtendedDataSchema();
                        extendedDataSchema.setContentType(output.getContentType());
                        extendedDataSchema.setName(output.getSchemaName());
                        serviceInterface.addExtendedDataSchema(extendedDataSchema);
                    }
                    extendedData.setSchemaId(extendedDataSchema.getOid());
                    serviceInterface.addExtendedDataToRevision(project.getLastRevisionId(), extendedData);
                    response.setHeader("Output-Type", output.getSchemaName());
                    response.setHeader("Data-Title", output.getTitle());
                    response.setHeader("Data-Identifier", "" + project.getOid());
                    response.setHeader("Content-Type", output.getContentType());
                    response.setHeader("Content-Disposition", output.getContentDisposition());
                    response.getOutputStream().write(output.getData());
                } else {
                    // When we don't store the service runs, there is no other way than to just use the old deserializer and run the service from the EMF model
                    LOGGER.info("NOT Storing intermediate results");
                    DeserializerPlugin deserializerPlugin = getBimServer().getPluginManager().getFirstDeserializer("ifc", Schema.IFC2X3TC1, true);
                    if (deserializerPlugin == null) {
                        throw new BimBotsException("No deserializer plugin found");
                    }
                    byte[] data = IOUtils.toByteArray(request.getInputStream());
                    SchemaName schema = SchemaName.valueOf(inputType);
                    Deserializer deserializer = deserializerPlugin.createDeserializer(new PluginConfiguration());
                    PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData("ifc2x3tc1");
                    deserializer.init(packageMetaData);
                    IfcModelInterface model = deserializer.read(new ByteArrayInputStream(data), schema.name(), data.length, null);
                    BimServerBimBotsInput input = new BimServerBimBotsInput(getBimServer(), authorization.getUoid(), schema, data, model);
                    BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, getBimServer().getSConverter().convertToSObject(foundService.getSettings()));
                    response.setHeader("Output-Type", output.getSchemaName());
                    response.setHeader("Data-Title", output.getTitle());
                    response.setHeader("Content-Type", output.getContentType());
                    response.setHeader("Content-Disposition", output.getContentDisposition());
                    response.getOutputStream().write(output.getData());
                }
            } catch (BimBotsException e) {
                LOGGER.error("", e);
            } catch (DeserializeException e) {
                LOGGER.error("", e);
            } catch (PluginException e) {
                LOGGER.error("", e);
            } catch (ServerException e) {
                LOGGER.error("", e);
            }
        } else {
            throw new ServletException("Service \"" + serviceName + "\" does not implement the BimBotsServiceInterface");
        }
    } catch (AuthenticationException e) {
        LOGGER.error("", e);
    } catch (BimserverDatabaseException e) {
        LOGGER.error("", e);
    } catch (UserException e) {
        LOGGER.error("", e);
    }
}
Also used : ServicePlugin(org.bimserver.plugins.services.ServicePlugin) User(org.bimserver.models.store.User) SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) DatabaseSession(org.bimserver.database.DatabaseSession) AuthenticationException(org.bimserver.webservices.authorization.AuthenticationException) IfcModelInterface(org.bimserver.emf.IfcModelInterface) DataHandler(javax.activation.DataHandler) BimBotsServiceInterface(org.bimserver.bimbots.BimBotsServiceInterface) SProject(org.bimserver.interfaces.objects.SProject) SExtendedDataSchema(org.bimserver.interfaces.objects.SExtendedDataSchema) Authorization(org.bimserver.webservices.authorization.Authorization) ServletException(javax.servlet.ServletException) InputStreamDataSource(org.bimserver.utils.InputStreamDataSource) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) Random(java.util.Random) BimBotsServiceInterface(org.bimserver.bimbots.BimBotsServiceInterface) ServiceInterface(org.bimserver.shared.interfaces.ServiceInterface) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) PluginConfiguration(org.bimserver.plugins.PluginConfiguration) UserException(org.bimserver.shared.exceptions.UserException) SFile(org.bimserver.interfaces.objects.SFile) ServerException(org.bimserver.shared.exceptions.ServerException) UserSettings(org.bimserver.models.store.UserSettings) PackageMetaData(org.bimserver.emf.PackageMetaData) PluginException(org.bimserver.shared.exceptions.PluginException) DeserializerPlugin(org.bimserver.plugins.deserializers.DeserializerPlugin) BimBotsException(org.bimserver.bimbots.BimBotsException) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) BasicIfcModel(org.bimserver.ifc.BasicIfcModel) BimServerBimBotsInput(org.bimserver.bimbots.BimServerBimBotsInput) OldQuery(org.bimserver.database.OldQuery) PluginDescriptor(org.bimserver.models.store.PluginDescriptor) Revision(org.bimserver.models.store.Revision) SExtendedData(org.bimserver.interfaces.objects.SExtendedData) ByteArrayInputStream(java.io.ByteArrayInputStream) Deserializer(org.bimserver.plugins.deserializers.Deserializer) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) BimBotsOutput(org.bimserver.bimbots.BimBotsOutput) SchemaName(org.bimserver.plugins.SchemaName)

Example 5 with SFile

use of org.bimserver.interfaces.objects.SFile 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;
            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;
                        }
                        InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(realStream);
                        inputStreamDataSource.setName(name);
                        DataHandler ifcFile = new DataHandler(inputStreamDataSource);
                        if (token != null) {
                            try {
                                if (topicId == -1) {
                                    ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                    long newTopicId = service.checkin(poid, comment, deserializerOid, -1L, name, ifcFile, merge, sync);
                                    result.put("topicId", newTopicId);
                                } else {
                                    ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                    long newTopicId = service.checkinInitiated(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge, true);
                                    result.put("topicId", newTopicId);
                                }
                            } catch (Exception e) {
                                // First handle the remaining stream, so we can send the exception
                                IOUtils.copy(realStream, new OutputStream() {

                                    @Override
                                    public void write(int b) throws IOException {
                                    }

                                    @Override
                                    public void write(byte[] b, int off, int len) throws IOException {
                                    }
                                });
                                throw e;
                            }
                        }
                    } else {
                        result.put("exception", "No poid");
                    }
                }
            }
        }
    } 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) OutputStream(java.io.OutputStream) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) 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) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Aggregations

SFile (org.bimserver.interfaces.objects.SFile)10 SExtendedData (org.bimserver.interfaces.objects.SExtendedData)7 IOException (java.io.IOException)6 ServerException (org.bimserver.shared.exceptions.ServerException)5 UserException (org.bimserver.shared.exceptions.UserException)5 BcfException (org.opensourcebim.bcf.BcfException)5 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)4 DatabaseSession (org.bimserver.database.DatabaseSession)4 SExtendedDataSchema (org.bimserver.interfaces.objects.SExtendedDataSchema)4 SProject (org.bimserver.interfaces.objects.SProject)4 DeserializeException (org.bimserver.plugins.deserializers.DeserializeException)4 SerializerException (org.bimserver.plugins.serializers.SerializerException)4 BcfFile (org.opensourcebim.bcf.BcfFile)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 MalformedURLException (java.net.MalformedURLException)3 DataHandler (javax.activation.DataHandler)3 ServletException (javax.servlet.ServletException)3 SDeserializerPluginConfiguration (org.bimserver.interfaces.objects.SDeserializerPluginConfiguration)3 OutputStream (java.io.OutputStream)2