/*
  * This will list all projects, select the first project with at least one
  * revision and dump the names of all walls within the last revision of that
  * project
  */
 @Test
 public void testDump() {
   try {
     ServiceMap serviceMap = bimServer.getServiceFactory().get(AccessMethod.INTERNAL);
     ServiceInterface service = serviceMap.get(ServiceInterface.class);
     String token = serviceMap.get(AuthInterface.class).login(username, password);
     service =
         bimServer
             .getServiceFactory()
             .get(token, AccessMethod.INTERNAL)
             .get(ServiceInterface.class);
     BimDatabase database = bimServer.getDatabase();
     DatabaseSession session = database.createSession();
     SProject firstProjectWithRevisions = null;
     for (SProject project : serviceMap.getServiceInterface().getAllProjects(false, true)) {
       System.out.println(project.getName());
       if (!project.getRevisions().isEmpty() && firstProjectWithRevisions == null) {
         firstProjectWithRevisions = project;
       }
     }
     if (firstProjectWithRevisions != null) {
       long roid = firstProjectWithRevisions.getLastRevisionId();
       DownloadDatabaseAction downloadDatabaseAction =
           new DownloadDatabaseAction(
               bimServer,
               session,
               AccessMethod.INTERNAL,
               roid,
               -1,
               -1,
               ((ServiceImpl) service).getAuthorization(),
               null);
       IfcModelInterface ifcModelInterface = downloadDatabaseAction.execute();
       for (IfcWall ifcWall : ifcModelInterface.getAllWithSubTypes(IfcWall.class)) {
         System.out.println(ifcWall.getName());
       }
     }
   } catch (ServiceException e) {
     e.printStackTrace();
   } catch (BimserverDatabaseException e) {
     e.printStackTrace();
   } catch (PublicInterfaceNotFoundException e) {
     e.printStackTrace();
   }
 }
  /*
   * Setup a BIMserver
   */
  @BeforeClass
  public static void initClass() {
    try {
      // Create a BIMserver
      BimServerConfig config = new BimServerConfig();
      config.setHomeDir(Paths.get("home"));
      config.setResourceFetcher(new LocalDevelopmentResourceFetcher(Paths.get("../")));
      bimServer = new BimServer(config);

      // Load plugins
      LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), null);

      // Start
      bimServer.start();

      // Convenience, setup the server to make sure it is in RUNNING state
      if (bimServer.getServerInfo().getServerState() == ServerState.NOT_SETUP) {
        bimServer
            .getService(AdminInterface.class)
            .setup(
                "http://localhost",
                "localhost",
                "*****@*****.**",
                "Administrator",
                "*****@*****.**",
                "admin");
      }

      // Change a setting to normal users can create projects
      //			bimServer.getSettingsManager().getSettings().setAllowUsersToCreateTopLevelProjects(true);
    } catch (ServiceException e) {
      e.printStackTrace();
    } catch (PluginException e) {
      e.printStackTrace();
    } catch (DatabaseInitException e) {
      e.printStackTrace();
    } catch (BimserverDatabaseException e) {
      e.printStackTrace();
    } catch (DatabaseRestartRequiredException e) {
      e.printStackTrace();
    }
  }
 public String getFileNameWithoutExtension() {
   switch (downloadType) {
     case DOWNLOAD_REVISION:
       return getRoidsString();
     case DOWNLOAD_BY_GUIDS:
       return getRoidsString() + "-" + getGuidsString();
     case DOWNLOAD_BY_NAMES:
       return getRoidsString() + "-" + getNamesString();
     case DOWNLOAD_BY_OIDS:
       return getRoidsString() + "-" + getOidsString();
     case DOWNLOAD_OF_TYPE:
       return getRoidsString() + "-" + classNames;
     case DOWNLOAD_PROJECTS:
       DatabaseSession session = bimServer.getDatabase().createSession();
       StringBuilder fileName = new StringBuilder();
       for (long roid : roids) {
         Revision revision;
         try {
           revision =
               session.get(
                   session.getEClassForName("store", "Revision"), roid, Query.getDefault());
           for (ConcreteRevision concreteRevision : revision.getConcreteRevisions()) {
             fileName.append(concreteRevision.getProject().getName() + "-");
           }
         } catch (BimserverDatabaseException e) {
           e.printStackTrace();
         }
       }
       fileName.delete(fileName.length() - 1, fileName.length());
       return fileName.toString();
     case DOWNLOAD_COMPARE:
       return "compare";
     case DOWNLOAD_JSON_QUERY:
       return getRoidsString();
     case DOWNLOAD_QUERY:
       return "query";
   }
   return "unknown";
 }
  private void start() {
    BimServerConfig config = new BimServerConfig();
    Path homeDir = Paths.get("home");
    try {
      if (Files.isDirectory(homeDir)) {
        PathUtils.removeDirectoryWithContent(homeDir);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    config.setClassPath(System.getProperty("java.class.path"));
    config.setHomeDir(homeDir);
    config.setPort(8080);
    config.setStartEmbeddedWebServer(true);
    config.setResourceFetcher(new LocalDevelopmentResourceFetcher(Paths.get("../")));
    final BimServer bimServer = new BimServer(config);
    try {
      LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), null);
      bimServer.start();
      if (bimServer.getServerInfo().getServerState() == ServerState.NOT_SETUP) {
        bimServer
            .getService(AdminInterface.class)
            .setup(
                "http://localhost",
                "localhost",
                "*****@*****.**",
                "Administrator",
                "*****@*****.**",
                "admin");
      }
    } catch (PluginException e2) {
      e2.printStackTrace();
    } catch (ServerException e) {
      e.printStackTrace();
    } catch (DatabaseInitException e) {
      e.printStackTrace();
    } catch (BimserverDatabaseException e) {
      e.printStackTrace();
    } catch (DatabaseRestartRequiredException e) {
      e.printStackTrace();
    } catch (UserException e) {
      e.printStackTrace();
    }

    try {
      final ServiceMap serviceMap = bimServer.getServiceFactory().get(AccessMethod.INTERNAL);
      ServiceInterface serviceInterface = serviceMap.get(ServiceInterface.class);
      SettingsInterface settingsInterface = serviceMap.get(SettingsInterface.class);
      final Bimsie1AuthInterface authInterface = serviceMap.get(Bimsie1AuthInterface.class);
      serviceInterface =
          bimServer
              .getServiceFactory()
              .get(authInterface.login("*****@*****.**", "admin"), AccessMethod.INTERNAL)
              .get(ServiceInterface.class);
      settingsInterface.setCacheOutputFiles(true);
      settingsInterface.setGenerateGeometryOnCheckin(false);
      final SProject project =
          serviceMap.getBimsie1ServiceInterface().addProject("test", "ifc2x3tc1");
      SDeserializerPluginConfiguration deserializerByName =
          serviceMap.getBimsie1ServiceInterface().getDeserializerByName("IfcStepDeserializer");
      Path file = Paths.get("../TestData/data/AC11-Institute-Var-2-IFC.ifc");
      serviceInterface.checkin(
          project.getOid(),
          "test",
          deserializerByName.getOid(),
          file.toFile().length(),
          file.getFileName().toString(),
          new DataHandler(new FileDataSource(file.toFile())),
          false,
          true);
      final SProject projectUpdate =
          serviceMap.getBimsie1ServiceInterface().getProjectByPoid(project.getOid());
      ThreadPoolExecutor executor =
          new ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(1000));
      for (int i = 0; i < 20; i++) {
        executor.execute(
            new Runnable() {
              @Override
              public void run() {
                try {
                  ServiceMap serviceMap2 =
                      bimServer
                          .getServiceFactory()
                          .get(
                              authInterface.login("*****@*****.**", "admin"),
                              AccessMethod.INTERNAL);
                  SSerializerPluginConfiguration serializerPluginConfiguration =
                      serviceMap.getBimsie1ServiceInterface().getSerializerByName("Ifc2x3");
                  Long download =
                      serviceMap2
                          .getBimsie1ServiceInterface()
                          .download(
                              projectUpdate.getLastRevisionId(),
                              serializerPluginConfiguration.getOid(),
                              true,
                              true);
                  SDownloadResult downloadData =
                      serviceMap2.getBimsie1ServiceInterface().getDownloadData(download);
                  if (downloadData.getFile().getDataSource()
                      instanceof CacheStoringEmfSerializerDataSource) {
                    CacheStoringEmfSerializerDataSource c =
                        (CacheStoringEmfSerializerDataSource)
                            downloadData.getFile().getDataSource();
                    try {
                      ByteArrayOutputStream baos = new ByteArrayOutputStream();
                      c.writeToOutputStream(baos, null);
                      System.out.println(baos.size());
                    } catch (SerializerException e) {
                      e.printStackTrace();
                    }
                  } else {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(downloadData.getFile().getInputStream(), baos);
                    System.out.println(baos.size());
                  }
                  serviceMap2.getServiceInterface().cleanupLongAction(download);
                } catch (ServerException e) {
                  e.printStackTrace();
                } catch (UserException e) {
                  e.printStackTrace();
                } catch (FileNotFoundException e) {
                  e.printStackTrace();
                } catch (IOException e) {
                  e.printStackTrace();
                } catch (PublicInterfaceNotFoundException e1) {
                  e1.printStackTrace();
                }
              }
            });
      }
      executor.shutdown();
      executor.awaitTermination(1, TimeUnit.HOURS);
      bimServer.stop();
    } catch (ServerException e1) {
      e1.printStackTrace();
    } catch (UserException e1) {
      e1.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }