/**
  * Updates or adds an agent to the database.
  *
  * @param agent The Agent you wish to modify or add in the database.
  */
 protected void updateAgentInDatabase(AgentImpl agent) {
   EntityManager em = null;
   EntityTransaction tx = null;
   try {
     em = emf.createEntityManager();
     tx = em.getTransaction();
     tx.begin();
     AgentImpl existing = getAgent(agent.getName(), agent.getOrganization(), em);
     if (existing == null) {
       em.persist(agent);
     } else {
       existing.setConfiguration(agent.getConfiguration());
       existing.setLastHeardFrom(agent.getLastHeardFrom());
       existing.setState(agent.getState());
       existing.setSchedulerRoles(agent.getSchedulerRoles());
       existing.setUrl(agent.getUrl());
       em.merge(existing);
     }
     tx.commit();
   } catch (RollbackException e) {
     logger.warn("Unable to commit to DB in updateAgent.");
     throw e;
   } finally {
     if (em != null) em.close();
   }
 }
  /**
   * {@inheritDoc}
   *
   * @see org.opencastproject.capture.admin.api.CaptureAgentStateService#setAgentConfiguration
   */
  public int setAgentConfiguration(String agentName, Properties configuration) {

    AgentImpl agent = getAgent(agentName);
    if (agent != null) {
      logger.debug("Setting Agent {}'s capabilities", agentName);
      agent.setConfiguration(configuration);
      updateAgentInDatabase(agent);
    } else {
      // If the agent doesn't exists, but the name is not null nor empty, create a new one.
      if (StringUtils.isBlank(agentName)) {
        logger.debug("Unable to set agent state, agent name is blank or null.");
        return BAD_PARAMETER;
      }
      logger.debug("Creating Agent {} with state {}.", agentName, UNKNOWN);
      Organization org = securityService.getOrganization();
      AgentImpl a = new AgentImpl(agentName, org.getId(), UNKNOWN, "", configuration);
      updateAgentInDatabase(a);
    }

    return OK;
  }