@Override
  public void setSymbols(List<List<String>> symbols) {
    log.info("set symbols called");

    clearTickSymbols();

    final List<TickParms> tp = new ArrayList<TickParms>();

    try {

      TickParms p;
      for (List<String> m : symbols) {
        p = new TickParms();
        p.setSymbol(m.get(0));
        p.setMinvol(Integer.parseInt(m.get(1)));
        p.setMaxvol(Integer.parseInt(m.get(2)));
        p.setPriceBasis(Double.parseDouble(m.get(3)));
        tp.add(p);
      }

    } catch (Exception e) {
      log.severe("caught exception parsing parms: " + e.getMessage());
    }

    log.info(String.format("calling setSymbols with %d symbols\n", tp.size()));
    try {
      ctx.getBean(TickGenerator.class).setSymbols(tp.toArray(new TickParms[] {}));
    } catch (Exception e) {
      log.severe("caught exception setting parms: " + e.getMessage());
    }
  }
  protected void closeWebDriver(Thread thread) {
    ALL_WEB_DRIVERS_THREADS.remove(thread);
    WebDriver webdriver = THREAD_WEB_DRIVER.remove(thread.getId());

    if (webdriver != null && !holdBrowserOpen) {
      log.info("Close webdriver: " + thread.getId() + " -> " + webdriver);

      long start = System.currentTimeMillis();

      Thread t = new Thread(new CloseBrowser(webdriver));
      t.setDaemon(true);
      t.start();

      try {
        t.join(closeBrowserTimeoutMs);
      } catch (InterruptedException e) {
        log.log(FINE, "Failed to close webdriver in " + closeBrowserTimeoutMs + " milliseconds", e);
      }

      long duration = System.currentTimeMillis() - start;
      if (duration >= closeBrowserTimeoutMs) {
        log.severe("Failed to close webdriver in " + closeBrowserTimeoutMs + " milliseconds");
      } else if (duration > 200) {
        log.info("Closed webdriver in " + duration + " ms");
      } else {
        log.fine("Closed webdriver in " + duration + " ms");
      }
    }
  }
  public void process(String queueName) {
    XtrTask xtrTask;
    Queue gaeQueue = QueueFactory.getDefaultQueue();

    log.info("Processing queue " + queueName);

    java.util.Queue<XtrTask> taskQueue = queues.get(queueName);
    if (taskQueue == null) {
      log.warning("Queue " + queueName + " does not exist");
      return;
    }

    TaskHandle taskHandle = null;

    while ((xtrTask = taskQueue.poll()) != null) {
      taskHandle =
          gaeQueue.add(
              url("/webxtractor/task/".concat(queueName))
                  .param("payload", xtrTask.getPayload())
                  .method(TaskOptions.Method.GET));
      log.info(
          "GA queue "
              + taskHandle.getQueueName()
              + " accepted task "
              + xtrTask.getName()
              + " as "
              + taskHandle.getName()
              + " estimated to run at "
              + taskHandle.getEtaMillis());
    }
  }
示例#4
0
  @Test
  public void testNEQ() {
    Model m1 = new CPModel();
    IntegerVariable x = makeIntVar("x", 2, 4);
    IntegerVariable y = makeIntVar("y", 2, 4);

    m1.addConstraint(distanceNEQ(x, y, -2));

    Model m2 = new CPModel();
    m2.addConstraint(neq(abs(minus(x, y)), -2));

    Solver s1 = new CPSolver();
    s1.read(m1);

    Solver s2 = new CPSolver();
    s2.read(m2);

    //        s1.solveAll();
    //        s2.solveAll();
    s1.solve();
    do {
      LOGGER.info("x:" + s1.getVar(x).getVal() + " y:" + s1.getVar(y).getVal());
    } while (s1.nextSolution());
    LOGGER.info("=======");

    s2.solve();
    do {
      LOGGER.info("x:" + s2.getVar(x).getVal() + " y:" + s2.getVar(y).getVal());
    } while (s2.nextSolution());

    Assert.assertEquals("nb sol", s1.getNbSolutions(), s2.getNbSolutions());
  }
示例#5
0
 @Test
 public void test3BoundsSolve() {
   for (int seed = 0; seed < 10; seed++) {
     m = new CPModel();
     s = new CPSolver();
     int k = 9, k1 = 7, k2 = 6;
     IntegerVariable v0 = makeIntVar("v0", 0, 10);
     IntegerVariable v1 = makeIntVar("v1", 0, 10);
     IntegerVariable v2 = makeIntVar("v2", 0, 10);
     IntegerVariable v3 = makeIntVar("v3", 0, 10);
     m.addVariables(Options.V_BOUND, v0, v1, v2, v3);
     m.addConstraint(distanceEQ(v0, v1, k));
     m.addConstraint(distanceEQ(v1, v2, k1));
     m.addConstraint(distanceEQ(v2, v3, k2));
     s.read(m);
     s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
     s.setValIntSelector(new RandomIntValSelector(seed));
     try {
       s.propagate();
     } catch (ContradictionException e) {
       LOGGER.info(e.getMessage()); // To change body of catch statement use File | Settings | File
       // Templates.
     }
     s.solveAll();
     int nbNode = s.getNodeCount();
     LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
     assertEquals(s.getNbSolutions(), 4);
   }
 }
示例#6
0
 /** Creates a new empty project in a temp directory */
 public void test2Reload() {
   logger.info("test2Reload");
   try {
     if (_project != null) {
       _project.close();
     }
     assertNotNull(
         _editor =
             FlexoResourceManager.initializeExistingProject(
                 _projectDirectory, EDITOR_FACTORY, null));
     _project = _editor.getProject();
   } catch (ProjectInitializerException e) {
     e.printStackTrace();
     fail();
   } catch (ProjectLoadingCancelledException e) {
     e.printStackTrace();
     fail();
   }
   logger.info("_project.getGeneratedCode()=" + _project.getGeneratedCode());
   _project.close();
   FileUtils.deleteDir(_projectDirectory);
   _editor = null;
   _project = null;
   _projectDirectory = null;
   _projectIdentifier = null;
 }
  /**
   * Reads incoming data from the client:
   *
   * <UL>
   *   <LI>Reads some bytes from the SocketChannel
   *   <LI>create a protocolTask, to process this data, possibly generating an answer
   *   <LI>Inserts the Task to the ThreadPool
   * </UL>
   *
   * @throws
   * @throws IOException in case of an IOException during reading
   */
  public void read() {
    // do not read if OLD.protocol has terminated. only write of pending data is
    // allowed
    if (_protocol.shouldClose()) {
      return;
    }

    SocketAddress address = _sChannel.socket().getRemoteSocketAddress();
    logger.info("Reading from " + address);

    ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
    int numBytesRead = 0;
    try {
      numBytesRead = _sChannel.read(buf);
    } catch (IOException e) {
      numBytesRead = -1;
    }
    // is the channel closed??
    if (numBytesRead == -1) {
      // No more bytes can be read from the channel
      logger.info("client on " + address + " has disconnected");
      closeConnection();
      // tell the OLD.protocol that the connection terminated.
      _protocol.connectionTerminated();
      return;
    }

    // add the buffer to the OLD.protocol task
    buf.flip();
    _task.addBytes(buf);
    // add the OLD.protocol task to the OLD.reactor
    _data.getExecutor().execute(_task);
  }
  private long checkInternal(MesosComputer c) {
    if (c.getNode() == null) {
      return 1;
    }

    // If we just launched this computer, check back after 1 min.
    // NOTE: 'c.getConnectTime()' refers to when the Jenkins slave was launched.
    if ((System.currentTimeMillis() - c.getConnectTime())
        < MINUTES.toMillis(idleTerminationMinutes)) {
      return 1;
    }

    // If the computer is offline, terminate it.
    if (c.isOffline()) {
      LOGGER.info("Disconnecting offline computer " + c.getName());
      c.getNode().terminate();
      return 1;
    }

    // Terminate the computer if it is idle for longer than
    // 'idleTerminationMinutes'.
    if (c.isIdle()) {
      final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();

      if (idleMilliseconds > MINUTES.toMillis(idleTerminationMinutes)) {
        LOGGER.info("Disconnecting idle computer " + c.getName());
        c.getNode().terminate();
      }
    }
    return 1;
  }
  public void run() {

    if (SMPPSim.isCallback()) {
      synchronized (mutex) {
        boolean connected = false;
        Socket callback;
        while (!connected) {
          try {
            callback = new Socket(SMPPSim.getCallback_target_host(), SMPPSim.getCallback_port());
            connected = true;
            smsc.setCallback(callback);
            smsc.setCallback_stream(callback.getOutputStream());
            smsc.setCallback_server_online(true);
            logger.info("Connected to callback server");
          } catch (Exception ce) {
            try {
              logger.info("Callback server not accepting connections - retrying");
              Thread.sleep(1000);
            } catch (InterruptedException ie) {
            }
          }
        }
        mutex.notifyAll();
      }
    }
  }
示例#10
0
 private void setWorldConfigFile(File newFile) {
   if ((worldConfigFile == null)
       || (!newFile.getAbsolutePath().equals(worldConfigFile.getAbsolutePath()))) {
     worldConfigFile = newFile;
     if (usable(worldConfigFile)) {
       // usable world
       logger.info(worldConfigFile.getPath());
       if (newFile.exists()) {
         worldSpecific = new Configuration(worldConfigFile);
         logger.info("exists ");
         worldSpecific.load();
         settings.readFrom(worldSpecific);
       } else {
         logger.info("doesn't exist");
         worldSpecific = new Configuration(worldConfigFile);
         // else we use the default;
         settings.readFrom(general);
         settings.copyTo(worldSpecific);
       }
       worldSpecific.save();
     } else {
       logger.info("null file");
       worldSpecific = null;
       settings.readFrom(general);
     }
   }
 }
  /**
   * One common task in machine learning is evaluating an algorithm’s accuracy. One way you can use
   * the existing data is to take some portion, say 90%, to train the classifier. Then you’ll take
   * the remaining 10% to test the classifier and see how accurate it is.
   *
   * @return
   * @throws IOException
   */
  public int classifyTest() throws IOException {
    FileHelper fileHelper = new FileHelper(INPUT_FILE_NAME);
    Matrix dataSet = fileHelper.getMatrix();
    Matrix normMat = autoNormalize(dataSet);
    int testSetLength = (int) (normMat.getRowDimension() * TEST_RATIO);
    Matrix trainingSubmatrix =
        normMat.getMatrix(
            testSetLength, normMat.getRowDimension() - 1, 0, normMat.getColumnDimension() - 1);
    List<Integer> classLabels = fileHelper.getClassLabels();
    List<Integer> trainingClassLabels = classLabels.subList(testSetLength, classLabels.size());

    int errorCount = 0;
    for (int i = 0; i < testSetLength; i++) {
      int classifierResult =
          classify(normMat.getArray()[i], trainingSubmatrix, trainingClassLabels, K_NUMBER);
      System.out.println(
          String.format(
              "The classifier came back with: %d, the real answer is: %d",
              classifierResult, classLabels.get(i)));
      if (classifierResult != classLabels.get(i)) {
        errorCount++;
      }
    }
    log.info("The total error rate is: " + errorCount / (float) testSetLength);
    log.info("Error number: " + errorCount);
    return errorCount;
  }
示例#12
0
 private boolean importIsland(uSkyBlock plugin, File file) {
   log.info("Importing " + file);
   FileConfiguration config = new YamlConfiguration();
   readConfig(config, file);
   if (config.contains("party.leader") && !config.contains("party.leader.name")) {
     String leaderName = config.getString("party.leader");
     ConfigurationSection leaderSection = config.createSection("party.leader");
     leaderSection.set("name", leaderName);
     leaderSection.set("uuid", UUIDUtil.asString(getUUID(leaderName)));
   }
   ConfigurationSection members = config.getConfigurationSection("party.members");
   if (members != null) {
     for (String member : members.getKeys(false)) {
       ConfigurationSection section = members.getConfigurationSection(member);
       if (!section.contains("name")) {
         members.set(member, null);
         String uuid = UUIDUtil.asString(getUUID(member));
         members.createSection(uuid, section.getValues(true));
         members.set(uuid + ".name", member);
       } else {
         log.info("Skipping " + member + ", already has a name");
       }
     }
   }
   try {
     config.save(file);
     return true;
   } catch (IOException e) {
     log.log(Level.SEVERE, "Failed to import " + file, e);
     return false;
   }
 }
示例#13
0
  public Set<MeemPath> getAllPaths() {
    Set<MeemPath> paths = new HashSet<MeemPath>();

    if (DEBUG) {
      logger.info("Getting all MeemPaths");
    }

    try {
      EntityManager em = PersistenceContext.instance().getEntityManager();
      em.getTransaction().begin();

      @SuppressWarnings("unchecked")
      List<String> ids = em.createNamedQuery("Content.selectIds").getResultList();
      for (String id : ids) {
        MeemPath meemPath = MeemPath.spi.create(Space.MEEMSTORE, id);
        //				if (DEBUG) {
        //					logger.info("Got MeemPath: " + meemPath);
        //				}
        paths.add(meemPath);
      }
      em.getTransaction().commit();
    } catch (Exception e) {
      logger.log(Level.INFO, "Exception while retriving MeemPaths from MeemStore", e);
    } finally {
      PersistenceContext.instance().release();
    }
    if (DEBUG) {
      logger.info("Returning " + paths.size() + " MeemPaths");
    }
    return paths;
  }
示例#14
0
 private void showCC() {
   for (int i = 0; i < setCC.size(); i++) {
     IStateBitSet contain = setCC.elementAt(i);
     LOGGER.info("cc(" + i + ") = " + contain.toString());
   }
   LOGGER.info("*-*-*-*-*-*-*-*-*-*-*-*-*");
 }
 private static void readJsonFile() {
   try (JsonReader jsonReader =
       Json.createReader(
           new FileReader(
               Paths.get(System.getProperty("user.dir"), "target/myData.json").toString()))) {
     JsonStructure jsonStructure = jsonReader.read();
     JsonValue.ValueType valueType = jsonStructure.getValueType();
     if (valueType == JsonValue.ValueType.OBJECT) {
       JsonObject jsonObject = (JsonObject) jsonStructure;
       JsonValue firstName = jsonObject.get("firstName");
       LOGGER.info("firstName=" + firstName);
       JsonValue emailAddresses = jsonObject.get("phoneNumbers");
       if (emailAddresses.getValueType() == JsonValue.ValueType.ARRAY) {
         JsonArray jsonArray = (JsonArray) emailAddresses;
         for (int i = 0; i < jsonArray.size(); i++) {
           JsonValue jsonValue = jsonArray.get(i);
           LOGGER.info("emailAddress(" + i + "): " + jsonValue);
         }
       }
     } else {
       LOGGER.warning("First object is not of type " + JsonValue.ValueType.OBJECT);
     }
   } catch (FileNotFoundException e) {
     LOGGER.severe("Failed to open file: " + e.getMessage());
   }
 }
 /**
  * Method to create a new TE LSP initiated in this node
  *
  * @param destinationId IP AddreStart LSP Errorss of the destination of the LSP
  * @param bw Bandwidth requested
  * @param bidirectional bidirectional
  * @param OFcode
  * @throws LSPCreationException
  */
 public long addnewLSP(
     Inet4Address destinationId, float bw, boolean bidirectional, int OFcode, int lspID)
     throws LSPCreationException {
   log.info("Adding New LSP to " + destinationId);
   // FIXME: mirar esto
   // meter structura --> RequestedLSPinformation --> Dependiente de cada tecnologia
   // meter campo con el estado del LSP e ir cambiandolo
   LSPTE lsp =
       new LSPTE(
           lspID,
           localIP,
           destinationId,
           bidirectional,
           OFcode,
           bw,
           PathStateParameters.creatingLPS);
   LSPList.put(new LSPKey(localIP, lsp.getIdLSP()), lsp);
   ReentrantLock lock = new ReentrantLock();
   Condition lspEstablished = lock.newCondition();
   // log.info("Metemos en Lock list con ID: "+lsp.getIdLSP());
   lockList.put(lsp.getIdLSP(), lock);
   conditionList.put(lsp.getIdLSP(), lspEstablished);
   /*log.info("Size lockList : "+lockList.size());
   log.info("Size conditionList : "+conditionList.size());*/
   timeIni = System.nanoTime();
   log.info("Start to establish path: " + System.nanoTime());
   try {
     startLSP(lsp);
   } catch (LSPCreationException e) {
     log.info("Start LSP Error!");
     throw e;
   }
   return lsp.getIdLSP();
 }
  public void waitForLSPaddition(long lspId, long timeWait) {
    Lock lock;
    Condition lspEstablished;
    try {
      lock = lockList.get(lspId);
      if (lock == null) log.info("Lock is NULL!");
      lspEstablished = conditionList.get(lspId);
    } catch (Exception e) {
      return;
    }

    lock.lock();
    try {
      if (established == false) {
        log.info("Waiting " + timeWait + " ms  for LSP " + lspId + " to be established");
        lspEstablished.await(timeWait, TimeUnit.MILLISECONDS);
      } else {
        log.info("Inside waitForLSPaddition lockList.remove");
        // FIXME: Revisar esto
        lockList.remove(lspId);
        conditionList.remove(lspId);
      }
      log.info("LSP " + lspId + " has been established");
    } catch (InterruptedException e) {
      return;
    } finally {
      lock.unlock();
    }
  }
示例#18
0
  /**
   * metoda pobierajaca wszystkie rekordy z BD1.
   *
   * @return
   */
  public ArrayList<StudentFirst> getAllStudentFromDBfirst() {
    logger.info("getAllContactFromDB");
    ResultSet result = null;
    ArrayList<StudentFirst> students = new ArrayList<>();
    try {
      prepStmt = conn.prepareStatement("SELECT * FROM student1");
      result = prepStmt.executeQuery();
      int id, index;
      String name, surname, university, faculty, field;

      for (int i = 0; result.next(); i++) {
        id = result.getInt("stud1_id");
        index = result.getInt("stud1_index");
        name = result.getString("stud1_name");
        surname = result.getString("stud1_lastname");
        university = result.getString("stud1_university");
        faculty = result.getString("stud1_faculty");
        field = result.getString("stud1_field");
        students.add(new StudentFirst(id, index, name, surname, university, faculty, field));
        logger.info(students.get(i).toString());
      }

      if (students.size() == 0) {
        logger.info("Pusta BD?");
      }
      return students;
    } catch (SQLException e1) {
      JOptionPane.showMessageDialog(null, e1);
      e1.printStackTrace();
      return null;
    }
  }
  @Test
  public void test() throws Exception {
    try {
      String queryFileShort =
          queryFile.getPath().substring(PATH_QUERIES.length()).replace(SEPARATOR.charAt(0), '/');
      if (!only.isEmpty()) {
        boolean toRun = TestHelper.isInPrefixList(only, queryFileShort);
        if (!toRun) {
          LOGGER.info(
              "SKIP TEST: \""
                  + queryFile.getPath()
                  + "\" \"only.txt\" not empty and not in \"only.txt\".");
        }
        Assume.assumeTrue(toRun);
      }
      boolean skipped = TestHelper.isInPrefixList(ignore, queryFileShort);
      if (skipped) {
        LOGGER.info("SKIP TEST: \"" + queryFile.getPath() + "\" in \"ignore.txt\".");
      }
      Assume.assumeTrue(!skipped);

      LOGGER.info("RUN TEST: \"" + queryFile.getPath() + "\"");
      parserTestExecutor.testSQLPPParser(queryFile, actualFile, expectedFile);
    } catch (Exception e) {
      if (!(e instanceof AssumptionViolatedException)) {
        LOGGER.severe("Test \"" + queryFile.getPath() + "\" FAILED!");
        throw new Exception("Test \"" + queryFile.getPath() + "\" FAILED!", e);
      } else {
        throw e;
      }
    }
  }
  @Override
  public AbstractFeature build() throws JATEException {
    List<String> contextIds = new ArrayList<>(frequencyCtxBased.getMapCtx2TTF().keySet());
    // start workers
    int cores = Runtime.getRuntime().availableProcessors();
    cores = (int) (cores * properties.getFeatureBuilderMaxCPUsage());
    cores = cores == 0 ? 1 : cores;
    StringBuilder sb = new StringBuilder("Building features using cpu cores=");
    sb.append(cores)
        .append(", total ctx=")
        .append(contextIds.size())
        .append(", max per worker=")
        .append(properties.getFeatureBuilderMaxDocsPerWorker());
    LOG.info(sb.toString());
    CooccurrenceFBWorker worker =
        new CooccurrenceFBWorker(
            contextIds,
            frequencyTermBased,
            minTTF,
            frequencyCtxBased,
            minTCF,
            properties.getFeatureBuilderMaxTermsPerWorker());
    LOG.info("Filtering candidates with min.ttf=" + minTTF + " min.tcf=" + minTCF);
    ForkJoinPool forkJoinPool = new ForkJoinPool(cores);
    Cooccurrence feature = forkJoinPool.invoke(worker);
    sb = new StringBuilder("Complete building features.");
    LOG.info(sb.toString());

    return feature;
  }
示例#21
0
 /**
  * Finally activates a plugin. Called once the plugin's requirements are met (see
  * PluginImpl.checkRequirementsForActivation()).
  *
  * <p>Activation comprises: - install the plugin in the database (includes migrations,
  * post-install event, type introduction) - initialize the plugin - register the plugin's
  * listeners - add the plugin to the pool of activated plugins
  *
  * <p>If this plugin is already activated, nothing is performed and false is returned. Otherwise
  * true is returned.
  *
  * <p>Note: this method is synchronized. While a plugin is activated no other plugin must be
  * activated. Otherwise the "type introduction" mechanism might miss some types. Consider this
  * unsynchronized scenario: plugin B starts running its migrations just in the moment between
  * plugin A's type introduction and listener registration. Plugin A might miss some of the types
  * created by plugin B.
  */
 synchronized boolean activatePlugin(PluginImpl plugin) {
   try {
     // Note: we must not activate a plugin twice.
     // This would happen e.g. if a dependency plugin is redeployed.
     if (isPluginActivated(plugin.getUri())) {
       logger.info("Activation of " + plugin + " ABORTED -- already activated");
       return false;
     }
     //
     logger.info("----- Activating " + plugin + " -----");
     plugin.installPluginInDB();
     plugin.initializePlugin();
     plugin.registerListeners();
     // Note: registering the listeners is deferred until the plugin is installed in the database
     // and the
     // POST_INSTALL_PLUGIN event is delivered (see PluginImpl.installPluginInDB()).
     // Consider the Access Control plugin: it can't set a topic's creator before the "admin" user
     // is created.
     addToActivatedPlugins(plugin);
     logger.info("----- Activation of " + plugin + " complete -----");
     return true;
   } catch (Exception e) {
     throw new RuntimeException("Activation of " + plugin + " failed", e);
   }
 }
  public void add(Topic topic) {
    if (logger.isLoggable(Level.INFO)) {
      logger.info("Adding topic " + topic);
    }

    List<Topic> topics = getTopics();
    if (topics == null) {
      return;
    }
    if (topics.contains(topic)) {
      if (logger.isLoggable(Level.INFO)) {
        logger.info("Topic is already in the list " + topic);
      }
      return;
    }

    // Bad Hack, remove the RPUpdate topic from the list. This one is
    // malformed!
    Iterator<Topic> iter = topics.iterator();
    while (iter.hasNext()) {
      Topic t = iter.next();
      if ("RPUpdate".equals(t.name)) {
        iter.remove();
      }
    }

    topics.add(topic);

    synchronized (lock) {
      logger.fine("Updating topics for add");
      this.engine.updateTopicSet(topics);
    }
  }
示例#23
0
  @PostInit
  public void postInit(FMLPostInitializationEvent event) throws Exception {
    try {

      DispenserActionRegistry.init();

      // Now that all mods have completed their main initialization
      // sequence, scan for other mods we want to
      // use the APIs of.
      ModDetector.beginModDetection();

      // Now, register the stairs and walls because the inclusions have
      // been registered.
      WallStairRegistrationHandler.addWallsAndStairs();

      CoreLoadingPlugin.EVENT_BUS.register(new ArmorProjectionHandler());

      logger.info("Registered " + BlockRegistry.blockcount + " blocks!");
      logger.info("Registered " + ItemRegistry.itemcount + " items!");

      FuelController.registerFuel(ItemRegistry.EndimoniumIngot.itemID, Integer.MAX_VALUE);

    } catch (Exception e) {
      CrashLogger.killWithError(e, "Fatal error during post-initialization");
    }
  }
  public boolean delete(Topic topic) {
    if (logger.isLoggable(Level.INFO)) {
      logger.info("Deleting topic " + topic);
    }

    List<Topic> topics = getTopics();
    if (topics == null) {
      return false;
    }
    // Bad Hack, remove the RPUpdate topic from the list. This one is
    // malformed!
    Iterator<Topic> iter = topics.iterator();
    while (iter.hasNext()) {
      Topic t = iter.next();
      if ("RPUpdate".equals(t.name)) {
        iter.remove();
      }
    }

    topics.remove(topic);

    synchronized (lock) {
      logger.info("Updating topics for delete");
      this.engine.updateTopicSet(topics);
      // let's remove all things related to the topic
      // HACK since it is buggy on the WSN side...
      this.engine
          .getNotificationManager()
          .getSubscriptionManagerEngine()
          .deleteAllForTopic(new QName(topic.ns, topic.name, topic.ns));
    }
    return true;
  }
示例#25
0
 @Test
 public void test3LTSolve() {
   for (int seed = 0; seed < 10; seed++) {
     m = new CPModel();
     s = new CPSolver();
     int k = 2;
     IntegerVariable v0 = makeIntVar("v0", 0, 10);
     IntegerVariable v1 = makeIntVar("v1", 0, 10);
     m.addConstraint(distanceLT(v0, v1, k));
     s.read(m);
     s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
     s.setValIntSelector(new RandomIntValSelector(seed));
     try {
       s.propagate();
     } catch (ContradictionException e) {
       LOGGER.info(e.getMessage()); // To change body of catch statement use File | Settings | File
       // Templates.
     }
     s.solveAll();
     int nbNode = s.getNodeCount();
     LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
     assertEquals(s.getNbSolutions(), 31);
     assertEquals(nbNodeFromRegulatModel(seed), nbNode);
   }
 }
  public void storeComment(CommentDTO comment) {

    Statement stmnt = null;

    try {
      stmnt = connection.createStatement();
      String sqlStr =
          "INSERT INTO TBL_COMMENTS (MVCHAR_ID, MVCHAR_NAME, USERNAME, COMMENT_DATE, COMMENT) VALUES ("
              + comment.getCharacterID()
              + ","
              + "'"
              + comment.getCharacterName()
              + "',"
              + "'"
              + comment.getUser()
              + "',"
              + "'"
              + fmt.format(comment.getCommentDate())
              + "',"
              + "'"
              + comment.getComment()
              + "')";
      logger.info("sql string is " + sqlStr);
      int result = stmnt.executeUpdate(sqlStr);
      logger.info("Statement successfully executed " + result);
      stmnt.close();
    } catch (Exception e) {
      logger.severe("Unable to store comment! ");
      e.printStackTrace();
    }
  }
示例#27
0
  @Test
  public void test1NeqSolve() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      int k = 9, k1 = 7, k2 = 6;
      IntegerVariable v0 = makeIntVar("v0", 0, 10);
      IntegerVariable v1 = makeIntVar("v1", 0, 10);
      IntegerVariable v2 = makeIntVar("v2", 0, 10);
      IntegerVariable v3 = makeIntVar("v3", 0, 10);

      m.addConstraint(distanceNEQ(v0, v1, k));
      m.addConstraint(distanceNEQ(v1, v2, k1));
      m.addConstraint(distanceNEQ(v2, v3, k2));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));
      try {
        s.propagate();
      } catch (ContradictionException e) {
        LOGGER.info(e.getMessage());
      }
      s.solveAll();
      int nbNode = s.getNodeCount();
      LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
      assertEquals(s.getNbSolutions(), 12147);
    }
  }
  public boolean signIn(CloudPlugin plugin, BugCollection bugCollection) throws IOException {
    loadProperties(plugin);

    if (softSignin()) return true;

    if (sessionId == null) sessionId = loadOrCreateSessionId();

    LOGGER.info("Opening browser for session " + sessionId);
    URL u = new URL(host + "/browser-auth/" + sessionId);
    LaunchBrowser.showDocument(u);

    // wait 1 minute for the user to sign in
    for (int i = 0; i < USER_SIGNIN_TIMEOUT_SECS; i++) {
      if (checkAuthorized(getAuthCheckUrl(sessionId))) {
        return true;
      }
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        break;
      }
    }
    LOGGER.info("Sign-in timed out for " + sessionId);
    throw new IOException("Sign-in timed out");
  }
示例#29
0
  /* (non-Javadoc)
   * @see net.sf.thingamablog.transport.PublishTransport#connect()
   */
  public boolean connect() {
    failMsg = "";
    if (isConnected) {
      failMsg = "Already connected";
      return false;
    }

    try {
      JSch jsch = new JSch();
      Session session = jsch.getSession(getUserName(), getAddress(), getPort());

      // password will be given via UserInfo interface.
      UserInfo ui = new MyUserInfo(getPassword());
      session.setUserInfo(ui);

      logger.info("Connecting to SFTP");
      session.connect();
      logger.info("Logged in to SFTP");

      Channel channel = session.openChannel("sftp");
      channel.connect();
      sftp = (ChannelSftp) channel;

      isConnected = true;
      return true;
    } catch (Exception ex) {
      failMsg = "Error logging in to " + getAddress();
      failMsg += "\n" + ex.getMessage();
      logger.log(Level.WARNING, failMsg, ex);
      ex.printStackTrace();
    }

    return false;
  }
  public void execute(TaskListener arg0) throws IOException, InterruptedException {
    if (templates != null && templates.size() > 0) {
      LOGGER.info("AzureTemplateMonitorTask: execute: start , template size " + templates.size());
      for (Map.Entry<String, String> entry : templates.entrySet()) {
        AzureCloud azureCloud = getCloud(entry.getValue());
        AzureSlaveTemplate slaveTemplate = azureCloud.getAzureSlaveTemplate(entry.getKey());

        if (slaveTemplate.getTemplateStatus().equals(Constants.TEMPLATE_STATUS_DISBALED)) {
          try {
            List<String> errors = slaveTemplate.verifyTemplate();

            if (errors.size() == 0) {
              // Template errors are now gone, set template to Active
              slaveTemplate.setTemplateStatus(Constants.TEMPLATE_STATUS_ACTIVE);
              slaveTemplate.setTemplateStatusDetails("");
              // remove from the list
              templates.remove(slaveTemplate.getTemplateName());
            }
          } catch (Exception e) {
            // just ignore
          }
        }
      }
      LOGGER.info("AzureTemplateMonitorTask: execute: end");
    }
  }