public static boolean testCommand(
     final Context context,
     final String command,
     final String contains,
     final List<String> arguments) {
   try {
     final List<String> commandAndArgs = new ArrayList<String>();
     commandAndArgs.add(command);
     commandAndArgs.addAll(arguments);
     final ProcessBuilder pb = new ProcessBuilder(commandAndArgs);
     logCommand(context, pb);
     final Process compilation = pb.start();
     final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), null);
     final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), null);
     compilation.waitFor();
     result.join();
     error.join();
     return error.output.toString().contains(contains)
         || result.output.toString().contains(contains);
   } catch (IOException ex) {
     context.log(ex.getMessage());
     return false;
   } catch (InterruptedException ex) {
     context.log(ex.getMessage());
     return false;
   }
 }
Example #2
1
 private CIJobStatus deleteCI(CIJob job, List<String> builds) throws PhrescoException {
   S_LOGGER.debug("Entering Method CIManagerImpl.deleteCI(CIJob job)");
   S_LOGGER.debug("Job name " + job.getName());
   cli = getCLI(job);
   String deleteType = null;
   List<String> argList = new ArrayList<String>();
   S_LOGGER.debug("job name " + job.getName());
   S_LOGGER.debug("Builds " + builds);
   if (CollectionUtils.isEmpty(builds)) { // delete job
     S_LOGGER.debug("Job deletion started");
     S_LOGGER.debug("Command " + FrameworkConstants.CI_JOB_DELETE_COMMAND);
     deleteType = DELETE_TYPE_JOB;
     argList.add(FrameworkConstants.CI_JOB_DELETE_COMMAND);
     argList.add(job.getName());
   } else { // delete Build
     S_LOGGER.debug("Build deletion started");
     deleteType = DELETE_TYPE_BUILD;
     argList.add(FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     argList.add(job.getName());
     StringBuilder result = new StringBuilder();
     for (String string : builds) {
       result.append(string);
       result.append(",");
     }
     String buildNos = result.substring(0, result.length() - 1);
     argList.add(buildNos);
     S_LOGGER.debug("Command " + FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     S_LOGGER.debug("Build numbers " + buildNos);
   }
   try {
     int status = cli.execute(argList);
     String message = deleteType + " deletion started in jenkins";
     if (status == FrameworkConstants.JOB_STATUS_NOTOK) {
       deleteType = deleteType.substring(0, 1).toLowerCase() + deleteType.substring(1);
       message = "Error while deleting " + deleteType + " in jenkins";
     }
     S_LOGGER.debug("Delete CI Status " + status);
     S_LOGGER.debug("Delete CI Message " + message);
     return new CIJobStatus(status, message);
   } finally {
     if (cli != null) {
       try {
         cli.close();
       } catch (IOException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       } catch (InterruptedException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       }
     }
   }
 }
  private boolean waitForAvailableConnection(long expireTime) {
    _availableWaitCount.incrementAndGet();

    try {
      synchronized (_availableLock) {
        // return false only if the timeout occurs before the wait
        boolean isAfterWait = false;

        while (!isIdleAvailable() && !isCreateAvailable()) {
          try {
            long now = CurrentTime.getCurrentTimeActual();

            long delta = expireTime - now;

            if (delta <= 0) return isAfterWait;

            Thread.interrupted();
            _availableLock.wait(delta);

            isAfterWait = true;
          } catch (InterruptedException e) {
            log.log(Level.FINER, e.toString(), e);
          }
        }

        return true;
      }
    } finally {
      _availableWaitCount.decrementAndGet();
    }
  }
Example #4
0
  public void start(boolean return_when_done) {
    // TODO Auto-generated method stub
    SwingWorker worker =
        new SwingWorker() {

          final NodeDistances this$0;

          protected Object doInBackground() throws Exception {
            return new NodeDistancesTask();
          }

          {
            this$0 = NodeDistances.this;
            // super();
          }
        };
    worker.execute();
    if (return_when_done)
      try {
        worker.get();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }
  }
  @Override
  public void run() {
    System.out.print(key + " ");
    map.put(key, key);
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    String value = map.remove(key);

    Assert.assertNotNull(value);
    Assert.assertEquals(value, key);
    //        if (value == null) {
    //            System.exit(-1);
    //        }
    //
    //        if (!value.equals(key)) {
    //            System.exit(-2);
    //        }

  }
 public void run() {
   try {
     performIntersection(this.gridPosition);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Example #7
0
 public void run() throws Exception {
   Thread[] threads = new Thread[THREADS];
   for (int i = 0; i < THREADS; i++) {
     try {
       threads[i] = new Thread(peerFactory.newClient(this), "Client " + i);
     } catch (Exception e) {
       e.printStackTrace();
       return;
     }
     threads[i].start();
   }
   try {
     for (int i = 0; i < THREADS; i++) {
       threads[i].join();
     }
   } catch (InterruptedException e) {
     setFailed();
     e.printStackTrace();
   }
   if (failed) {
     throw new Exception("*** Test '" + peerFactory.getName() + "' failed ***");
   } else {
     System.out.println("Test '" + peerFactory.getName() + "' completed successfully");
   }
 }
  /**
   * openConnections: open the connection to the master. has retry mechanism
   *
   * @return: true if the connection is built, false if failed
   */
  public boolean openConnections() {

    _log("Try to connect to Master...");

    int i = 0;
    while (true) {

      boolean isConnected = connect();

      if (!isConnected) {
        i++;
        if (i == DropboxConstants.MAX_TRY) {
          break;
        }
        _log("Cannot connect to Master, retry " + i);
        try {
          Thread.sleep(DropboxConstants.TRY_CONNECT_MILLIS);
        } catch (InterruptedException e) {
          if (!_server.noException()) {
            _elog(e.toString());
          }
          if (_server.debugMode()) {
            e.printStackTrace();
          }
          _log("Retry connection is interrupted");
          break;
        }
      } else {
        _log("Success!");
        return true;
      }
    }
    _log("Failed");
    return false;
  }
Example #9
0
 private void sleep() {
   try {
     Thread.sleep(1);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
    private void decompressTile(final File outputFile, int jp2TileX, int jp2TileY)
        throws IOException {
      final int tileIndex = bandInfo.imageLayout.numXTiles * jp2TileY + jp2TileX;
      final Process process =
          new ProcessBuilder(
                  EXE,
                  "-i",
                  imageFile.getPath(),
                  "-o",
                  outputFile.getPath(),
                  "-r",
                  getLevel() + "",
                  "-t",
                  tileIndex + "")
              .directory(cacheDir)
              .start();

      try {
        final int exitCode = process.waitFor();
        if (exitCode != 0) {
          System.err.println("Failed to uncompress tile: exitCode = " + exitCode);
        }
      } catch (InterruptedException e) {
        System.err.println("InterruptedException: " + e.getMessage());
      }
    }
Example #11
0
 protected void handleQTake(String[] args) {
   try {
     println(getQueue().take());
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Example #12
0
 private void setExecutablePermissions(File gradleHome) {
   if (isWindows()) {
     return;
   }
   File gradleCommand = new File(gradleHome, "bin/gradle");
   String errorMessage = null;
   try {
     ProcessBuilder pb = new ProcessBuilder("chmod", "755", gradleCommand.getCanonicalPath());
     Process p = pb.start();
     if (p.waitFor() == 0) {
       System.out.println("Set executable permissions for: " + gradleCommand.getAbsolutePath());
     } else {
       BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
       Formatter stdout = new Formatter();
       String line;
       while ((line = is.readLine()) != null) {
         stdout.format("%s%n", line);
       }
       errorMessage = stdout.toString();
     }
   } catch (IOException e) {
     errorMessage = e.getMessage();
   } catch (InterruptedException e) {
     errorMessage = e.getMessage();
   }
   if (errorMessage != null) {
     System.out.println(
         "Could not set executable permissions for: " + gradleCommand.getAbsolutePath());
     System.out.println("Please do this manually if you want to use the Gradle UI.");
   }
 }
Example #13
0
  private CIJobStatus buildJob(CIJob job) throws PhrescoException {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.buildJob(CIJob job)");
    }
    cli = getCLI(job);

    List<String> argList = new ArrayList<String>();
    argList.add(FrameworkConstants.CI_BUILD_JOB_COMMAND);
    argList.add(job.getName());
    try {
      int status = cli.execute(argList);
      String message = FrameworkConstants.CI_BUILD_STARTED;
      if (status == FrameworkConstants.JOB_STATUS_NOTOK) {
        message = FrameworkConstants.CI_BUILD_STARTING_ERROR;
      }
      return new CIJobStatus(status, message);
    } finally {
      if (cli != null) {
        try {
          cli.close();
        } catch (IOException e) {
          if (debugEnabled) {
            S_LOGGER.error(e.getLocalizedMessage());
          }
        } catch (InterruptedException e) {
          if (debugEnabled) {
            S_LOGGER.error(e.getLocalizedMessage());
          }
        }
      }
    }
  }
 @SuppressWarnings({"unchecked", "rawtypes"})
 public static void main(String[] args) {
   // ch.qos.logback.classic.Logger rootLogger =
   // (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
   // rootLogger.setLevel(Level.toLevel("info"));
   final ClassPathXmlApplicationContext ctx =
       new ClassPathXmlApplicationContext(CONFIG, Consumer.class);
   ctx.start();
   final QueueChannel channel = ctx.getBean("inputFromKafka", QueueChannel.class);
   Message msg;
   while ((msg = channel.receive()) != null) {
     HashMap map = (HashMap) msg.getPayload();
     Set<Map.Entry> set = map.entrySet();
     for (Map.Entry entry : set) {
       String topic = (String) entry.getKey();
       System.out.println("Topic:" + topic);
       ConcurrentHashMap<Integer, List<byte[]>> messages =
           (ConcurrentHashMap<Integer, List<byte[]>>) entry.getValue();
       Collection<List<byte[]>> values = messages.values();
       for (Iterator<List<byte[]>> iterator = values.iterator(); iterator.hasNext(); ) {
         List<byte[]> list = iterator.next();
         for (byte[] object : list) {
           String message = new String(object);
           System.out.println("\tMessage : " + message);
         }
       }
     }
   }
   try {
     Thread.sleep(100000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   ctx.close();
 }
  @Override
  public T next() {
    T t;
    boolean hasResult;

    if (!resultsQueue.isEmpty()) {
      t = resultsQueue.poll();
      hasResult = true;
    } else {
      t = null;
      hasResult = false;
    }

    // Always restart when we call next.
    while (!deferQueue.isEmpty()) {
      executorService.submit(deferQueue.poll());
    }

    // If we don't have a result...
    while (!hasResult) {

      // recheck that there is an element to be had and then wait.
      if (!hasNext()) {
        throw new NoSuchElementException();
      }

      try {
        return resultsQueue.take();
      } catch (final InterruptedException e) {
        e.printStackTrace();
      }
    }

    return t;
  }
 public void sendEmail() {
   String email = person.getEmail();
   errorMessage.setForeground(Color.blue);
   String recipientEmail = person.getEmail();
   String recipientName = person.getName();
   person.getUsername();
   person.getId();
   String newPassword = "";
   char[] newChar = new char[10];
   for (int i = 0; i < 10; i++) {
     newChar[i] = getRandomString(10).charAt(i);
     newPassword = newPassword + newChar[i];
     try {
       // if you generate more than 1 time, you must
       // put the process to sleep for awhile
       // otherwise it will return the same random
       // string
       Thread.sleep(100);
     } catch (InterruptedException d) {
       d.printStackTrace();
     }
   }
   if (sendEmail(
       "*****@*****.**", "oopjpass", recipientEmail, recipientName, newPassword)) {
     errorMessage.setText(
         errorMessage.getText() + "A replacement password has been sent to \n" + recipientEmail);
   } else {
     errorMessage.setText(errorMessage.getText() + "Sending failed.");
   }
   DesEncryption encryption = new DesEncryption("Password");
   inputPassword = encryption.encrypt(newPassword);
 }
Example #17
0
  private static void exec(String command) {
    try {
      System.out.println("Invoking: " + command);
      Process p = Runtime.getRuntime().exec(command);

      // get standard output
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line;
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      // get error output
      input = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      p.waitFor();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Example #18
0
  public static CudaEngine getCudaEngine(CudaObject co) {
    synchronized (cudaEngines) {
      if (!isCudaAvailable()) throw new CudaException("No cuda device found");
      try {
        initialization.awaitTermination(100, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Pheromone p = (Pheromone) co;
      final int pheroID = cudaObjectID.incrementAndGet();

      final CudaEngine ce = cudaEngines.get(pheroID % availableDevicesNb);
      //			final CudaEngine ce = cudaEngines.get(1);
      //			final CudaEngine ce = cudaEngines.get(0);

      //			final CudaEngine ce;
      //			if(p.getName().contains("PRE")){
      //				ce = cudaEngines.get(0);
      //			}
      //			else{
      //				ce = cudaEngines.get(1);
      //			}
      //
      ce.cudaObjects.add(co);
      System.err.println(co + "ID " + pheroID + " getting cuda engine Id " + ce.Id);
      return ce;
    }
  }
Example #19
0
 @SuppressWarnings("LockAcquiredButNotSafelyReleased")
 protected void handleLock(String[] args) {
   String lockStr = args[0];
   String key = args[1];
   Lock lock = hazelcast.getLock(key);
   if (lockStr.equalsIgnoreCase("lock")) {
     lock.lock();
     println("true");
   } else if (lockStr.equalsIgnoreCase("unlock")) {
     lock.unlock();
     println("true");
   } else if (lockStr.equalsIgnoreCase("trylock")) {
     String timeout = args.length > 2 ? args[2] : null;
     if (timeout == null) {
       println(lock.tryLock());
     } else {
       long time = Long.valueOf(timeout);
       try {
         println(lock.tryLock(time, TimeUnit.SECONDS));
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
   }
 }
Example #20
0
  public void startNGameCycles(Runnable finalAction, int nrOfRuns) {
    Class currWhitePlayer = whitePlayer.getClass();
    Class currBlackPlayer = blackPlayer.getClass();

    new Thread(
            () -> {
              for (int i = 0; i < nrOfRuns; i++) {
                progressOfNGames = OptionalDouble.of((double) i / nrOfRuns);

                GipfBoardState gipfBoardStateCopy =
                    new GipfBoardState(
                        getGipfBoardState(), gipfBoardState.getPieceMap(), gipfBoardState.players);
                Game copyOfGame = new BasicGame();
                try {
                  copyOfGame.whitePlayer = (ComputerPlayer) currWhitePlayer.newInstance();
                  copyOfGame.blackPlayer = (ComputerPlayer) currBlackPlayer.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                  e.printStackTrace();
                }
                copyOfGame.loadState(gipfBoardStateCopy);

                GameLoopThread gameLoopThread = new GameLoopThread(copyOfGame, finalAction);
                gameLoopThread.start();
                try {
                  gameLoopThread.join();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              }

              progressOfNGames = OptionalDouble.empty();
            })
        .start();
  }
Example #21
0
 /**
  * Return {@code true} if the specified dn is contained in the parent set, or in the specified DN
  * cache. This would indicate that the parent has already been processed. It returns {@code false}
  * otherwise.
  *
  * <p>It will optionally check the dn2id database for the dn if the specified cleared backend
  * boolean is {@code true}.
  *
  * @param dn The DN to check for.
  * @param dnCache The importer DN cache.
  * @param clearedBackend Set to {@code true} if the import process cleared the backend before
  *     processing.
  * @return {@code true} if the dn is contained in the parent ID, or {@code false} otherwise.
  * @throws DatabaseException If an error occurred searching the DN cache, or dn2id database.
  * @throws InterruptedException If an error occurred processing the pending map.
  */
 public boolean isParentProcessed(DN dn, DNCache dnCache, boolean clearedBackend)
     throws DatabaseException, InterruptedException {
   synchronized (synchObject) {
     if (parentSet.contains(dn)) {
       return true;
     }
   }
   // The DN was not in the parent set. Make sure it isn't pending.
   try {
     assureNotPending(dn);
   } catch (InterruptedException e) {
     logger.error(ERR_IMPORT_LDIF_PENDING_ERR, e.getMessage());
     throw e;
   }
   // Either parent is in the DN cache,
   // or else check the dn2id database for the DN (only if backend wasn't cleared)
   final boolean parentThere =
       dnCache.contains(dn)
           || (!clearedBackend && getDN2ID().get(null, dn, LockMode.DEFAULT) != null);
   // Add the DN to the parent set if needed.
   if (parentThere) {
     synchronized (synchObject) {
       if (parentSet.size() >= PARENT_ID_SET_SIZE) {
         Iterator<DN> iterator = parentSet.iterator();
         iterator.next();
         iterator.remove();
       }
       parentSet.add(dn);
     }
   }
   return parentThere;
 }
Example #22
0
 public int computeStep(int metric) {
   int work = 0;
   if (nSteps == whenToThrow) {
     throw new ExpectedRuntimeException("Hash step throw test");
   }
   if (nSteps-- > 0) {
     if (eachStepTime > 0) {
       Deadline time = Deadline.in(eachStepTime);
       while (!time.expired()) {
         try {
           Thread.sleep(1);
         } catch (InterruptedException e) {
           throw new RuntimeException(e.toString());
         }
         work++;
       }
     } else {
       work = -eachStepTime;
       TimeBase.step(work);
       try {
         Thread.sleep(1);
       } catch (InterruptedException e) {
         throw new RuntimeException(e.toString());
       }
     }
   }
   return work;
 }
Example #23
0
 @Test
 public void testCreateBroker() {
   System.out.println("testCreateBroker");
   Platform.runLater(
       new Runnable() {
         @Override
         public void run() {
           synchronized (lock) {
             // Setup
             act = new ChildActivity();
             act.setScene(new HBox());
             Response response = new Response();
             response.setStatus(Status.OK);
             response.setActivity(act);
             browser.getBrowserPanel().receiveResponse(response);
           }
         }
       });
   try {
     Thread.sleep(100);
   } catch (InterruptedException ex) {
     ex.printStackTrace();
   }
   synchronized (lock) {
     assertNotNull(act.createBroker());
   }
 }
Example #24
0
 @Override
 public Node.PropertySet[] getPropertySets() {
   final Node.PropertySet[][] props = new Node.PropertySet[1][];
   Runnable runnable =
       new Runnable() {
         @Override
         public void run() {
           FormLAF.executeWithLAFLocks(
               new Runnable() {
                 @Override
                 public void run() {
                   props[0] = component.getProperties();
                 }
               });
         }
       };
   if (EventQueue.isDispatchThread()) {
     runnable.run();
   } else {
     try {
       // We have made some attempts to keep initialization
       // of properties outside AWT thread, but it always
       // deadlocked with AWT thread for various reasons.
       EventQueue.invokeAndWait(runnable);
     } catch (InterruptedException iex) {
       FormUtils.LOGGER.log(Level.INFO, iex.getMessage(), iex);
     } catch (InvocationTargetException itex) {
       FormUtils.LOGGER.log(Level.INFO, itex.getMessage(), itex);
     }
   }
   return props[0];
 }
 @Async
 public Future<Boolean> stop(String nsr_id, String vnfr_id) {
   log.debug("Stopping ExecutionTask/CooldownTask for VNFR with id: " + vnfr_id);
   int i = 60;
   while (!actionMonitor.isTerminated(vnfr_id)
       && actionMonitor.getAction(vnfr_id) != Action.INACTIVE
       && i >= 0) {
     actionMonitor.terminate(vnfr_id);
     log.debug(
         "Waiting for finishing ExecutionTask/Cooldown for VNFR with id: "
             + vnfr_id
             + " ("
             + i
             + "s)");
     log.debug(actionMonitor.toString());
     try {
       Thread.sleep(1_000);
     } catch (InterruptedException e) {
       log.error(e.getMessage(), e);
     }
     i--;
     if (i <= 0) {
       actionMonitor.removeId(vnfr_id);
       log.error(
           "Were not able to wait until ExecutionTask finished for VNFR with id: " + vnfr_id);
       return new AsyncResult<>(false);
     }
   }
   actionMonitor.removeId(vnfr_id);
   log.info("Stopped ExecutionTask for VNFR with id: " + vnfr_id);
   return new AsyncResult<>(true);
 }
Example #26
0
  protected void runSootDirectly(String mainClass) {

    int length = getSootCommandList().getList().size();
    String temp[] = new String[length];

    getSootCommandList().getList().toArray(temp);

    sendSootOutputEvent(mainClass);
    sendSootOutputEvent(" ");

    final String[] cmdAsArray = temp;

    for (int i = 0; i < temp.length; i++) {

      sendSootOutputEvent(temp[i]);
      sendSootOutputEvent(" ");
    }
    sendSootOutputEvent("\n");

    IRunnableWithProgress op;
    try {
      newProcessStarting();
      op = new SootRunner(temp, Display.getCurrent(), mainClass);
      ((SootRunner) op).setParent(this);
      ModalContext.run(op, true, new NullProgressMonitor(), Display.getCurrent());
    } catch (InvocationTargetException e1) {
      // handle exception
      System.out.println("InvocationTargetException: " + e1.getMessage());
      System.out.println("InvocationTargetException: " + e1.getTargetException());
      System.out.println(e1.getStackTrace());
    } catch (InterruptedException e2) {
      // handle cancelation
      System.out.println("InterruptedException: " + e2.getMessage());
    }
  }
  public static void main(String[] args) {
    long head = 0;
    num_thread = Integer.parseInt(args[0]);
    long total = Long.parseLong(args[1]);
    section = total / ((long) num_thread);
    sectionHead = new long[num_thread];

    long start = System.currentTimeMillis();
    Thread[] threads = new Thread[num_thread];
    for (int i = 0; i < num_thread; i++) {
      threads[i] = new Thread(new CoinFlip(i));
      threads[i].start();
    }
    for (int j = 0; j < num_thread; j++) {
      try {
        threads[j].join();
        head = head + sectionHead[j];
      } catch (InterruptedException e) {
        System.out.println(
            "Thread interrupted.  Exception: " + e.toString() + " Message: " + e.getMessage());
        return;
      }
    }
    long end = System.currentTimeMillis();

    System.out.println(head + " heads in " + args[1] + " coin tosses");
    System.out.println("Elapsed time: " + ((end - start)) + "ms");
  }
Example #28
0
  @Override
  public void run() {

    try {
      if (Fecs.getApplicationContext() == null) return;

      Long currentTime = System.currentTimeMillis();
      double deltaTime = (currentTime - lastUpdateTime) * 0.001;

      if (getEngineState() == STATE_START) { // last bit is 1 = started
        int s = getCircumstanceState() - 1; // 0 is null state(error)
        if (s >= CircumstanceType.values().length || s < 0)
          throw new Exception("unstable state value with " + String.valueOf(s));
        Circumstance.get(CircumstanceType.values()[s])
            .setParameter("currentTime", currentTime)
            .setParameter("deltaTime", deltaTime)
            .trigger();
        for (Cabin cabin : cabins.values()) updateCabin(cabin, deltaTime);
      }

      lastUpdateTime = currentTime;

      draw();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    } finally {
      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
      }
      SwingUtilities.invokeLater(this);
    }
  }
    public void generateDiagram(String outputDirectory, File dotFile) {
      try {
        Runtime run = Runtime.getRuntime();
        Process pr =
            run.exec(
                "dot "
                    + dotFile.getAbsolutePath()
                    + " -Tpng -o"
                    + outputDirectory
                    + FILE_SEPARATOR
                    + "graph.png");
        pr.waitFor();
        // BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));

        // should the output be really printed?
        //            String line;
        //            while ( ( line = buf.readLine() ) != null )
        //            {
        //                System.out.println(line) ;
        //            }
        // FIXME how to handle exceptions in listener?
      } catch (IOException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (InterruptedException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      }
    }
Example #30
0
 void noncritical() {
   try {
     this.sleep(sleeptime);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }