void _pickInitial() throws MongoException {
    if (_curAddress != null) return;

    // we need to just get a server to query for ismaster
    _pickCurrent();

    try {
      _logger.info("current address beginning of _pickInitial: " + _curAddress);

      DBObject im = isMasterCmd();
      if (_isMaster(im)) return;

      synchronized (_allHosts) {
        Collections.shuffle(_allHosts);
        for (ServerAddress a : _allHosts) {
          if (_curAddress == a) continue;

          _logger.info("remote [" + _curAddress + "] -> [" + a + "]");
          _set(a);

          im = isMasterCmd();
          if (_isMaster(im)) return;

          _logger.severe("switched to: " + a + " but isn't master");
        }

        throw new MongoException("can't find master");
      }
    } catch (Exception e) {
      _logger.log(Level.SEVERE, "can't pick initial master, using random one", e);
    }
  }
Example #2
0
  /** 基类实现消息监听接口,加上打印metaq监控日志的方法 */
  @Override
  public ConsumeConcurrentlyStatus consumeMessage(
      List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    long startTime = System.currentTimeMillis();
    logger.info("receive_message:{}", msgs.toString());
    if (msgs == null || msgs.size() < 1) {
      logger.error("receive empty msg!");
      return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    List<Serializable> msgList = new ArrayList<>();
    for (MessageExt message : msgs) {
      msgList.add(decodeMsg(message));
    }

    final int reconsumeTimes = msgs.get(0).getReconsumeTimes();
    MsgObj msgObj = new MsgObj();
    msgObj.setReconsumeTimes(reconsumeTimes);
    msgObj.setMsgList(msgList);
    msgObj.setContext(context);
    context.setDelayLevelWhenNextConsume(getDelayLevelWhenNextConsume(reconsumeTimes));

    ConsumeConcurrentlyStatus status = doConsumeMessage(msgObj);
    logger.info(
        "ConsumeConcurrentlyStatus:{}|cost:{}", status, System.currentTimeMillis() - startTime);
    return status;
  }
Example #3
0
  private void initLoader() {
    if (loaderStartupDone) return;
    loaderStartupDone = true;

    // Set up base class overrides
    prepareClassOverrides();

    // Set up loader, initialises any reflection methods needed
    if (prepareLoader()) {
      logger.info("LiteLoader " + LOADER_VERSION + " starting up...");
      logger.info(
          String.format("Java reports OS=\"%s\"", System.getProperty("os.name").toLowerCase()));

      // Examines the class path and mods folder and locates loadable mods
      prepareMods();

      // Initialises enumerated mods
      initMods();

      // Initialises the required hooks for loaded mods
      initHooks();

      loaderStartupComplete = true;
    }
  }
  public static void authenticate(String username, String password) {
    Logger.info("Attempting to authenticate with " + username + ":" + password);
    Admin admin = Admin.findByUsername(username);
    if ((admin != null) && (admin.checkPassword(password) == true)) {
      Logger.info("Successfull authentication of " + admin.username);

      /**
       * wanted to put an extra value in session - logged_in_adminid to distinguish an admin, as a
       * user could be logged in and type the route for admin URLs and get into the restricted
       * access areas. By putting a new value in session, it can only be set if an admin is logged
       * in.
       */
      session.put("logged_in_adminid", admin.id);

      /**
       * if login successful, communicate back to AJAX call in adminlogin.js and that will handle
       * the next screen
       */
      JSONObject obj = new JSONObject();
      String value = "correct";
      obj.put("inputdata", value);
      renderJSON(obj);

    } else {
      /**
       * if login unsuccessful, communicate back to AJAX call in adminlogin.js and that will
       * redisplay login.html with error
       */
      Logger.info("Authentication failed");
      JSONObject obj = new JSONObject();
      String value = "Error: Incorrect Email/Password entered.";
      obj.put("inputdata", value);
      renderJSON(obj);
    }
  }
  @Override
  public void processCalculations(final User u, final Entity point, final Value value)
      throws NimbitsException {

    final List<Entity> calculations =
        EntityServiceFactory.getInstance().getEntityByTrigger(u, point, EntityType.calculation);
    for (final Entity entity : calculations) {
      Calculation c = (Calculation) entity;
      try {

        final List<Entity> target =
            EntityServiceFactory.getInstance().getEntityByKey(u, c.getTarget(), EntityType.point);
        if (target.isEmpty()) {
          log.severe("Point target was null " + c.getTarget());
          log.severe(c.getFormula());
          log.severe("trigger: " + c.getTrigger());
          disableCalc(u, c);
        } else {
          log.info("Solving calc" + c.getFormula());
          final Value result = solveEquation(u, c);
          log.info("result" + result);
          ValueServiceFactory.getInstance().recordValue(u, target.get(0), result);
        }
      } catch (NimbitsException e1) {
        LogHelper.logException(this.getClass(), e1);
        disableCalc(u, c);
      }
    }
  }
  /**
   * Persists an SorPerson on update.
   *
   * @param sorPerson the person to update.
   * @return serviceExecutionResult.
   */
  public ServiceExecutionResult<SorPerson> updateSorPerson(final SorPerson sorPerson) {
    final Set validationErrors = this.validator.validate(sorPerson);

    if (!validationErrors.isEmpty()) {
      Iterator iter = validationErrors.iterator();
      while (iter.hasNext()) {
        logger.info("validation errors: " + iter.next());
      }
      // since because of existing design we cannot raise exception, we can only rollback the
      // transaction through code
      // OR-384
      if (TransactionAspectSupport.currentTransactionStatus() != null) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }

      return new GeneralServiceExecutionResult<SorPerson>(validationErrors);
    }

    // do reconciliationCheck to make sure that modifications do not cause person to reconcile to a
    // different person
    if (!this.reconciler.reconcilesToSamePerson(sorPerson)) {
      throw new IllegalStateException();
    }

    // Iterate over any sorRoles setting sorid and source id if not specified by SoR.
    for (final SorRole sorRole : sorPerson.getRoles()) {
      setRoleIdAndSource(sorRole, sorPerson.getSourceSor());
    }

    // Save Sor Person
    final SorPerson savedSorPerson = this.personRepository.saveSorPerson(sorPerson);

    Person person = this.findPersonById(savedSorPerson.getPersonId());

    Assert.notNull(person, "person cannot be null.");

    logger.info(
        "Verifying Number of calculated Roles before the calculate: " + person.getRoles().size());

    // Iterate over sorRoles. SorRoles may be new or updated.
    for (final SorRole savedSorRole : savedSorPerson.getRoles()) {
      logger.info(
          "DefaultPersonService: savedSorPersonRole Found, savedSorRoleID: "
              + savedSorRole.getId());
      logger.info("DefaultPersonService: savedSorPersonRole Found, Role Must be newly added.");
      // let sor role elector decide if this new role can be converted to calculated one
      sorRoleElector.addSorRole(savedSorRole, person);
      logger.info(
          "Verifying Number of calculated Roles after calculate: " + person.getRoles().size());
    }

    for (final IdentifierAssigner ia : this.identifierAssigners) {
      ia.addIdentifierTo(sorPerson, person);
    }

    person = recalculatePersonBiodemInfo(person, savedSorPerson, RecalculationType.UPDATE, false);
    person = this.personRepository.savePerson(person);

    return new GeneralServiceExecutionResult<SorPerson>(savedSorPerson);
  }
Example #7
0
  private void ConnectKnowledgeBaseBtnMouseClicked(
      java.awt.event.MouseEvent evt) { // GEN-FIRST:event_ConnectKnowledgeBaseBtnMouseClicked

    String sPrjFile = ProjectNameTF.getText().trim();
    String sLocationURI = sURI + "Location";

    Collection errors = new ArrayList();
    Date d1 = new Date();
    long l1 = d1.getTime();
    prj = Project.loadProjectFromFile(sPrjFile, errors);
    owlModel = (OWLModel) prj.getKnowledgeBase();

    kb = prj.getKnowledgeBase();
    URI uri = prj.getActiveRootURI();

    Collection colNumberOfInstance = kb.getInstances();
    lNumberOfInstance = colNumberOfInstance.size();

    Date d2 = new Date();
    long l2 = d2.getTime();
    lLoadedTime = (l2 - l1);

    theLogger.info("Connected to MySQL in " + lLoadedTime + " ms");
    theLogger.info("KB has " + lNumberOfInstance + " instances");

    LoggingAreaTA.append("Project has " + lNumberOfInstance + " in total\n");
    LoggingAreaTA.append("Project is loaded in " + lLoadedTime + " ms\n");
  } // GEN-LAST:event_ConnectKnowledgeBaseBtnMouseClicked
  public ServiceExecutionResult<ReconciliationResult> reconcile(
      final ReconciliationCriteria reconciliationCriteria) throws IllegalArgumentException {
    Assert.notNull(reconciliationCriteria, "reconciliationCriteria cannot be null");
    logger.info("reconcile start");
    final Set validationErrors = this.validator.validate(reconciliationCriteria);

    if (!validationErrors.isEmpty()) {
      Iterator iter = validationErrors.iterator();
      while (iter.hasNext()) {
        logger.info("validation errors: " + iter.next());
      }
      logger.info("reconcile start");
      // since because of existing design we cannot raise exception, we can only rollback the
      // transaction through code
      // OR-384
      if (TransactionAspectSupport.currentTransactionStatus() != null) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }

      return new GeneralServiceExecutionResult<ReconciliationResult>(validationErrors);
    }

    final ReconciliationResult result = this.reconciler.reconcile(reconciliationCriteria);
    // (reconciliationCriteria, result);
    return new GeneralServiceExecutionResult<ReconciliationResult>(result);
  }
  @PreAuthorize("hasPermission(#sorRole, 'admin')")
  public ServiceExecutionResult<SorRole> validateAndSaveRoleForSorPerson(
      final SorPerson sorPerson, final SorRole sorRole) {
    logger.info(" validateAndSaveRoleForSorPerson start");
    Assert.notNull(sorPerson, "SorPerson cannot be null.");
    Assert.notNull(sorRole, "SorRole cannot be null.");

    // check if the SoR Role has an ID assigned to it already and assign source sor
    setRoleIdAndSource(sorRole, sorPerson.getSourceSor());

    final Set validationErrors = this.validator.validate(sorRole);

    if (!validationErrors.isEmpty()) {
      // since because of existing design we cannot raise exception, we can only rollback the
      // transaction through code
      // OR-384
      if (TransactionAspectSupport.currentTransactionStatus() != null) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }

      return new GeneralServiceExecutionResult<SorRole>(validationErrors);
    }

    final SorPerson newSorPerson = this.personRepository.saveSorPerson(sorPerson);
    Person person = this.personRepository.findByInternalId(newSorPerson.getPersonId());
    final SorRole newSorRole = newSorPerson.findSorRoleBySorRoleId(sorRole.getSorId());
    // let sor role elector decide if this new role can be converted to calculated one
    sorRoleElector.addSorRole(newSorRole, person);
    person = recalculatePersonBiodemInfo(person, newSorPerson, RecalculationType.UPDATE, false);
    this.personRepository.savePerson(person);
    logger.info("validateAndSaveRoleForSorPerson end");
    return new GeneralServiceExecutionResult<SorRole>(newSorRole);
  }
Example #10
0
  private void doConnect() {
    L.info(
        "Connecting to MQTT broker "
            + mqttc.getServerURI()
            + " with CLIENTID="
            + mqttc.getClientId()
            + " and TOPIC PREFIX="
            + topicPrefix);

    MqttConnectOptions copts = new MqttConnectOptions();
    copts.setWill(topicPrefix + "connected", "0".getBytes(), 1, true);
    copts.setCleanSession(true);
    copts.setUserName("emonpi");
    copts.setPassword("emonpimqtt2016".toCharArray());
    try {
      mqttc.connect(copts);
      sendConnectionState();
      L.info("Successfully connected to broker, subscribing to " + topicPrefix + "(set|get)/#");
      try {
        mqttc.subscribe(topicPrefix + "set/#", 1);
        mqttc.subscribe(topicPrefix + "get/#", 1);
        shouldBeConnected = true;
      } catch (MqttException mqe) {
        L.log(Level.WARNING, "Error subscribing to topic hierarchy, check your configuration", mqe);
        throw mqe;
      }
    } catch (MqttException mqe) {
      L.log(
          Level.WARNING,
          "Error while connecting to MQTT broker, will retry: " + mqe.getMessage(),
          mqe);
      queueConnect(); // Attempt reconnect
    }
  }
Example #11
0
  /**
   * Reads a base class overrride from a resource file
   *
   * @param binaryClassName
   * @param fileName
   */
  private void registerBaseClassOverride(String binaryClassName, String fileName) {
    try {
      Method mDefineClass =
          ClassLoader.class.getDeclaredMethod(
              "defineClass", String.class, byte[].class, int.class, int.class);
      mDefineClass.setAccessible(true);

      InputStream resourceInputStream =
          LiteLoader.class.getResourceAsStream("/classes/" + fileName + ".bin");

      if (resourceInputStream != null) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        for (int readBytes = resourceInputStream.read();
            readBytes >= 0;
            readBytes = resourceInputStream.read()) {
          outputStream.write(readBytes);
        }

        byte[] data = outputStream.toByteArray();

        outputStream.close();
        resourceInputStream.close();

        logger.info("Defining class override for " + binaryClassName);
        mDefineClass.invoke(
            Minecraft.class.getClassLoader(), binaryClassName, data, 0, data.length);
      } else {
        logger.info("Error defining class override for " + binaryClassName + ", file not found");
      }
    } catch (Throwable th) {
      logger.log(Level.WARNING, "Error defining class override for " + binaryClassName, th);
    }
  }
  /**
   * Processes the session initiation {@link SessionIQ} that we were created with, passing its
   * content to the media handler and then sends either a "session-info/ringing" or a "terminate"
   * response.
   *
   * @param sessionInitIQ The {@link SessionIQ} that created the session that we are handling here.
   */
  protected synchronized void processSessionInitiate(SessionIQ sessionInitIQ) {
    // Do initiate the session.
    this.sessionInitIQ = sessionInitIQ;
    this.initiator = true;

    RtpDescriptionPacketExtension description = null;

    for (PacketExtension ext : sessionInitIQ.getExtensions()) {
      if (ext.getElementName().equals(RtpDescriptionPacketExtension.ELEMENT_NAME)) {
        description = (RtpDescriptionPacketExtension) ext;
        break;
      }
    }

    if (description == null) {
      logger.info("No description in incoming session initiate");

      // send an error response;
      String reasonText = "Error: no description";
      SessionIQ errResp =
          GTalkPacketFactory.createSessionTerminate(
              sessionInitIQ.getTo(),
              sessionInitIQ.getFrom(),
              sessionInitIQ.getID(),
              Reason.INCOMPATIBLE_PARAMETERS,
              reasonText);

      setState(CallPeerState.FAILED, reasonText);
      getProtocolProvider().getConnection().sendPacket(errResp);
      return;
    }

    try {
      getMediaHandler().processOffer(description);
    } catch (Exception ex) {
      logger.info("Failed to process an incoming session initiate", ex);

      // send an error response;
      String reasonText = "Error: " + ex.getMessage();
      SessionIQ errResp =
          GTalkPacketFactory.createSessionTerminate(
              sessionInitIQ.getTo(),
              sessionInitIQ.getFrom(),
              sessionInitIQ.getID(),
              Reason.INCOMPATIBLE_PARAMETERS,
              reasonText);

      setState(CallPeerState.FAILED, reasonText);
      getProtocolProvider().getConnection().sendPacket(errResp);
      return;
    }

    // If we do not get the info about the remote peer yet. Get it right
    // now.
    if (this.getDiscoveryInfo() == null) {
      String calleeURI = sessionInitIQ.getFrom();
      retrieveDiscoveryInfo(calleeURI);
    }
  }
Example #13
0
 public static void closeConnection() {
   if (twitter != null) {
     Logger.info("Closing down Twitter stream...");
     twitter.cleanUp();
     if (esClient != null) esClient.close();
   } else {
     Logger.info("No twitter stream found");
   }
 }
Example #14
0
 /* (non-Javadoc)
  * @see com.lexst.thread.VirtualThread#process()
  */
 @Override
 public void process() {
   Logger.info("WorkPool.process, into...");
   while (!isInterrupted()) {
     this.check();
     this.delay(1000);
   }
   Logger.info("WorkPool.process, exit");
 }
Example #15
0
  public void onEnable() {
    // TODO: Place any custom enable code here including the registration of any events

    // Setup Plugin Member Variables
    server = getServer();
    log = server.getLogger();

    commandMap =
        new CommandsManager<Player>() {
          @Override
          public boolean hasPermission(Player player, String perm) {
            // TODO: Implement Permissions
            return true;
          }
        };

    dungeons = new HashMap<String, Dungeon>();
    editSessions = new HashMap<Player, EditSession>();

    PluginManager pm = getServer().getPluginManager();

    try {
      // Register our events
      pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.ENTITY_DEATH, entityListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.ENTITY_COMBUST, entityListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.ENTITY_EXPLODE, entityListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.ENTITY_TARGET, entityListener, Priority.Normal, this);

    } catch (Exception e) {

      log.info("Exception while registering events.");
      log.info(e.getMessage());
    }

    try {

      // Setup PlayerListener class to preprocess command events
      pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, playerListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Priority.Normal, this);

      // Register Commands to the command map
      commandMap.register(LairDungeonCommand.class);

    } catch (Exception e) {

      log.info("Exception Registering Commands: ");
      log.info(e.getMessage());
    }

    // Say Hello
    log.info("Legends.Lair Hello!");
  }
Example #16
0
  // Gets a property.
  static String getStringProperty(String propName) {
    String temp = getConfigValue(propName);
    String result = "";
    if (temp != null) {
      result = temp;
      Logger.info("{DB}-" + propName + ":" + result);
    } else {
      result = properties.getProperty(propName);
      Logger.info("{FILE}-" + propName + ":" + result);
    }

    return result;
  }
Example #17
0
  // Gets a property and converts it into integer.
  static int getIntProperty(String propName, int defaultValue) {
    String temp = getConfigValue(propName);
    int result = defaultValue;
    if (temp != null) {
      result = Integer.parseInt(temp);
      Logger.info("{DB}-" + propName + ":" + result);
    } else {
      result =
          Integer.parseInt(properties.getProperty(propName, Integer.toString(defaultValue)).trim());
      Logger.info("{FILE}-" + propName + ":" + result);
    }

    return result;
  }
  public ServiceExecutionResult<Person> addPerson(
      final ReconciliationCriteria reconciliationCriteria)
      throws ReconciliationException, IllegalArgumentException, SorPersonAlreadyExistsException {
    Assert.notNull(reconciliationCriteria, "reconciliationCriteria cannot be null");
    logger.info("addPerson start");
    if (reconciliationCriteria.getSorPerson().getSorId() != null
        && this.findBySorIdentifierAndSource(
                reconciliationCriteria.getSorPerson().getSourceSor(),
                reconciliationCriteria.getSorPerson().getSorId())
            != null) {
      // throw new IllegalStateException("CANNOT ADD SAME SOR RECORD.");
      throw new SorPersonAlreadyExistsException(
          this.findBySorIdentifierAndSource(
              reconciliationCriteria.getSorPerson().getSourceSor(),
              reconciliationCriteria.getSorPerson().getSorId()));
    }

    final Set validationErrors = this.validator.validate(reconciliationCriteria);

    if (!validationErrors.isEmpty()) {
      Iterator iter = validationErrors.iterator();
      while (iter.hasNext()) {
        logger.info("validation errors: " + iter.next());
      }
      // since because of existing design we cannot raise exception, we can only rollback the
      // transaction through code
      // OR-384
      if (TransactionAspectSupport.currentTransactionStatus() != null) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }

      return new GeneralServiceExecutionResult<Person>(validationErrors);
    }

    final ReconciliationResult result = this.reconciler.reconcile(reconciliationCriteria);

    switch (result.getReconciliationType()) {
      case NONE:
        return new GeneralServiceExecutionResult<Person>(
            saveSorPersonAndConvertToCalculatedPerson(reconciliationCriteria));

      case EXACT:
        return new GeneralServiceExecutionResult<Person>(
            addNewSorPersonAndLinkWithMatchedCalculatedPerson(reconciliationCriteria, result));
    }

    this.criteriaCache.put(reconciliationCriteria, result);
    logger.info("addPerson start");
    throw new ReconciliationException(result);
  }
Example #19
0
 public TweetListener(List<String> terms, Client esClient, String esIndex, String esType) {
   this.terms = terms;
   this.esClient = esClient;
   StringBuilder query = new StringBuilder();
   for (int i = 0; i < terms.size(); i++) {
     if (i > 0) query.append("|");
     // query.append("(").append(Pattern.quote(terms.get(i))).append(")");
     // query.append("(").append(terms.get(i)).append(")");
     query.append(terms.get(i));
   }
   Logger.info("Query match pattern: " + query.toString());
   this.matchPattern = Pattern.compile(query.toString(), Pattern.CASE_INSENSITIVE);
   Logger.info("Query match pattern: " + matchPattern.toString());
 }
  public DBTCPConnector(Mongo m, ServerAddress addr) throws MongoException {
    _mongo = m;
    _portHolder = new DBPortPool.Holder(m._options);
    _checkAddress(addr);

    _createLogger.info(addr.toString());

    if (addr.isPaired()) {
      _allHosts = new ArrayList<ServerAddress>(addr.explode());
      _createLogger.info("switch to paired mode : " + _allHosts + " -> " + _curAddress);
    } else {
      _set(addr);
      _allHosts = null;
    }
  }
Example #21
0
  // Gets a property and converts it into byte.
  static byte getByteProperty(String propName, byte defaultValue) {

    String temp = getConfigValue(propName);
    byte result = defaultValue;
    if (temp != null) {
      result = Byte.parseByte(temp);
      Logger.info("{DB}-" + propName + ":" + result);
    } else {

      result = Byte.parseByte(properties.getProperty(propName, Byte.toString(defaultValue)).trim());
      Logger.info("{FILE}-" + propName + ":" + result);
    }

    return result;
  }
Example #22
0
  private static void startStream(List<String> terms) throws TwitterException {
    if (twitter != null) {
      twitter.cleanUp();
    }
    if (esClient != null) {
      esClient.close();
      esClient = null;
    }

    play.Configuration pconf = Play.application().configuration();
    String elasticSearchCluster = pconf.getString("tweet.elasticsearch.cluster.name");
    if (elasticSearchCluster != null) {
      Logger.info("Configuring ElasticSearch...");
      Settings settings =
          ImmutableSettings.settingsBuilder().put("cluster.name", elasticSearchCluster).build();

      esClient =
          new TransportClient(settings)
              .addTransportAddress(
                  new InetSocketTransportAddress(
                      pconf.getString("tweet.elasticsearch.transport.host"),
                      pconf.getInt("tweet.elasticsearch.transport.port")));
    } else {
      esClient = null;
    }

    twitter4j.conf.Configuration tconf = Application.getTwitterConfiguration();
    TwitterStreamFactory tf = new TwitterStreamFactory(tconf);
    twitter = tf.getInstance();
    StatusListener l =
        new TweetListener(
            terms,
            esClient,
            pconf.getString("tweet.elasticsearch.index"),
            pconf.getString("tweet.elasticsearch.type"));
    twitter.addListener(l);

    String[] tracks = new String[terms.size()];
    StringBuffer termsString = new StringBuffer();
    for (int i = 0; i < terms.size(); i++) {
      tracks[i] = terms.get(i);
      if (i != 0) termsString.append(",");
      termsString.append(terms.get(i));
    }
    FilterQuery q = new FilterQuery().track(tracks);
    twitter.filter(q);
    Logger.info("Starting listening for tweets using terms " + termsString.toString() + "...");
  }
Example #23
0
  /**
   * @param host
   * @param notify
   * @return
   */
  private boolean remove(SiteHost host, boolean notify) {
    Logger.info("WorkPool.remove, work site %s", host);

    boolean success = false;
    this.lockSingle();
    try {
      mapTime.remove(host);
      WorkSite site = mapSite.remove(host);
      if (site != null) {
        for (Naming naming : site.list()) {
          SiteSet set = mapNaming.get(naming);
          if (set != null) {
            set.remove(host);
          }
          if (set == null || set.isEmpty()) {
            mapNaming.remove(naming);
          }
        }
        success = true;

        if (notify) {
          CallPool.getInstance().refreshWorkSite();
        }
      }
    } catch (Throwable exp) {
      Logger.error(exp);
    } finally {
      this.unlockSingle();
    }
    return success;
  }
Example #24
0
 void setConfig(Configuration config) {
   log.debug("config: " + config);
   proxyHost = config.get(PARAM_PROXY_HOST);
   proxyPort = config.getInt(PARAM_PROXY_PORT, DEFAULT_PROXY_PORT);
   if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) {
     String http_proxy = System.getenv("http_proxy");
     if (!StringUtil.isNullString(http_proxy)) {
       try {
         HostPortParser hpp = new HostPortParser(http_proxy);
         proxyHost = hpp.getHost();
         proxyPort = hpp.getPort();
       } catch (HostPortParser.InvalidSpec e) {
         log.warning("Can't parse http_proxy environment var, ignoring: " + http_proxy + ": " + e);
       }
     }
   }
   if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) {
     proxyHost = null;
   } else {
     log.info("Proxying through " + proxyHost + ":" + proxyPort);
   }
   userAgent = config.get(PARAM_USER_AGENT);
   if (StringUtil.isNullString(userAgent)) {
     userAgent = null;
   } else {
     log.debug("Setting User-Agent to " + userAgent);
   }
 }
Example #25
0
 private void handleException(Exception e) {
   if (INTERRUPTED_EXCEPTION_TYPES.contains(e.getClass())) {
     LOG.info("Changes feed was interrupted");
   } else {
     LOG.error("Caught exception while listening to changes feed:", e);
   }
 }
Example #26
0
 protected List<MappingWithDirection> findApplicable(MappingKey key) {
   ArrayList<MappingWithDirection> result = new ArrayList<MappingWithDirection>();
   for (ParsedMapping pm : mappings) {
     if ((pm.mappingCase == null && key.mappingCase == null)
         ^ (pm.mappingCase != null && pm.mappingCase.equals(key.mappingCase))) {
       if (pm.sideA.isAssignableFrom(key.source) && pm.sideB.isAssignableFrom(key.target))
         result.add(new MappingWithDirection(pm, true));
       else if (pm.sideB.isAssignableFrom(key.source) && pm.sideA.isAssignableFrom(key.target))
         result.add(new MappingWithDirection(pm, false));
     }
   }
   if (!result.isEmpty()) {
     Collections.sort(result, new MappingComparator(key.target));
   } else if (automappingEnabled) {
     logger.info(
         "Could not find applicable mappings between {} and {}. A mapping will be created using automapping facility",
         key.source.getName(),
         key.target.getName());
     ParsedMapping pm = new Mapping(key.source, key.target, this).automap().parse();
     logger.debug("Automatically created {}", pm);
     mappings.add(pm);
     result.add(new MappingWithDirection(pm, true));
   } else
     logger.warn(
         "Could not find applicable mappings between {} and {}!",
         key.source.getName(),
         key.target.getName());
   return result;
 }
Example #27
0
  /**
   * Send Conference POST request to API endpoint which is used for allocating new conferences in
   * reservation system.
   *
   * @param ownerEmail email of new conference owner
   * @param mucRoomName full name of MUC room that is hosting the conference.
   *     {room_name}@{muc.server.net}
   * @return <tt>ApiResult</tt> that contains system response. It will contain <tt>Conference</tt>
   *     instance filled with data from the reservation system if everything goes OK.
   * @throws FaultTolerantRESTRequest.RetryExhaustedException When the number of retries to submit
   *     the request for the conference data is reached
   * @throws UnsupportedEncodingException When the room data have the encoding that does not play
   *     with UTF8 standard
   */
  public ApiResult createNewConference(String ownerEmail, String mucRoomName)
      throws FaultTolerantRESTRequest.RetryExhaustedException, UnsupportedEncodingException {
    Conference conference = new Conference(mucRoomName, ownerEmail, new Date());

    HttpPost post = new HttpPost(baseUrl + "/conference");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    Map<String, Object> jsonMap = conference.createJSonMap();

    for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
      nameValuePairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
    }

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF8"));

    logger.info("Sending post: " + jsonMap);

    CreateConferenceResponseParser conferenceResponseParser =
        new CreateConferenceResponseParser(conference);

    FaultTolerantRESTRequest faultTolerantRESTRequest =
        new FaultTolerantRESTRequest(post, conferenceResponseParser, retriesCreate, httpClient);

    return faultTolerantRESTRequest.submit();
  }
Example #28
0
  /**
   * Starts the configuration service
   *
   * @param bundleContext the <tt>BundleContext</tt> as provided by the OSGi framework.
   * @throws Exception if anything goes wrong
   */
  public void start(BundleContext bundleContext) throws Exception {
    FileAccessService fas = ServiceUtils.getService(bundleContext, FileAccessService.class);

    if (fas != null) {
      File usePropFileConfig;
      try {
        usePropFileConfig =
            fas.getPrivatePersistentFile(".usepropfileconfig", FileCategory.PROFILE);
      } catch (Exception ise) {
        // There is somewhat of a chicken-and-egg dependency between
        // FileConfigurationServiceImpl and ConfigurationServiceImpl:
        // FileConfigurationServiceImpl throws IllegalStateException if
        // certain System properties are not set,
        // ConfigurationServiceImpl will make sure that these properties
        // are set but it will do that later.
        // A SecurityException is thrown when the destination
        // is not writable or we do not have access to that folder
        usePropFileConfig = null;
      }

      if (usePropFileConfig != null && usePropFileConfig.exists()) {
        logger.info("Using properties file configuration store.");
        this.cs = LibJitsi.getConfigurationService();
      }
    }

    if (this.cs == null) {
      this.cs = new JdbcConfigService(fas);
    }

    bundleContext.registerService(ConfigurationService.class.getName(), this.cs, null);

    fixPermissions(this.cs);
  }
Example #29
0
  /*
   * return 0 is success, otherwise failure
   */
  public final int runAdminCommandOnRemoteNode(
      Node thisNode, StringBuilder output, List<String> args, List<String> stdinLines)
      throws SSHCommandExecutionException, IllegalArgumentException, UnsupportedOperationException {

    String humanreadable = null;
    try {
      this.node = thisNode;
      dcomInfo = new DcomInfo(node);
      List<String> fullcommand = new ArrayList<String>();
      WindowsRemoteAsadmin asadmin = dcomInfo.getAsadmin();

      if (stdinLines != null && !stdinLines.isEmpty()) setupAuthTokenFile(fullcommand, stdinLines);

      fullcommand.addAll(args);
      humanreadable = dcomInfo.getNadminPath() + " " + commandListToString(fullcommand);

      // This is where the rubber meets the road...
      String out = asadmin.run(fullcommand);
      output.append(out);
      logger.info(Strings.get("remote.command.summary", humanreadable, out));
      return determineStatus(args);
    } catch (WindowsException ex) {
      throw new SSHCommandExecutionException(
          Strings.get("remote.command.error", ex.getMessage(), humanreadable), ex);
    } finally {
      teardownAuthTokenFile();
    }
  }
Example #30
0
  public static Result start() {
    java.util.Map<String, String[]> map = request().body().asFormUrlEncoded();

    List<String> terms = new ArrayList<>(map.size());
    for (int i = 0; i < map.size(); i++) {
      String key = "terms[" + i + "]";
      if (map.containsKey(key)) {
        String[] values = map.get(key);
        if ((values != null) && (values.length >= 1)) {
          terms.add(values[0]);
        }
      }
    }

    StreamConfig config = getConfig();
    config.putTerms(terms);
    config.update();

    StringBuilder sb = new StringBuilder();
    for (String t : terms) {
      sb.append(t);
      sb.append(", ");
    }
    sb.delete(sb.length() - 2, sb.length());

    try {
      startStream(terms);
      flash("success", "Twitter stream started (" + sb.toString() + ")");
    } catch (TwitterException e) {
      Logger.info("Error starting twitter stream", e);
      flash("error", "Error starting Twitter stream" + e.getMessage());
    }
    return redirect(routes.Streams.listAll());
  }