private void createDeployment(SoftwareComponent softwareComponent, String location) {
    Deployment deployment = new Deployment();
    deployment.setLocation(location);
    deployment.setDeployedComponent(softwareComponent);

    deploymentRegistry.persist(deployment);
  }
 private void addDeploymentToEnvironment(
     EnvironmentRegistry environmentRegistry, Environment environment, Deployment deployment) {
   environment.attachDeployment(deployment);
   environmentRegistry.update(environment);
   if (log.isDebugEnabled()) {
     log.debug(
         "Successfully added deployment: "
             + deployment.getLocation()
             + "@"
             + deployment.getDeployedComponent().getCode()
             + " to Environment: "
             + environment.getCode());
   }
 }
  /**
   * This method implements the HTTP <code>GET</code> method of the present deployment carrying
   * entity resource. It facilitates the retrieval of all deployments either attached to the present
   * entity or one of its subentities. It expects the method to be addressed via the following URL
   * pattern <code>/{Entity}/Deployment/all/{code}</code>. <code>{Entity}</code> is the name of the
   * deployment carrying entity class, <code>{code}</code> is the code of the entity.
   *
   * @return a 500 code in case of an internal problem, a 404 code if the deployment carrying entity
   *     resource could not be found, a 200 code otherwise. The body of the response contains the
   *     XML representation of the retrieved entity codes.
   *     <p>The form is
   *     <blockquote>
   *     <list xmlns="http://www.mercatis.com/lighthouse3"> <code>AAA</code>
   *     <location>BBB</location> </list>
   *     </blockquote>
   */
  @GET
  @Path("Deployment/all/{code}")
  @Produces("application/xml")
  public Response findAllDeployments(
      @PathParam("code") String code, @Context HttpServletRequest servletRequest) {
    if (log.isDebugEnabled()) {
      log.debug("Retrieving all deployments at " + getEntityDAO().getManagedType().getSimpleName());
    }

    List<Deployment> matches = new LinkedList<Deployment>();

    try {
      Entity entity = getEntityDAO().findByCode(code);
      if (entity == null) {
        log.error(
            "Could not find "
                + getEntityDAO().getManagedType().getSimpleName()
                + " with code"
                + code);
        return Response.status(Status.NOT_FOUND)
            .entity("Could not find resource with code " + code)
            .build();
      }
      if (overridableDenyAccess(servletRequest.getRemoteUser(), getContextRole(CtxOp.FIND), entity))
        return Response.status(Status.UNAUTHORIZED).build();

      for (Deployment d : entity.getAllDeployments()) {
        StringBuilder context =
            formatContext(
                new StringBuilder("/Deployment/Deployment"),
                d.getLocation(),
                d.getDeployedComponent().getCode());
        if (LighthouseAuthorizator.allowAccess(
            getServiceContainer(), servletRequest.getRemoteUser(), "viewDeployment", context))
          matches.add(d);
      }
    } catch (PersistenceException exception) {
      log.error(
          "Persistence exception caught while retrieving deployments for "
              + getEntityDAO().getManagedType().getSimpleName(),
          exception);

      return Response.status(Status.INTERNAL_SERVER_ERROR).entity(exception.toString()).build();
    }

    return Response.status(Status.OK).entity(createXmlListOfDeploymentReferences(matches)).build();
  }
  /**
   * Via this method, event filters are registered with the event logger service for live
   * notification about events of interest.
   *
   * @param filter the filter to register
   */
  public synchronized void registerFilterForLiveEvents(EventFilter filter) {
    if (log.isDebugEnabled())
      log.debug("Registering event filter for live events: " + filter.getUuid());

    // hibernate proxy prefetch workaround
    if (filter.getTemplate().getContext() != null) {
      if (Ranger.isEnumerationRange(filter.getTemplate().getContext())) {
        for (Deployment d :
            Ranger.castToEnumerationRange(filter.getTemplate().getContext()).getEnumeration()) {
          d.getDeployedComponent().getCode();
        }
      } else {
        filter.getTemplate().getContext().getDeployedComponent().getCode();
      }
    }
    this.eventFiltersByUuid.put(filter.getUuid(), filter);

    if (log.isDebugEnabled()) log.debug("Event filter for live events registered.");
  }
  /**
   * Via this method, event filters are registered with the event logger service for live
   * notification about events of interest. Before this happens though, the template in the filter
   * is used to query the event registry. Matching events in this registry are sent to the client
   * first before live event notification is established via <code>doRegisterEventFilter()</code>.
   *
   * @param filter the event filter to register
   */
  public void registerEventFilter(EventFilter filter, int limit) {
    if (log.isDebugEnabled())
      log.debug("Passing event filter on to registration: " + filter.toString());

    // hibernate proxy prefetch workaround
    if (filter.getTemplate().getContext() != null) {
      if (Ranger.isEnumerationRange(filter.getTemplate().getContext())) {
        for (Deployment d :
            Ranger.castToEnumerationRange(filter.getTemplate().getContext()).getEnumeration()) {
          d.getDeployedComponent().getCode();
        }
      } else {
        filter.getTemplate().getContext().getDeployedComponent().getCode();
      }
    }
    EventFilterRegistrationHandler eventFilterRegistrationHandler =
        this.createEventFilterRegistrationHandler(filter, limit);

    this.eventFilterRegistrationThreadPool.execute(eventFilterRegistrationHandler);
  }
  /**
   * Given a list of deployments, this method creates an XML list of references to those
   * deployments.
   *
   * <p>The form is
   *
   * <blockquote>
   *
   * <list xmlns="http://www.mercatis.com/lighthouse3"> <code>AAA</code> <location>BBB</location>
   * </list>
   *
   * </blockquote>
   *
   * @param entities the list of deployments for which to create the list
   * @return the XML list of references
   */
  protected String createXmlListOfDeploymentReferences(List<Deployment> deployments) {
    StringWriter result = new StringWriter();
    XmlWriter xml = new XmlEncXmlWriter(result);

    try {
      xml.writeEntity("list");
      xml.writeAttribute("xmlns", XmlMuncher.MERCATIS_NS);

      for (Deployment deployment : deployments) {
        xml.writeEntity("entry");
        xml.writeEntityWithText("code", deployment.getDeployedComponent().getCode());
        xml.writeEntityWithText("location", deployment.getLocation());
        xml.endEntity();
      }

      xml.endEntity();
    } catch (IOException e) {
      throw new ConflictException("Error creating result list");
    }

    return result.toString();
  }
  private void createContextForEvent(String eventXml) {
    if (log.isDebugEnabled()) {
      log.debug("Starting to create context for event: " + eventXml);
    }
    XmlMuncher xmlDocument = new XmlMuncher(eventXml);

    String deploymentLocation = xmlDocument.readValueFromXml("/*/:context/:deploymentLocation");
    String deployedComponentCode =
        xmlDocument.readValueFromXml("/*/:context/:deployedComponentCode");

    if (log.isDebugEnabled()) {
      log.debug("Create if missing - softwareComponent: " + deployedComponentCode);
    }
    SoftwareComponent softwareComponent =
        softwareComponentRegistry.findByCode(deployedComponentCode);
    if (softwareComponent == null) {
      createSoftwareComponent(deployedComponentCode);
      softwareComponent = softwareComponentRegistry.findByCode(deployedComponentCode);
      if (log.isDebugEnabled()) {
        log.debug(
            "Successfully created and persisted SoftwareComponent: " + softwareComponent.getCode());
      }
    } else {
      if (log.isDebugEnabled()) {
        log.debug("SoftwareComponent: " + deployedComponentCode + " already exists.");
      }
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "Create if missing - deployment: " + deployedComponentCode + " @ " + deploymentLocation);
    }
    Deployment deployment =
        deploymentRegistry.findByComponentCodeAndLocation(
            deployedComponentCode, deploymentLocation);
    if (deployment == null) {
      createDeployment(softwareComponent, deploymentLocation);
      deployment =
          deploymentRegistry.findByComponentAndLocation(softwareComponent, deploymentLocation);
      if (log.isDebugEnabled()) {
        log.debug(
            "Successfully created and persisted Deployment: "
                + deployment.getLocation()
                + "@"
                + deployment.getDeployedComponent().getCode());
      }
    } else {
      if (log.isDebugEnabled()) {
        log.debug(
            "Deployment: "
                + deployedComponentCode
                + " @ "
                + deploymentLocation
                + " already exists.");
      }
    }

    if (log.isDebugEnabled()) {
      log.debug("Create if missing - environment: " + autoDeployEnvironmentName);
    }
    EnvironmentRegistry environmentRegistry =
        EventLoggerServiceContainer.getServiceContainer().getDAO(EnvironmentRegistry.class);
    Environment environment = environmentRegistry.findByCode(autoDeployEnvironmentName);
    if (environment == null) {
      if (log.isDebugEnabled()) {
        log.debug("Environment " + autoDeployEnvironmentName + " missing, creating it....");
      }
      createEnvironment(environmentRegistry, autoDeployEnvironmentName);
      environment = environmentRegistry.findByCode(autoDeployEnvironmentName);
    } else {
      if (log.isDebugEnabled()) {
        log.debug("Environment: " + autoDeployEnvironmentName + " already exists.");
      }
    }

    if (!environment.hasAttachedDeployment(deployment)) {
      if (log.isDebugEnabled()) {
        log.debug(
            "Attaching Deployment: "
                + deployedComponentCode
                + " @ "
                + deploymentLocation
                + " to Environment: "
                + autoDeployEnvironmentName);
      }
      addDeploymentToEnvironment(environmentRegistry, environment, deployment);
    }

    if (log.isDebugEnabled()) {
      log.debug("Successfully created context for event: " + eventXml);
    }
  }
 private String deploymentToString(Deployment d) {
   return d.getDeployedComponent().getCode() + " @ " + d.getLocation();
 }