void loadFromXml(Element rootElement) {
   // Parse XML file
   if (StringUtils.equals(rootElement.getLocalName(), "row")) {
     name = rootElement.getAttribute("ows_LinkFilename");
     url = rootElement.getAttribute("ows_FileRef");
     if (StringUtils.isNotBlank(rootElement.getAttribute("ows_ID"))) {
       id = Integer.valueOf(rootElement.getAttribute("ows_ID"));
     }
     if (StringUtils.isNotBlank(rootElement.getAttribute("ows__Level"))) {
       level = Integer.valueOf(rootElement.getAttribute("ows__Level"));
     }
     if (StringUtils.isNotBlank(rootElement.getAttribute("ows_Created_x0020_Date"))) {
       String[] strArray = rootElement.getAttribute("ows_Created_x0020_Date").split(";#");
       if (strArray.length > 1) {
         Calendar calendar = DatatypeConverter.parseDateTime(strArray[1]);
         created = calendar.getTime();
       }
     }
     if (StringUtils.isNotBlank(rootElement.getAttribute("ows_Modified"))) {
       String[] strArray = rootElement.getAttribute("ows_Modified").split(";#");
       if (strArray.length > 1) {
         Calendar calendar = DatatypeConverter.parseDateTime(strArray[1]);
         modified = calendar.getTime();
       }
     }
   }
 }
  /**
   * Import users
   *
   * @param nodes list of users nodes (wrapper node, thus only one)
   * @return
   */
  private Boolean processUsers(NodeList nodes) {
    NodeList users = nodes.item(0).getChildNodes();

    for (int i = 0; i < users.getLength(); i++) {
      if (users.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element userNode = (Element) users.item(i);

        User user = new User();

        user.setIduser(Integer.parseInt(getTagValue("iduser", userNode)));
        user.setForename(getTagValue("forename", userNode));
        user.setSurname(getTagValue("surname", userNode));
        user.setPermitNumber(getTagValue("permitNumber", userNode));
        user.setAddress(getTagValue("address", userNode));
        user.setEmail(getTagValue("email", userNode));
        user.setRegistered(
            DatatypeConverter.parseDateTime(getTagValue("registered", userNode)).getTime());
        user.setExpire(DatatypeConverter.parseDateTime(getTagValue("expire", userNode)).getTime());
        user.setPassword(getTagValue("password", userNode));
        user.setLevel(getTagValue("level", userNode));

        try {
          userMgr.Save(user);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
Example #3
0
  // parses a datetime string that adhears to the given pattern and returns a java.util.Date object
  public static java.util.Calendar parse(String input, String pattern)
      throws IllegalArgumentException {
    if (pattern == null) pattern = DEFAULT_DATETIME_PATTERN;

    java.util.Calendar output = null;

    if (input != null) {
      if (pattern.equals("datetime")) {
        output = javax.xml.bind.DatatypeConverter.parseDateTime(input);
      } else if (pattern.equals("date")) {
        output = javax.xml.bind.DatatypeConverter.parseDate(input);
      } else if (pattern.equals("time")) {
        output = javax.xml.bind.DatatypeConverter.parseTime(input);
      } else if (pattern.equals("milliseconds")) {
        output = java.util.Calendar.getInstance();
        output.setTimeInMillis(Long.parseLong(input));
      } else {
        java.text.DateFormat formatter = new java.text.SimpleDateFormat(pattern);
        formatter.setLenient(false);
        output = java.util.Calendar.getInstance();
        try {
          output.setTime(formatter.parse(input));
        } catch (java.text.ParseException ex) {
          throw new IllegalArgumentException(tundra.exception.message(ex));
        }
      }
    }

    return output;
  }
 @Override
 protected Object parseDate(String value, boolean richDate) {
   return (richDate
       ? new TimestampWritable(
           new Timestamp(DatatypeConverter.parseDateTime(value).getTimeInMillis()))
       : parseString(value));
 }
  /**
   * Import book exemplars
   *
   * @param nodes
   * @return
   */
  private Boolean processExemplars(NodeList nodes) {
    NodeList exemplars = nodes.item(0).getChildNodes();

    for (int i = 0; i < exemplars.getLength(); i++) {
      if (exemplars.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element exemplarNode = (Element) exemplars.item(i);

        Exemplar exemplar = new Exemplar();

        exemplar.setIdexemplar(Integer.parseInt(getTagValue("idexemplar", exemplarNode)));
        exemplar.setAquired(
            DatatypeConverter.parseDateTime(getTagValue("aquired", exemplarNode)).getTime());
        exemplar.setState(Integer.parseInt(getTagValue("state", exemplarNode)));

        Book book = bookMgr.findByIdbook(Integer.parseInt(getTagValue("book", exemplarNode)));
        if (book == null) {
          continue;
        }

        exemplar.setBook(book);

        try {
          exemplarMgr.save(exemplar);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import books
   *
   * @param nodes
   * @return
   */
  private Boolean processBooks(NodeList nodes) {
    NodeList books = nodes.item(0).getChildNodes();

    for (int i = 0; i < books.getLength(); i++) {
      if (books.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element bookNode = (Element) books.item(i);

        Book book = new Book();

        book.setIdbook(Integer.parseInt(getTagValue("idbook", bookNode)));
        book.setCode(getTagValue("code", bookNode));
        book.setEdition(Integer.parseInt(getTagValue("edition", bookNode)));
        book.setPages(Integer.parseInt(getTagValue("pages", bookNode)));
        book.setPlace(getTagValue("place", bookNode));
        book.setYear(DatatypeConverter.parseDateTime(getTagValue("year", bookNode)).getTime());
        book.setType(getTagValue("type", bookNode));
        book.setName(getTagValue("name", bookNode));

        // find and set publisher
        Publisher publisher =
            publisherMgr.findByIdpublisher(Integer.parseInt(getTagValue("publisher", bookNode)));
        if (publisher == null) {
          continue;
        }

        book.setPublisher(publisher);

        // find and set genre
        Genre genre = genreMgr.findByIdgenre(Integer.parseInt(getTagValue("genre", bookNode)));
        if (genre == null) {
          continue;
        }

        book.setGenre(genre);

        // setup book authors
        List<String> authors = getTagsValues("authorCollection", bookNode);

        if (book.getAuthorCollection() == null) {
          book.setAuthorCollection(new ArrayList<Author>());
        }

        for (String authorId : authors) {
          Author author = authorMgr.findByIdauthor(Integer.parseInt(authorId));
          if (author != null) {
            //						book.getAuthorCollection().add(author);
            author.getBooksCollection().add(book);
            authorMgr.save(author);
          }
        }

        try {
          bookMgr.save(book);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import borrows
   *
   * @param nodes
   * @return
   */
  public Boolean processBorrows(NodeList nodes) {
    NodeList borrows = nodes.item(0).getChildNodes();

    for (int i = 0; i < borrows.getLength(); i++) {
      if (borrows.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element borrowNode = (Element) borrows.item(i);

        Borrow borrow = new Borrow();

        borrow.setIdborrow(Integer.parseInt(getTagValue("idborrow", borrowNode)));
        borrow.setProlongations(Integer.parseInt(getTagValue("prolongations", borrowNode)));
        borrow.setBorrowed(
            DatatypeConverter.parseDateTime(getTagValue("borrowed", borrowNode)).getTime());

        // set returned date (can be null)
        try {
          if (getTagValue("returned", borrowNode) != null) {
            borrow.setReturned(
                DatatypeConverter.parseDateTime(getTagValue("returned", borrowNode)).getTime());
          }
        } catch (NullPointerException e) {
        }

        User user = userMgr.findByIduser(Integer.parseInt(getTagValue("user", borrowNode)));
        if (user == null) {
          continue;
        }

        borrow.setUser(user);

        Exemplar exemplar =
            exemplarMgr.findByIdexemplar(Integer.parseInt(getTagValue("exemplar", borrowNode)));
        if (exemplar == null) {
          continue;
        }

        borrow.setExemplar(exemplar);

        try {
          borrowMgr.Save(borrow);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
Example #8
0
  private List<Job> getJobs() {
    List<Job> jobs = new ArrayList();
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    try {
      WebResource service = client.resource(getBaseURI());
      String result = service.path("jobs").accept(MediaType.APPLICATION_JSON).get(String.class);

      if (result != null) {
        JSONObject jsonRes = new JSONObject(result);

        JSONArray jobsArry = jsonRes.getJSONArray("jobs");
        if (jobsArry.length() > 0) {
          for (int i = 0; i < jobsArry.length(); i++) {
            JSONObject jobsObj = jobsArry.getJSONObject(i);
            Job job = new Job();
            job.setTitle(jobsObj.getString("title"));
            job.setUrl(jobsObj.getString("angellist_url"));

            // Created date
            Calendar dtCal = DatatypeConverter.parseDateTime(jobsObj.getString("created_at"));
            job.setCreated(dtCal.getTime());

            // Startup name
            if (!jobsObj.isNull("startup")) {
              JSONObject startup = jobsObj.getJSONObject("startup");
              if (!startup.isNull("name")) job.setCreatorName(startup.getString("name"));
              if (!startup.isNull("logo_url")) job.setCreatorLogo(startup.getString("logo_url"));
              if (!startup.isNull("thumb_url"))
                job.setCreatorThumbnail(startup.getString("thumb_url"));
              if (!startup.isNull("product_desc")) job.setDesc(startup.getString("product_desc"));
            }

            // add skills
            if (!jobsObj.isNull("tags")) {
              JSONArray tagsArry = jobsObj.getJSONArray("tags");
              if (tagsArry.length() > 0) {
                List<Skill> skills = new ArrayList();
                for (int j = 0; j < tagsArry.length(); j++) {
                  JSONObject tag = tagsArry.getJSONObject(j);
                  String tagType = tag.getString("tag_type");
                  if (tagType.equalsIgnoreCase("SkillTag")) {
                    Skill skill = new Skill(tag.getString("display_name"));
                    skills.add(skill);
                  }
                }
                job.setSkills(skills);
              }
            }
            jobs.add(job);
          }
        }
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return jobs;
  }
  @Override
  public long extractIfmapMetadataTimestamp(Document document) {
    LOGGER.trace("extracting timestamp from XML");

    Element root = document.getDocumentElement();

    String time = null;
    try {
      time = root.getAttribute("ifmap-timestamp");
      Calendar cal = DatatypeConverter.parseDateTime(time);
      long unixTime = cal.getTime().getTime();
      LOGGER.trace("found timestamp '" + unixTime + "'");
      return unixTime;
    } catch (IllegalArgumentException e) {
      LOGGER.error(
          "could not parse timestamp '"
              + time
              + "' in "
              + document.getLocalName()
              + "setting current local time as timestamp");
      return System.currentTimeMillis();
    }
  }
Example #10
0
  /**
   * Import bookings
   *
   * @param nodes
   * @return
   */
  private Boolean processBookings(NodeList nodes) {
    NodeList bookings = nodes.item(0).getChildNodes();

    for (int i = 0; i < bookings.getLength(); i++) {
      if (bookings.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element bookingNode = (Element) bookings.item(i);

        Booking booking = new Booking();

        booking.setIdbooking(Integer.parseInt(getTagValue("idbooking", bookingNode)));
        booking.setState(Integer.parseInt(getTagValue("state", bookingNode)));
        booking.setDate(
            DatatypeConverter.parseDateTime(getTagValue("date", bookingNode)).getTime());

        Book book = bookMgr.findByIdbook(Integer.parseInt(getTagValue("book", bookingNode)));
        if (book == null) {
          continue;
        }

        booking.setBook(book);

        User user = userMgr.findByIduser(Integer.parseInt(getTagValue("user", bookingNode)));
        if (user == null) {
          continue;
        }

        booking.setUser(user);

        try {
          bookingMgr.Save(booking);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
Example #11
0
  public static SyslogMessage parseMessage(byte[] bytes) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    byteBuffer.put(bytes);
    byteBuffer.rewind();

    Character charFound = (char) byteBuffer.get();

    SyslogFacility foundFacility = null;
    SyslogSeverity foundSeverity = null;

    while (charFound != '<') {
      // Ignore noise in beginning of message.
      charFound = (char) byteBuffer.get();
    }
    char priChar = 0;
    if (charFound == '<') {
      int facility = 0;

      while (Character.isDigit(priChar = (char) (byteBuffer.get() & 0xff))) {
        facility *= 10;
        facility += Character.digit(priChar, 10);
      }
      foundFacility = SyslogFacility.values()[facility >> 3];
      foundSeverity = SyslogSeverity.values()[facility & 0x07];
    }

    if (priChar != '>') {
      // Invalid character - this is not a well defined syslog message.
      LOG.error("Invalid syslog message, missing a > in the Facility/Priority part");
    }

    SyslogMessage syslogMessage = new SyslogMessage();
    boolean isRfc5424 = false;
    // Read next character
    charFound = (char) byteBuffer.get();
    // If next character is a 1, we have probably found an rfc 5424 message
    // message
    if (charFound == '1') {
      syslogMessage = new Rfc5424SyslogMessage();
      isRfc5424 = true;
    } else {
      // go back one to parse the rfc3164 date
      byteBuffer.position(byteBuffer.position() - 1);
    }

    syslogMessage.setFacility(foundFacility);
    syslogMessage.setSeverity(foundSeverity);

    if (!isRfc5424) {
      // Parse rfc 3164 date
      syslogMessage.setTimestamp(parseRfc3164Date(byteBuffer));
    } else {

      charFound = (char) byteBuffer.get();
      if (charFound != ' ') {
        LOG.error("Invalid syslog message, missing a mandatory space after version");
      }

      // This should be the timestamp
      StringBuilder date = new StringBuilder();
      while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {
        date.append(charFound);
      }

      syslogMessage.setTimestamp(DatatypeConverter.parseDateTime(date.toString()));
    }

    // The host is the char sequence until the next ' '

    StringBuilder host = new StringBuilder();
    while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {
      host.append(charFound);
    }

    syslogMessage.setHostname(host.toString());

    if (isRfc5424) {
      Rfc5424SyslogMessage rfc5424SyslogMessage = (Rfc5424SyslogMessage) syslogMessage;
      StringBuilder appName = new StringBuilder();
      while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {
        appName.append(charFound);
      }
      rfc5424SyslogMessage.setAppName(appName.toString());

      StringBuilder procId = new StringBuilder();
      while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {
        procId.append(charFound);
      }
      rfc5424SyslogMessage.setProcId(procId.toString());

      StringBuilder msgId = new StringBuilder();
      while ((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') {
        msgId.append(charFound);
      }
      rfc5424SyslogMessage.setMsgId(msgId.toString());

      StringBuilder structuredData = new StringBuilder();
      boolean inblock = false;
      while (((charFound = (char) (byteBuffer.get() & 0xff)) != ' ') || inblock) {
        if (charFound == '[') {
          inblock = true;
        }
        if (charFound == ']') {
          inblock = false;
        }
        structuredData.append(charFound);
      }
      rfc5424SyslogMessage.setStructuredData(structuredData.toString());
    }

    StringBuilder msg = new StringBuilder();
    while (byteBuffer.hasRemaining()) {
      charFound = (char) (byteBuffer.get() & 0xff);
      msg.append(charFound);
    }

    syslogMessage.setLogMessage(msg.toString());
    LOG.trace("Syslog message : {}", syslogMessage.toString());

    return syslogMessage;
  }
  /**
   * Parses the SecurityToken by wrapping within an AssertionWrapper.
   *
   * @param securityToken SecurityToken
   */
  private void parseToken(SecurityToken securityToken) {
    XMLStreamReader xmlStreamReader = StaxUtils.createXMLStreamReader(securityToken.getToken());

    try {
      AttrStatement attributeStatement = null;
      AuthenticationStatement authenticationStatement = null;
      Attr attribute = null;
      int attrs = 0;
      while (xmlStreamReader.hasNext()) {
        int event = xmlStreamReader.next();
        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            {
              String localName = xmlStreamReader.getLocalName();
              switch (localName) {
                case NameID.DEFAULT_ELEMENT_LOCAL_NAME:
                  name = xmlStreamReader.getElementText();
                  for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {
                    if (xmlStreamReader
                        .getAttributeLocalName(i)
                        .equals(NameID.FORMAT_ATTRIB_NAME)) {
                      nameIDFormat = xmlStreamReader.getAttributeValue(i);
                      break;
                    }
                  }
                  break;
                case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  attributeStatement = new AttrStatement();
                  attributeStatements.add(attributeStatement);
                  break;
                case AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  authenticationStatement = new AuthenticationStatement();
                  authenticationStatements.add(authenticationStatement);
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME.equals(name)) {
                      authenticationStatement.setAuthnInstant(DateTime.parse(value));
                    }
                  }
                  break;
                case AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME:
                  if (authenticationStatement != null) {
                    String classValue = xmlStreamReader.getText();
                    classValue = classValue.trim();
                    AuthenticationContextClassRef authenticationContextClassRef =
                        new AuthenticationContextClassRef();
                    authenticationContextClassRef.setAuthnContextClassRef(classValue);
                    AuthenticationContext authenticationContext = new AuthenticationContext();
                    authenticationContext.setAuthnContextClassRef(authenticationContextClassRef);
                    authenticationStatement.setAuthnContext(authenticationContext);
                  }
                  break;
                case Attribute.DEFAULT_ELEMENT_LOCAL_NAME:
                  attribute = new Attr();
                  if (attributeStatement != null) {
                    attributeStatement.addAttribute(attribute);
                  }
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (Attribute.NAME_ATTTRIB_NAME.equals(name)) {
                      attribute.setName(value);
                    } else if (Attribute.NAME_FORMAT_ATTRIB_NAME.equals(name)) {
                      attribute.setNameFormat(value);
                    }
                  }
                  break;
                case AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME:
                  XSString xsString = new XMLString();
                  xsString.setValue(xmlStreamReader.getElementText());
                  if (attribute != null) {
                    attribute.addAttributeValue(xsString);
                  }
                  break;
                case Issuer.DEFAULT_ELEMENT_LOCAL_NAME:
                  issuer = xmlStreamReader.getElementText();
                  break;
                case Conditions.DEFAULT_ELEMENT_LOCAL_NAME:
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (Conditions.NOT_BEFORE_ATTRIB_NAME.equals(name)) {
                      notBefore = DatatypeConverter.parseDateTime(value).getTime();
                    } else if (Conditions.NOT_ON_OR_AFTER_ATTRIB_NAME.equals(name)) {
                      notOnOrAfter = DatatypeConverter.parseDateTime(value).getTime();
                    }
                  }
                  break;
              }
              break;
            }
          case XMLStreamConstants.END_ELEMENT:
            {
              String localName = xmlStreamReader.getLocalName();
              switch (localName) {
                case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  attributeStatement = null;
                  break;
                case Attribute.DEFAULT_ELEMENT_LOCAL_NAME:
                  attribute = null;
                  break;
              }
              break;
            }
        }
      }
    } catch (XMLStreamException e) {
      LOGGER.error("Unable to parse security token.", e);
    } finally {
      try {
        xmlStreamReader.close();
      } catch (XMLStreamException ignore) {
        // ignore
      }
    }
  }
Example #13
0
 protected Object read(String in) {
   return DatatypeConverter.parseDateTime(in);
 }
Example #14
0
  @Override
  public Metacard transform(InputStream input, String uri)
      throws IOException, CatalogTransformerException {
    if (input == null) {
      throw new CatalogTransformerException("Cannot transform null input.");
    }

    MetacardImpl metacard = new MetacardImpl(BasicTypes.BASIC_METACARD);

    Metadata metadata = new Metadata();
    ContentHandler handler = new BodyContentHandler();
    AutoDetectParser parser = new AutoDetectParser();

    try {
      parser.parse(input, handler, metadata);
      String title = metadata.get(TikaCoreProperties.TITLE);
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Title: " + title);
        LOGGER.debug("Creator: " + metadata.get(TikaCoreProperties.CREATOR));
        LOGGER.debug("Author: " + metadata.get(Metadata.AUTHOR));
        LOGGER.debug("Creation Date: " + metadata.get(TikaCoreProperties.CREATED));
        LOGGER.debug("Modified Date: " + metadata.get(TikaCoreProperties.MODIFIED));
        LOGGER.debug("Content Type: " + metadata.get(Metadata.CONTENT_TYPE));
        // LOGGER.debug("content: " + handler.toString());
        // int count = 1;
        // for (String stringMetadata : metadata.names())
        // {
        // LOGGER.debug("Metadata " + count + " ----> name : "
        // + stringMetadata + "&nbsp; value : " + metadata.get(stringMetadata));
        // count++;
        // }
      }

      // mc.setMetadata(convertNodeToString(getDocument(jaxbDoc)));
      if (StringUtils.isEmpty(title)) {
        title = "<No title provided>";
      }
      metacard.setTitle(title);

      Date date =
          javax.xml.bind.DatatypeConverter.parseDateTime(metadata.get(TikaCoreProperties.CREATED))
              .getTime();
      metacard.setCreatedDate(date);

      date =
          javax.xml.bind.DatatypeConverter.parseDateTime(metadata.get(TikaCoreProperties.MODIFIED))
              .getTime();
      metacard.setModifiedDate(date);

      // metacard.setExpirationDate(getExpirationDate(resource));
      // metacard.setEffectiveDate(getEffectiveDate(resource));
      // metacard.setLocation(getLocation(resource));
      // metacard.setSourceId(getSourceId());
      // metacard.setResourceSize(getResourceSize(resource));
      if (uri != null) {
        metacard.setResourceURI(URI.create(uri));
      } else {
        metacard.setResourceURI(null);
      }
    } catch (SAXException e) {
      LOGGER.warn(e);
      throw new CatalogTransformerException(e);
    } catch (TikaException e) {
      LOGGER.warn(e);
      throw new CatalogTransformerException(e);
    }

    return metacard;
  }
 private AbstractMonitorEvent toAlienEvent(Event cloudifyEvent) {
   AbstractMonitorEvent alienEvent;
   switch (cloudifyEvent.getEventType()) {
     case EventType.WORKFLOW_SUCCEEDED:
       PaaSDeploymentStatusMonitorEvent succeededStatusEvent =
           new PaaSDeploymentStatusMonitorEvent();
       if (Workflow.INSTALL.equals(cloudifyEvent.getContext().getWorkflowId())) {
         succeededStatusEvent.setDeploymentStatus(DeploymentStatus.DEPLOYED);
       } else if (Workflow.DELETE_DEPLOYMENT_ENVIRONMENT.equals(
           cloudifyEvent.getContext().getWorkflowId())) {
         succeededStatusEvent.setDeploymentStatus(DeploymentStatus.UNDEPLOYED);
       } else {
         return null;
       }
       alienEvent = succeededStatusEvent;
       break;
     case EventType.WORKFLOW_FAILED:
       PaaSDeploymentStatusMonitorEvent failedStatusEvent = new PaaSDeploymentStatusMonitorEvent();
       failedStatusEvent.setDeploymentStatus(DeploymentStatus.FAILURE);
       alienEvent = failedStatusEvent;
       break;
     case EventType.TASK_SUCCEEDED:
       if (Workflow.DELETE_DEPLOYMENT_ENVIRONMENT.equals(
               cloudifyEvent.getContext().getWorkflowId())
           && "riemann_controller.tasks.delete".equals(cloudifyEvent.getContext().getTaskName())) {
         PaaSDeploymentStatusMonitorEvent undeployedEvent = new PaaSDeploymentStatusMonitorEvent();
         undeployedEvent.setDeploymentStatus(DeploymentStatus.UNDEPLOYED);
         alienEvent = undeployedEvent;
       } else {
         String newInstanceState =
             CloudifyLifeCycle.getSucceededInstanceState(
                 cloudifyEvent.getContext().getOperation());
         if (newInstanceState == null) {
           return null;
         }
         PaaSInstanceStateMonitorEvent instanceTaskStartedEvent =
             new PaaSInstanceStateMonitorEvent();
         instanceTaskStartedEvent.setInstanceId(cloudifyEvent.getContext().getNodeId());
         instanceTaskStartedEvent.setNodeTemplateId(cloudifyEvent.getContext().getNodeName());
         instanceTaskStartedEvent.setInstanceState(newInstanceState);
         instanceTaskStartedEvent.setInstanceStatus(
             statusService.getInstanceStatusFromState(newInstanceState));
         alienEvent = instanceTaskStartedEvent;
       }
       break;
     case EventType.A4C_PERSISTENT_EVENT:
       String persistentCloudifyEvent = cloudifyEvent.getMessage().getText();
       ObjectMapper objectMapper = new ObjectMapper();
       objectMapper.setPropertyNamingStrategy(
           PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
       try {
         EventAlienPersistent eventAlienPersistent =
             objectMapper.readValue(persistentCloudifyEvent, EventAlienPersistent.class);
         // query API
         // TODO make that Async
         NodeInstance instance = nodeInstanceClient.read(cloudifyEvent.getContext().getNodeId());
         String attributeValue =
             (String)
                 instance
                     .getRuntimeProperties()
                     .get(eventAlienPersistent.getPersistentResourceId());
         alienEvent =
             new PaaSInstancePersistentResourceMonitorEvent(
                 cloudifyEvent.getContext().getNodeName(),
                 cloudifyEvent.getContext().getNodeId(),
                 eventAlienPersistent.getPersistentAlienAttribute(),
                 attributeValue);
       } catch (IOException e) {
         return null;
       }
       break;
     case EventType.A4C_WORKFLOW_STARTED:
       String wfCloudifyEvent = cloudifyEvent.getMessage().getText();
       objectMapper = new ObjectMapper();
       objectMapper.setPropertyNamingStrategy(
           PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
       try {
         EventAlienWorkflowStarted eventAlienWorkflowStarted =
             objectMapper.readValue(wfCloudifyEvent, EventAlienWorkflowStarted.class);
         PaaSWorkflowStepMonitorEvent e = new PaaSWorkflowStepMonitorEvent();
         PaaSWorkflowMonitorEvent pwme = new PaaSWorkflowMonitorEvent();
         pwme.setExecutionId(cloudifyEvent.getContext().getExecutionId());
         pwme.setWorkflowId(eventAlienWorkflowStarted.getWorkflowName());
         pwme.setSubworkflow(eventAlienWorkflowStarted.getSubworkflow());
         alienEvent = pwme;
       } catch (IOException e) {
         return null;
       }
       break;
     case EventType.A4C_WORKFLOW_EVENT:
       wfCloudifyEvent = cloudifyEvent.getMessage().getText();
       objectMapper = new ObjectMapper();
       objectMapper.setPropertyNamingStrategy(
           PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
       try {
         EventAlienWorkflow eventAlienPersistent =
             objectMapper.readValue(wfCloudifyEvent, EventAlienWorkflow.class);
         PaaSWorkflowStepMonitorEvent e = new PaaSWorkflowStepMonitorEvent();
         e.setNodeId(cloudifyEvent.getContext().getNodeName());
         e.setInstanceId(cloudifyEvent.getContext().getNodeId());
         e.setStepId(eventAlienPersistent.getStepId());
         e.setStage(eventAlienPersistent.getStage());
         String workflowId = cloudifyEvent.getContext().getWorkflowId();
         e.setExecutionId(cloudifyEvent.getContext().getExecutionId());
         if (workflowId.startsWith(Workflow.A4C_PREFIX)) {
           workflowId = workflowId.substring(Workflow.A4C_PREFIX.length());
         }
         e.setWorkflowId(cloudifyEvent.getContext().getWorkflowId());
         alienEvent = e;
       } catch (IOException e) {
         return null;
       }
       break;
     default:
       return null;
   }
   alienEvent.setDate(
       DatatypeConverter.parseDateTime(cloudifyEvent.getTimestamp()).getTimeInMillis());
   String alienDeploymentId =
       paaSDeploymentIdToAlienDeploymentIdMapping.get(
           cloudifyEvent.getContext().getDeploymentId());
   if (alienDeploymentId == null) {
     if (log.isDebugEnabled()) {
       log.debug(
           "Alien deployment id is not found for paaS deployment {}, must ignore this event {}",
           cloudifyEvent.getContext().getDeploymentId(),
           cloudifyEvent);
     }
     return null;
   }
   alienEvent.setDeploymentId(alienDeploymentId);
   return alienEvent;
 }
 @Override
 public Date unmarshal(String v) throws Exception {
   return DatatypeConverter.parseDateTime(v).getTime();
 }
Example #17
0
 /**
  * @param s
  * @return
  */
 public static Date parseDateTime(String s) {
   if (s != null && !s.trim().isEmpty()) {
     return DatatypeConverter.parseDateTime(s).getTime();
   }
   return null;
 }