Search in sources :

Example 1 with ServiceMap

use of org.bimserver.webservices.ServiceMap in project BIMserver by opensourceBIM.

the class AllTests method setup.

private static void setup() {
    // Create a config
    Path home = Paths.get("tmptestdata/home-" + new Random().nextInt(1000000000));
    // Remove the home dir if it's there
    if (Files.exists(home)) {
        try {
            PathUtils.removeDirectoryWithContent(home);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    BimServerConfig config = new BimServerConfig();
    config.setHomeDir(home);
    config.setStartEmbeddedWebServer(true);
    config.setPort(7010);
    config.setResourceFetcher(new LocalDevelopmentResourceFetcher(Paths.get("../")));
    config.setClassPath(System.getProperty("java.class.path"));
    bimServer = new BimServer(config);
    try {
        bimServer.setEmbeddedWebServer(new EmbeddedWebServer(bimServer, Paths.get("."), false));
        // CHANGE THESE TO MATCH YOUR CONFIGURATION
        // Path[] pluginDirectories = new Path[]{Paths.get("C:\\Git\\IfcPlugins\\IfcPlugins"), Paths.get("C:\\Git\\IfcOpenShell-BIMserver-plugin")};
        // Start it
        bimServer.start();
        // Load plugins
        // LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), pluginDirectories);
        // Get a client, not using any protocol (direct connection)
        BimServerClientInterface client = bimServer.getBimServerClientFactory().create();
        // Setup the server
        client.getAdminInterface().setup("http://localhost:7010", "Test Name", "Test Description", "noicon", "Administrator", "admin@bimserver.org", "admin");
        ServiceMap serviceMap = bimServer.getServiceFactory().get(new SystemAuthorization(1, TimeUnit.HOURS), AccessMethod.INTERNAL);
        serviceMap.getSettingsInterface().setCacheOutputFiles(false);
        client.disconnect();
        client = bimServer.getBimServerClientFactory().create(new UsernamePasswordAuthenticationInfo("admin@bimserver.org", "admin"));
        String pluginsString = System.getProperty("plugins");
        if (pluginsString != null) {
            String[] plugins = pluginsString.split(";");
            Path[] paths = new Path[plugins.length];
            int i = 0;
            for (String p : plugins) {
                paths[i++] = Paths.get(p);
            }
            LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), paths);
        } else {
            LoggerFactory.getLogger(AllTests.class).info("Installing plugins");
            client.getPluginInterface().installPluginBundle("http://archiva.logic-labs.nl/repository/snapshots", "org.opensourcebim", "ifcplugins", null, null);
            client.getPluginInterface().installPluginBundle("http://archiva.logic-labs.nl/repository/snapshots", "org.opensourcebim", "binaryserializers", null, null);
            client.getPluginInterface().installPluginBundle("http://archiva.logic-labs.nl/repository/snapshots", "org.opensourcebim", "ifcopenshellplugin", null, null);
        }
        client.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Path(java.nio.file.Path) ServiceMap(org.bimserver.webservices.ServiceMap) UsernamePasswordAuthenticationInfo(org.bimserver.shared.UsernamePasswordAuthenticationInfo) BimServer(org.bimserver.BimServer) IOException(java.io.IOException) SystemAuthorization(org.bimserver.webservices.authorization.SystemAuthorization) BimServerConfig(org.bimserver.BimServerConfig) LocalDevelopmentResourceFetcher(org.bimserver.shared.LocalDevelopmentResourceFetcher) EmbeddedWebServer(org.bimserver.EmbeddedWebServer) IOException(java.io.IOException) Random(java.util.Random) BimServerClientInterface(org.bimserver.plugins.services.BimServerClientInterface)

Example 2 with ServiceMap

use of org.bimserver.webservices.ServiceMap in project BIMserver by opensourceBIM.

the class SyndicationServlet 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;
    }
    if (request.getHeader("Authorization") != null) {
        String authorization = request.getHeader("Authorization");
        String usernamePasswordEncoded = authorization.substring(6);
        String decodeBase64 = new String(Base64.decodeBase64(usernamePasswordEncoded.getBytes(Charsets.UTF_8)), Charsets.UTF_8);
        if (decodeBase64.equals(":")) {
            response.getWriter().print("Not authenticated");
            return;
        }
        String[] split = decodeBase64.split(":");
        String username = split[0];
        String password = split[1];
        String token = (String) getServletContext().getAttribute("token");
        ServiceMap serviceMap = null;
        try {
            if (token == null) {
                serviceMap = getBimServer().getServiceFactory().get(AccessMethod.SYNDICATION);
            } else {
                serviceMap = getBimServer().getServiceFactory().get(token, AccessMethod.SYNDICATION);
            }
            if (serviceMap.getAuthInterface().login(username, password) != null) {
                String requestURI = request.getRequestURI();
                response.setContentType("application/atom+xml");
                try {
                    if (requestURI.endsWith("/projects")) {
                        writeProjectsFeed(request, response, serviceMap);
                    } else if (requestURI.contains("/revisions")) {
                        writeRevisionsFeed(request, response, serviceMap);
                    } else if (requestURI.contains("/checkouts")) {
                        writeCheckoutsFeed(request, response, serviceMap);
                    }
                } catch (ServiceException e) {
                    response.setContentType("text/html");
                    response.getWriter().println(e.getUserMessage());
                } catch (FeedException e) {
                    LOGGER.error("", e);
                }
            } else {
                response.setStatus(401);
                response.setHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"");
            }
        } catch (ServiceException e) {
            LOGGER.error("", e);
        } catch (PublicInterfaceNotFoundException e) {
            LOGGER.error("", e);
        }
    } else {
        response.setStatus(401);
        response.setHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"");
    }
}
Also used : ServiceMap(org.bimserver.webservices.ServiceMap) ServiceException(org.bimserver.shared.exceptions.ServiceException) FeedException(com.rometools.rome.io.FeedException) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException)

Example 3 with ServiceMap

use of org.bimserver.webservices.ServiceMap in project BIMserver by opensourceBIM.

the class NewRevisionNotification method triggerNewRevision.

public void triggerNewRevision(DatabaseSession session, NotificationsManager notificationsManager, final BimServer bimServer, String siteAddress, Project project, final long roid, Trigger trigger, final NewService service) throws UserException, ServerException {
    ServiceMap serviceMap = bimServer.getServiceFactory().get(authorization, AccessMethod.INTERNAL);
    Thread thread = new Thread() {

        @Override
        public void run() {
            try {
                serviceMap.get(ServiceInterface.class).triggerRevisionService(roid, service.getOid());
            } catch (Exception e) {
                LOGGER.error("", e);
            }
        }
    };
    thread.start();
}
Also used : ServiceMap(org.bimserver.webservices.ServiceMap) RemoteServiceInterface(org.bimserver.shared.interfaces.RemoteServiceInterface) ServiceInterface(org.bimserver.shared.interfaces.ServiceInterface) AsyncRemoteServiceInterface(org.bimserver.shared.interfaces.async.AsyncRemoteServiceInterface) ModelCheckException(org.bimserver.plugins.modelchecker.ModelCheckException) UserException(org.bimserver.shared.exceptions.UserException) ChannelConnectionException(org.bimserver.shared.ChannelConnectionException) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException) ServerException(org.bimserver.shared.exceptions.ServerException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException)

Example 4 with ServiceMap

use of org.bimserver.webservices.ServiceMap 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 5 with ServiceMap

use of org.bimserver.webservices.ServiceMap in project BIMserver by opensourceBIM.

the class Streamer method onText.

public void onText(Reader reader) {
    JsonReader jsonreader = new JsonReader(reader);
    JsonParser parser = new JsonParser();
    JsonObject request = (JsonObject) parser.parse(jsonreader);
    if (request.has("hb")) {
    // Heartbeat, ignore
    } else if (request.has("action")) {
        if (request.get("action").getAsString().equals("download")) {
            final long topicId = request.get("topicId").getAsLong();
            Thread thread = new Thread() {

                @Override
                public void run() {
                    try {
                        LongAction<?> longAction = bimServer.getLongActionManager().getLongAction(topicId);
                        Writer writer = null;
                        if (longAction instanceof LongStreamingDownloadAction) {
                            LongStreamingDownloadAction longStreamingDownloadAction = (LongStreamingDownloadAction) longAction;
                            writer = longStreamingDownloadAction.getMessagingStreamingSerializer();
                        } else {
                            LongDownloadOrCheckoutAction longDownloadAction = (LongDownloadOrCheckoutAction) longAction;
                            writer = longDownloadAction.getMessagingSerializer();
                        }
                        boolean writeMessage = true;
                        int counter = 0;
                        long bytes = 0;
                        long start = System.nanoTime();
                        // TODO whenever a large object has been sent, the large buffer stays in memory until websocket closes...
                        ReusableLittleEndianDataOutputStream byteArrayOutputStream = new ReusableLittleEndianDataOutputStream();
                        GrowingByteBuffer growingByteBuffer = byteArrayOutputStream.getGrowingByteBuffer();
                        ProgressReporter progressReporter = new ProgressReporter() {

                            @Override
                            public void update(long progress, long max) {
                                longAction.updateProgress("test", (int) ((progress * 100) / max));
                            }

                            @Override
                            public void setTitle(String title) {
                            }
                        };
                        do {
                            byteArrayOutputStream.reset();
                            byteArrayOutputStream.writeLong(topicId);
                            writeMessage = writer.writeMessage(byteArrayOutputStream, progressReporter);
                            bytes += growingByteBuffer.usedSize();
                            streamingSocketInterface.sendBlocking(growingByteBuffer.array(), 0, growingByteBuffer.usedSize());
                            counter++;
                        } while (writeMessage);
                        long end = System.nanoTime();
                        LOGGER.info(counter + " messages written " + Formatters.bytesToString(bytes) + " in " + ((end - start) / 1000000) + " ms");
                    } catch (IOException e) {
                    // Probably closed/F5-ed browser
                    } catch (SerializerException e) {
                        LOGGER.error("", e);
                    }
                }
            };
            thread.setName("Streamer " + topicId);
            thread.start();
        }
    } else if (request.has("token")) {
        String token = request.get("token").getAsString();
        try {
            ServiceMap serviceMap = bimServer.getServiceFactory().get(token, AccessMethod.JSON);
            uoid = serviceMap.getBimServerAuthInterface().getLoggedInUser().getOid();
            this.endpointid = bimServer.getEndPointManager().register(this);
            JsonObject enpointMessage = new JsonObject();
            enpointMessage.add("endpointid", new JsonPrimitive(endpointid));
            streamingSocketInterface.send(enpointMessage);
        } catch (UserException e) {
            LOGGER.error("", e);
        } catch (ServerException e) {
            LOGGER.error("", e);
        }
    } else {
        bimServer.getJsonHandler().execute(request, null, new NullWriter());
    }
}
Also used : LongAction(org.bimserver.longaction.LongAction) ServerException(org.bimserver.shared.exceptions.ServerException) ServiceMap(org.bimserver.webservices.ServiceMap) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) LongStreamingDownloadAction(org.bimserver.longaction.LongStreamingDownloadAction) ProgressReporter(org.bimserver.plugins.serializers.ProgressReporter) IOException(java.io.IOException) SerializerException(org.bimserver.plugins.serializers.SerializerException) NullWriter(org.apache.commons.io.output.NullWriter) LongDownloadOrCheckoutAction(org.bimserver.longaction.LongDownloadOrCheckoutAction) JsonReader(com.google.gson.stream.JsonReader) UserException(org.bimserver.shared.exceptions.UserException) NullWriter(org.apache.commons.io.output.NullWriter) Writer(org.bimserver.plugins.serializers.Writer) GrowingByteBuffer(org.bimserver.utils.GrowingByteBuffer) JsonParser(com.google.gson.JsonParser)

Aggregations

ServiceMap (org.bimserver.webservices.ServiceMap)7 IOException (java.io.IOException)4 ServerException (org.bimserver.shared.exceptions.ServerException)4 UserException (org.bimserver.shared.exceptions.UserException)4 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)3 SerializerException (org.bimserver.plugins.serializers.SerializerException)3 ServiceException (org.bimserver.shared.exceptions.ServiceException)3 Path (java.nio.file.Path)2 BimServer (org.bimserver.BimServer)2 BimServerConfig (org.bimserver.BimServerConfig)2 SDownloadResult (org.bimserver.interfaces.objects.SDownloadResult)2 ProgressReporter (org.bimserver.plugins.serializers.ProgressReporter)2 PublicInterfaceNotFoundException (org.bimserver.shared.exceptions.PublicInterfaceNotFoundException)2 JsonObject (com.google.gson.JsonObject)1 JsonParser (com.google.gson.JsonParser)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 JsonReader (com.google.gson.stream.JsonReader)1 FeedException (com.rometools.rome.io.FeedException)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1